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);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
168 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
169 } else if (!Subtarget->useSoftFloat()) {
170 // We have an algorithm for SSE2->double, and we turn this into a
171 // 64-bit FILD followed by conditional FADD for other targets.
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 // We have an algorithm for SSE2, and we turn this into a 64-bit
174 // FILD for other targets.
175 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
178 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
180 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
183 if (!Subtarget->useSoftFloat()) {
184 // SSE has no i16 to fp conversion, only i32
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
198 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
199 // are Legal, f80 is custom lowered.
200 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (X86ScalarSSEf32) {
209 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
210 // f32 and f64 cases are Legal, f80 case is not
211 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
214 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 // Handle FP_TO_UINT by promoting the destination to a larger signed
219 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
220 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
221 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
223 if (Subtarget->is64Bit()) {
224 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
229 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 } else if (!Subtarget->useSoftFloat()) {
233 // Since AVX is a superset of SSE3, only check for SSE here.
234 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235 // Expand FP_TO_UINT into a select.
236 // FIXME: We would like to use a Custom expander here eventually to do
237 // the optimal thing for SSE vs. the default expansion in the legalizer.
238 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
240 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
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);
245 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
248 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249 if (!X86ScalarSSEf64) {
250 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
251 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
254 // Without SSE, i64->f64 goes through memory.
255 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
259 // Scalar integer divide and remainder are lowered to use operations that
260 // produce two results, to match the available instructions. This exposes
261 // the two-result form to trivial CSE, which is able to combine x/y and x%y
262 // into a single instruction.
264 // Scalar integer multiply-high is also lowered to use two-result
265 // operations, to match the available instructions. However, plain multiply
266 // (low) operations are left as Legal, as there are single-result
267 // instructions for this in x86. Using the two-result multiply instructions
268 // when both high and low results are needed must be arranged by dagcombine.
269 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
271 setOperationAction(ISD::MULHS, VT, Expand);
272 setOperationAction(ISD::MULHU, VT, Expand);
273 setOperationAction(ISD::SDIV, VT, Expand);
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SREM, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
278 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279 setOperationAction(ISD::ADDC, VT, Custom);
280 setOperationAction(ISD::ADDE, VT, Custom);
281 setOperationAction(ISD::SUBC, VT, Custom);
282 setOperationAction(ISD::SUBE, VT, Custom);
285 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
286 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
287 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
290 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
291 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
292 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
295 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
296 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
297 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
304 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
306 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
307 setOperationAction(ISD::FREM , MVT::f32 , Expand);
308 setOperationAction(ISD::FREM , MVT::f64 , Expand);
309 setOperationAction(ISD::FREM , MVT::f80 , Expand);
310 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
312 // Promote the i8 variants and force them on up to i32 which has a shorter
314 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
315 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
316 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
317 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
318 if (Subtarget->hasBMI()) {
319 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
321 if (Subtarget->is64Bit())
322 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
324 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
325 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
326 if (Subtarget->is64Bit())
327 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
330 if (Subtarget->hasLZCNT()) {
331 // When promoting the i8 variants, force them to i32 for a shorter
333 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
334 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
335 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
336 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
337 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
338 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
342 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
343 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
344 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
347 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
348 if (Subtarget->is64Bit()) {
349 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
354 // Special handling for half-precision floating point conversions.
355 // If we don't have F16C support, then lower half float conversions
356 // into library calls.
357 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
358 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
359 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
362 // There's never any support for operations beyond MVT::f32.
363 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
364 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
365 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
366 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
368 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
369 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
370 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
371 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
372 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
375 if (Subtarget->hasPOPCNT()) {
376 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
378 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
379 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
380 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
381 if (Subtarget->is64Bit())
382 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
385 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
387 if (!Subtarget->hasMOVBE())
388 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
390 // These should be promoted to a larger select which is supported.
391 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
392 // X86 wants to expand cmov itself.
393 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
394 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
395 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
396 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
397 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
398 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
399 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
400 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
401 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
402 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
403 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
404 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
405 if (Subtarget->is64Bit()) {
406 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
407 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
409 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
410 setOperationAction(ISD::CATCHRET , MVT::Other, Custom);
411 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
412 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
413 // support continuation, user-level threading, and etc.. As a result, no
414 // other SjLj exception interfaces are implemented and please don't build
415 // your own exception handling based on them.
416 // LLVM/Clang supports zero-cost DWARF exception handling.
417 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
418 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
421 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
422 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
423 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
424 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
425 if (Subtarget->is64Bit())
426 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
427 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
428 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
429 if (Subtarget->is64Bit()) {
430 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
431 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
432 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
433 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
434 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
436 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
437 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
438 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
439 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
440 if (Subtarget->is64Bit()) {
441 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
442 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
443 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
446 if (Subtarget->hasSSE1())
447 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
449 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
451 // Expand certain atomics
452 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
454 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
455 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
456 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
459 if (Subtarget->hasCmpxchg16b()) {
460 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
463 // FIXME - use subtarget debug flags
464 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
465 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
466 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
469 if (Subtarget->isTarget64BitLP64()) {
470 setExceptionPointerRegister(X86::RAX);
471 setExceptionSelectorRegister(X86::RDX);
473 setExceptionPointerRegister(X86::EAX);
474 setExceptionSelectorRegister(X86::EDX);
476 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
477 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
479 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
480 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
482 setOperationAction(ISD::TRAP, MVT::Other, Legal);
483 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
485 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
486 setOperationAction(ISD::VASTART , MVT::Other, Custom);
487 setOperationAction(ISD::VAEND , MVT::Other, Expand);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::VAARG , MVT::Other, Custom);
490 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
492 // TargetInfo::CharPtrBuiltinVaList
493 setOperationAction(ISD::VAARG , MVT::Other, Expand);
494 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
497 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
498 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
500 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
502 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
503 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
504 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
506 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
507 // f32 and f64 use SSE.
508 // Set up the FP register classes.
509 addRegisterClass(MVT::f32, &X86::FR32RegClass);
510 addRegisterClass(MVT::f64, &X86::FR64RegClass);
512 // Use ANDPD to simulate FABS.
513 setOperationAction(ISD::FABS , MVT::f64, Custom);
514 setOperationAction(ISD::FABS , MVT::f32, Custom);
516 // Use XORP to simulate FNEG.
517 setOperationAction(ISD::FNEG , MVT::f64, Custom);
518 setOperationAction(ISD::FNEG , MVT::f32, Custom);
520 // Use ANDPD and ORPD to simulate FCOPYSIGN.
521 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
522 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
524 // Lower this to FGETSIGNx86 plus an AND.
525 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
526 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
528 // We don't support sin/cos/fmod
529 setOperationAction(ISD::FSIN , MVT::f64, Expand);
530 setOperationAction(ISD::FCOS , MVT::f64, Expand);
531 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
532 setOperationAction(ISD::FSIN , MVT::f32, Expand);
533 setOperationAction(ISD::FCOS , MVT::f32, Expand);
534 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
536 // Expand FP immediates into loads from the stack, except for the special
538 addLegalFPImmediate(APFloat(+0.0)); // xorpd
539 addLegalFPImmediate(APFloat(+0.0f)); // xorps
540 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
541 // Use SSE for f32, x87 for f64.
542 // Set up the FP register classes.
543 addRegisterClass(MVT::f32, &X86::FR32RegClass);
544 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
546 // Use ANDPS to simulate FABS.
547 setOperationAction(ISD::FABS , MVT::f32, Custom);
549 // Use XORP to simulate FNEG.
550 setOperationAction(ISD::FNEG , MVT::f32, Custom);
552 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
554 // Use ANDPS and ORPS to simulate FCOPYSIGN.
555 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
556 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
558 // We don't support sin/cos/fmod
559 setOperationAction(ISD::FSIN , MVT::f32, Expand);
560 setOperationAction(ISD::FCOS , MVT::f32, Expand);
561 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
563 // Special cases we handle for FP constants.
564 addLegalFPImmediate(APFloat(+0.0f)); // xorps
565 addLegalFPImmediate(APFloat(+0.0)); // FLD0
566 addLegalFPImmediate(APFloat(+1.0)); // FLD1
567 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
568 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
570 if (!TM.Options.UnsafeFPMath) {
571 setOperationAction(ISD::FSIN , MVT::f64, Expand);
572 setOperationAction(ISD::FCOS , MVT::f64, Expand);
573 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
575 } else if (!Subtarget->useSoftFloat()) {
576 // f32 and f64 in x87.
577 // Set up the FP register classes.
578 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
579 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
581 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
582 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
583 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
584 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
586 if (!TM.Options.UnsafeFPMath) {
587 setOperationAction(ISD::FSIN , MVT::f64, Expand);
588 setOperationAction(ISD::FSIN , MVT::f32, Expand);
589 setOperationAction(ISD::FCOS , MVT::f64, Expand);
590 setOperationAction(ISD::FCOS , MVT::f32, Expand);
591 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
592 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
594 addLegalFPImmediate(APFloat(+0.0)); // FLD0
595 addLegalFPImmediate(APFloat(+1.0)); // FLD1
596 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
597 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
598 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
599 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
600 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
601 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
604 // We don't support FMA.
605 setOperationAction(ISD::FMA, MVT::f64, Expand);
606 setOperationAction(ISD::FMA, MVT::f32, Expand);
608 // Long double always uses X87.
609 if (!Subtarget->useSoftFloat()) {
610 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
611 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
612 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
614 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
615 addLegalFPImmediate(TmpFlt); // FLD0
617 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
620 APFloat TmpFlt2(+1.0);
621 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
623 addLegalFPImmediate(TmpFlt2); // FLD1
624 TmpFlt2.changeSign();
625 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
628 if (!TM.Options.UnsafeFPMath) {
629 setOperationAction(ISD::FSIN , MVT::f80, Expand);
630 setOperationAction(ISD::FCOS , MVT::f80, Expand);
631 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
634 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
635 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
636 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
637 setOperationAction(ISD::FRINT, MVT::f80, Expand);
638 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
639 setOperationAction(ISD::FMA, MVT::f80, Expand);
642 // Always use a library call for pow.
643 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
644 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
645 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
647 setOperationAction(ISD::FLOG, MVT::f80, Expand);
648 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
649 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
650 setOperationAction(ISD::FEXP, MVT::f80, Expand);
651 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
652 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
653 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
655 // First set operation action for all vector types to either promote
656 // (for widening) or expand (for scalarization). Then we will selectively
657 // turn on ones that can be effectively codegen'd.
658 for (MVT VT : MVT::vector_valuetypes()) {
659 setOperationAction(ISD::ADD , VT, Expand);
660 setOperationAction(ISD::SUB , VT, Expand);
661 setOperationAction(ISD::FADD, VT, Expand);
662 setOperationAction(ISD::FNEG, VT, Expand);
663 setOperationAction(ISD::FSUB, VT, Expand);
664 setOperationAction(ISD::MUL , VT, Expand);
665 setOperationAction(ISD::FMUL, VT, Expand);
666 setOperationAction(ISD::SDIV, VT, Expand);
667 setOperationAction(ISD::UDIV, VT, Expand);
668 setOperationAction(ISD::FDIV, VT, Expand);
669 setOperationAction(ISD::SREM, VT, Expand);
670 setOperationAction(ISD::UREM, VT, Expand);
671 setOperationAction(ISD::LOAD, VT, Expand);
672 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
673 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
674 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
675 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
676 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
677 setOperationAction(ISD::FABS, VT, Expand);
678 setOperationAction(ISD::FSIN, VT, Expand);
679 setOperationAction(ISD::FSINCOS, VT, Expand);
680 setOperationAction(ISD::FCOS, VT, Expand);
681 setOperationAction(ISD::FSINCOS, VT, Expand);
682 setOperationAction(ISD::FREM, VT, Expand);
683 setOperationAction(ISD::FMA, VT, Expand);
684 setOperationAction(ISD::FPOWI, VT, Expand);
685 setOperationAction(ISD::FSQRT, VT, Expand);
686 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
687 setOperationAction(ISD::FFLOOR, VT, Expand);
688 setOperationAction(ISD::FCEIL, VT, Expand);
689 setOperationAction(ISD::FTRUNC, VT, Expand);
690 setOperationAction(ISD::FRINT, VT, Expand);
691 setOperationAction(ISD::FNEARBYINT, VT, Expand);
692 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
693 setOperationAction(ISD::MULHS, VT, Expand);
694 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
695 setOperationAction(ISD::MULHU, VT, Expand);
696 setOperationAction(ISD::SDIVREM, VT, Expand);
697 setOperationAction(ISD::UDIVREM, VT, Expand);
698 setOperationAction(ISD::FPOW, VT, Expand);
699 setOperationAction(ISD::CTPOP, VT, Expand);
700 setOperationAction(ISD::CTTZ, VT, Expand);
701 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
702 setOperationAction(ISD::CTLZ, VT, Expand);
703 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
704 setOperationAction(ISD::SHL, VT, Expand);
705 setOperationAction(ISD::SRA, VT, Expand);
706 setOperationAction(ISD::SRL, VT, Expand);
707 setOperationAction(ISD::ROTL, VT, Expand);
708 setOperationAction(ISD::ROTR, VT, Expand);
709 setOperationAction(ISD::BSWAP, VT, Expand);
710 setOperationAction(ISD::SETCC, VT, Expand);
711 setOperationAction(ISD::FLOG, VT, Expand);
712 setOperationAction(ISD::FLOG2, VT, Expand);
713 setOperationAction(ISD::FLOG10, VT, Expand);
714 setOperationAction(ISD::FEXP, VT, Expand);
715 setOperationAction(ISD::FEXP2, VT, Expand);
716 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
717 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
718 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
719 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
720 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
721 setOperationAction(ISD::TRUNCATE, VT, Expand);
722 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
723 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
724 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
725 setOperationAction(ISD::VSELECT, VT, Expand);
726 setOperationAction(ISD::SELECT_CC, VT, Expand);
727 for (MVT InnerVT : MVT::vector_valuetypes()) {
728 setTruncStoreAction(InnerVT, VT, Expand);
730 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
731 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
733 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
734 // types, we have to deal with them whether we ask for Expansion or not.
735 // Setting Expand causes its own optimisation problems though, so leave
737 if (VT.getVectorElementType() == MVT::i1)
738 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
740 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
741 // split/scalarized right now.
742 if (VT.getVectorElementType() == MVT::f16)
743 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
748 // with -msoft-float, disable use of MMX as well.
749 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
750 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
751 // No operations on x86mmx supported, everything uses intrinsics.
754 // MMX-sized vectors (other than x86mmx) are expected to be expanded
755 // into smaller operations.
756 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
757 setOperationAction(ISD::MULHS, MMXTy, Expand);
758 setOperationAction(ISD::AND, MMXTy, Expand);
759 setOperationAction(ISD::OR, MMXTy, Expand);
760 setOperationAction(ISD::XOR, MMXTy, Expand);
761 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
762 setOperationAction(ISD::SELECT, MMXTy, Expand);
763 setOperationAction(ISD::BITCAST, MMXTy, Expand);
765 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
767 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
768 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
770 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
771 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
772 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
773 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
774 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
775 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
776 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
777 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
778 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
780 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
781 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
782 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
783 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
786 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
787 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
789 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
790 // registers cannot be used even for integer operations.
791 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
792 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
793 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
794 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
796 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
797 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
798 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
799 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
800 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
801 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
802 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
803 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
804 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
805 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
806 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
807 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
808 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
809 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
810 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
811 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
812 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
813 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
814 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
815 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
816 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
817 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
818 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
820 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
821 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
822 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
823 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
825 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
826 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
827 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
828 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
836 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
837 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
838 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
839 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
841 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
842 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
843 MVT VT = (MVT::SimpleValueType)i;
844 // Do not attempt to custom lower non-power-of-2 vectors
845 if (!isPowerOf2_32(VT.getVectorNumElements()))
847 // Do not attempt to custom lower non-128-bit vectors
848 if (!VT.is128BitVector())
850 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
851 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
852 setOperationAction(ISD::VSELECT, VT, Custom);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
856 // We support custom legalizing of sext and anyext loads for specific
857 // memory vector types which we can load as a scalar (or sequence of
858 // scalars) and extend in-register to a legal 128-bit vector type. For sext
859 // loads these must work with a single scalar load.
860 for (MVT VT : MVT::integer_vector_valuetypes()) {
861 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
862 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
863 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
864 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
865 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
866 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
867 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
868 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
869 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
873 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
875 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
876 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
877 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
878 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
879 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
881 if (Subtarget->is64Bit()) {
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
886 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
887 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
888 MVT VT = (MVT::SimpleValueType)i;
890 // Do not attempt to promote non-128-bit vectors
891 if (!VT.is128BitVector())
894 setOperationAction(ISD::AND, VT, Promote);
895 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
896 setOperationAction(ISD::OR, VT, Promote);
897 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
898 setOperationAction(ISD::XOR, VT, Promote);
899 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
900 setOperationAction(ISD::LOAD, VT, Promote);
901 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
902 setOperationAction(ISD::SELECT, VT, Promote);
903 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
906 // Custom lower v2i64 and v2f64 selects.
907 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
908 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
909 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
910 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
912 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
913 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
915 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
917 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
918 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
919 // As there is no 64-bit GPR available, we need build a special custom
920 // sequence to convert from v2i32 to v2f32.
921 if (!Subtarget->is64Bit())
922 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
924 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
925 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
927 for (MVT VT : MVT::fp_vector_valuetypes())
928 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
930 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
931 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
932 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
935 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
936 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
937 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
938 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
939 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
940 setOperationAction(ISD::FRINT, RoundedTy, Legal);
941 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
944 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
945 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
946 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
947 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
948 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
949 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
950 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
951 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
953 // FIXME: Do we need to handle scalar-to-vector here?
954 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
956 // We directly match byte blends in the backend as they match the VSELECT
958 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
960 // SSE41 brings specific instructions for doing vector sign extend even in
961 // cases where we don't have SRA.
962 for (MVT VT : MVT::integer_vector_valuetypes()) {
963 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
964 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
965 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
968 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
969 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
971 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
972 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
976 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
978 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
979 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983 // i8 and i16 vectors are custom because the source register and source
984 // source memory operand types are not the same width. f32 vectors are
985 // custom since the immediate controlling the insert encodes additional
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
997 // FIXME: these should be Legal, but that's only for the case where
998 // the index is constant. For now custom expand to deal with that.
999 if (Subtarget->is64Bit()) {
1000 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1005 if (Subtarget->hasSSE2()) {
1006 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1007 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1008 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1010 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1013 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1016 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1017 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1019 // In the customized shift lowering, the legal cases in AVX2 will be
1021 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1022 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1024 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1025 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1027 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1028 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1031 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1032 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1039 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1043 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1054 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1056 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1067 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1069 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1070 // even though v8i16 is a legal type.
1071 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1072 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1073 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1075 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1076 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1077 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1079 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1080 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1082 for (MVT VT : MVT::fp_vector_valuetypes())
1083 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1085 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1086 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1088 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1089 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1091 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1092 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1094 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1097 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1099 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1100 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1101 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1103 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1104 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1105 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1106 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1107 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1108 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1109 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1110 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1111 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1112 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1113 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1114 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1116 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1117 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1118 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1119 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1121 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1122 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1123 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1124 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1125 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1126 setOperationAction(ISD::FMA, MVT::f32, Legal);
1127 setOperationAction(ISD::FMA, MVT::f64, Legal);
1130 if (Subtarget->hasInt256()) {
1131 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1132 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1133 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1134 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1136 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1137 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1138 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1139 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1141 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1142 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1143 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1144 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1146 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1147 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1148 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1149 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1151 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1152 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1153 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1154 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1155 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1156 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1158 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1159 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1160 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1161 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1162 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1164 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1165 // when we have a 256bit-wide blend with immediate.
1166 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1168 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1169 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1170 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1171 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1172 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1173 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1174 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1176 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1177 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1178 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1179 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1180 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1181 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1183 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1184 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1185 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1186 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1188 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1190 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1193 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1194 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1195 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1196 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1198 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1199 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1200 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1201 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1202 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1203 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1204 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1205 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1206 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1207 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1208 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1209 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1212 // In the customized shift lowering, the legal cases in AVX2 will be
1214 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1215 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1217 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1218 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1220 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1221 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1223 // Custom lower several nodes for 256-bit types.
1224 for (MVT VT : MVT::vector_valuetypes()) {
1225 if (VT.getScalarSizeInBits() >= 32) {
1226 setOperationAction(ISD::MLOAD, VT, Legal);
1227 setOperationAction(ISD::MSTORE, VT, Legal);
1229 // Extract subvector is special because the value type
1230 // (result) is 128-bit but the source is 256-bit wide.
1231 if (VT.is128BitVector()) {
1232 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1234 // Do not attempt to custom lower other non-256-bit vectors
1235 if (!VT.is256BitVector())
1238 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1239 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1240 setOperationAction(ISD::VSELECT, VT, Custom);
1241 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1242 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1243 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1244 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1245 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1248 if (Subtarget->hasInt256())
1249 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1252 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254 MVT VT = (MVT::SimpleValueType)i;
1256 // Do not attempt to promote non-256-bit vectors
1257 if (!VT.is256BitVector())
1260 setOperationAction(ISD::AND, VT, Promote);
1261 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1262 setOperationAction(ISD::OR, VT, Promote);
1263 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1264 setOperationAction(ISD::XOR, VT, Promote);
1265 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1266 setOperationAction(ISD::LOAD, VT, Promote);
1267 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1268 setOperationAction(ISD::SELECT, VT, Promote);
1269 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1273 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1274 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1275 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1276 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1277 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1279 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1280 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1281 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1283 for (MVT VT : MVT::fp_vector_valuetypes())
1284 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1286 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1287 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1288 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1289 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1290 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1291 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1292 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1293 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1294 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1295 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1296 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1297 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1299 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1300 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1301 setOperationAction(ISD::XOR, MVT::i1, Legal);
1302 setOperationAction(ISD::OR, MVT::i1, Legal);
1303 setOperationAction(ISD::AND, MVT::i1, Legal);
1304 setOperationAction(ISD::SUB, MVT::i1, Custom);
1305 setOperationAction(ISD::ADD, MVT::i1, Custom);
1306 setOperationAction(ISD::MUL, MVT::i1, Custom);
1307 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1308 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1309 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1310 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1311 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1313 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1314 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1315 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1316 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1317 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1318 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1320 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1321 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1322 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1323 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1324 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1325 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1326 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1327 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1329 // FIXME: [US]INT_TO_FP are not legal for f80.
1330 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1331 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1332 if (Subtarget->is64Bit()) {
1333 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1334 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1336 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1337 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1338 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1339 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1340 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1341 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1343 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1344 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1347 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1348 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1349 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1350 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1351 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1353 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1354 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1355 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1356 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1357 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1358 if (Subtarget->hasVLX()){
1359 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1360 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1361 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1362 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1363 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1365 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1366 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1367 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1368 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1369 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1371 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1372 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1373 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1374 if (Subtarget->hasDQI()) {
1375 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1376 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1380 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1381 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1382 if (Subtarget->hasVLX()) {
1383 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1384 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1385 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1386 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1387 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1388 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1389 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1390 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1393 if (Subtarget->hasVLX()) {
1394 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1395 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1396 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1397 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1398 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1399 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1400 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1401 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1403 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1404 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1405 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1406 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1407 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1408 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1409 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1412 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1413 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1414 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1415 if (Subtarget->hasDQI()) {
1416 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1417 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1419 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1423 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1424 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1425 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1426 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1427 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1428 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1430 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1431 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1432 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1433 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1434 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1436 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1437 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1439 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1441 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1442 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1443 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1444 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1445 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1446 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1448 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1449 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1450 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1451 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1453 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1454 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1455 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1456 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1457 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1458 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1459 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1460 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1463 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1465 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1466 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1468 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1470 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1471 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1473 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1474 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1476 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1477 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1479 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1480 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1482 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1483 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1484 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1486 if (Subtarget->hasCDI()) {
1487 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1488 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1490 if (Subtarget->hasDQI()) {
1491 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1492 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1493 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1495 // Custom lower several nodes.
1496 for (MVT VT : MVT::vector_valuetypes()) {
1497 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1499 setOperationAction(ISD::AND, VT, Legal);
1500 setOperationAction(ISD::OR, VT, Legal);
1501 setOperationAction(ISD::XOR, VT, Legal);
1503 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1504 setOperationAction(ISD::MGATHER, VT, Custom);
1505 setOperationAction(ISD::MSCATTER, VT, Custom);
1507 // Extract subvector is special because the value type
1508 // (result) is 256/128-bit but the source is 512-bit wide.
1509 if (VT.is128BitVector() || VT.is256BitVector()) {
1510 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1512 if (VT.getVectorElementType() == MVT::i1)
1513 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1515 // Do not attempt to custom lower other non-512-bit vectors
1516 if (!VT.is512BitVector())
1519 if (EltSize >= 32) {
1520 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1521 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1522 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1523 setOperationAction(ISD::VSELECT, VT, Legal);
1524 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1525 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1526 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1527 setOperationAction(ISD::MLOAD, VT, Legal);
1528 setOperationAction(ISD::MSTORE, VT, Legal);
1531 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1532 MVT VT = (MVT::SimpleValueType)i;
1534 // Do not attempt to promote non-512-bit vectors.
1535 if (!VT.is512BitVector())
1538 setOperationAction(ISD::SELECT, VT, Promote);
1539 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1543 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1544 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1545 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1547 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1548 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1550 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1551 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1552 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1553 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1554 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1555 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1556 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1557 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1558 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1559 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1560 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1561 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1562 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1563 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1564 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1565 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1566 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1567 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1568 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1569 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1570 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1571 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1572 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1573 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1574 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1575 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1576 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1577 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1578 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1579 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1581 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1582 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1583 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1584 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1585 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1586 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1587 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1588 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1590 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1591 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1592 if (Subtarget->hasVLX())
1593 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1595 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1596 const MVT VT = (MVT::SimpleValueType)i;
1598 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1600 // Do not attempt to promote non-512-bit vectors.
1601 if (!VT.is512BitVector())
1605 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1606 setOperationAction(ISD::VSELECT, VT, Legal);
1611 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1612 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1613 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1615 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1616 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1617 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1618 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1619 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1620 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1621 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1622 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1623 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1624 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1626 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1627 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1628 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1629 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1630 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1631 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1632 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1633 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1635 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1636 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1637 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1638 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1639 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1640 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1641 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1642 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1645 // We want to custom lower some of our intrinsics.
1646 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1647 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1648 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1649 if (!Subtarget->is64Bit())
1650 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1652 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1653 // handle type legalization for these operations here.
1655 // FIXME: We really should do custom legalization for addition and
1656 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1657 // than generic legalization for 64-bit multiplication-with-overflow, though.
1658 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1659 // Add/Sub/Mul with overflow operations are custom lowered.
1661 setOperationAction(ISD::SADDO, VT, Custom);
1662 setOperationAction(ISD::UADDO, VT, Custom);
1663 setOperationAction(ISD::SSUBO, VT, Custom);
1664 setOperationAction(ISD::USUBO, VT, Custom);
1665 setOperationAction(ISD::SMULO, VT, Custom);
1666 setOperationAction(ISD::UMULO, VT, Custom);
1670 if (!Subtarget->is64Bit()) {
1671 // These libcalls are not available in 32-bit.
1672 setLibcallName(RTLIB::SHL_I128, nullptr);
1673 setLibcallName(RTLIB::SRL_I128, nullptr);
1674 setLibcallName(RTLIB::SRA_I128, nullptr);
1677 // Combine sin / cos into one node or libcall if possible.
1678 if (Subtarget->hasSinCos()) {
1679 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1680 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1681 if (Subtarget->isTargetDarwin()) {
1682 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1683 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1684 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1685 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1689 if (Subtarget->isTargetWin64()) {
1690 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1691 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1692 setOperationAction(ISD::SREM, MVT::i128, Custom);
1693 setOperationAction(ISD::UREM, MVT::i128, Custom);
1694 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1695 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1698 // We have target-specific dag combine patterns for the following nodes:
1699 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1700 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1701 setTargetDAGCombine(ISD::BITCAST);
1702 setTargetDAGCombine(ISD::VSELECT);
1703 setTargetDAGCombine(ISD::SELECT);
1704 setTargetDAGCombine(ISD::SHL);
1705 setTargetDAGCombine(ISD::SRA);
1706 setTargetDAGCombine(ISD::SRL);
1707 setTargetDAGCombine(ISD::OR);
1708 setTargetDAGCombine(ISD::AND);
1709 setTargetDAGCombine(ISD::ADD);
1710 setTargetDAGCombine(ISD::FADD);
1711 setTargetDAGCombine(ISD::FSUB);
1712 setTargetDAGCombine(ISD::FMA);
1713 setTargetDAGCombine(ISD::SUB);
1714 setTargetDAGCombine(ISD::LOAD);
1715 setTargetDAGCombine(ISD::MLOAD);
1716 setTargetDAGCombine(ISD::STORE);
1717 setTargetDAGCombine(ISD::MSTORE);
1718 setTargetDAGCombine(ISD::ZERO_EXTEND);
1719 setTargetDAGCombine(ISD::ANY_EXTEND);
1720 setTargetDAGCombine(ISD::SIGN_EXTEND);
1721 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1722 setTargetDAGCombine(ISD::SINT_TO_FP);
1723 setTargetDAGCombine(ISD::UINT_TO_FP);
1724 setTargetDAGCombine(ISD::SETCC);
1725 setTargetDAGCombine(ISD::BUILD_VECTOR);
1726 setTargetDAGCombine(ISD::MUL);
1727 setTargetDAGCombine(ISD::XOR);
1729 computeRegisterProperties(Subtarget->getRegisterInfo());
1731 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1732 MaxStoresPerMemsetOptSize = 8;
1733 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1734 MaxStoresPerMemcpyOptSize = 4;
1735 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1736 MaxStoresPerMemmoveOptSize = 4;
1737 setPrefLoopAlignment(4); // 2^4 bytes.
1739 // Predictable cmov don't hurt on atom because it's in-order.
1740 PredictableSelectIsExpensive = !Subtarget->isAtom();
1741 EnableExtLdPromotion = true;
1742 setPrefFunctionAlignment(4); // 2^4 bytes.
1744 verifyIntrinsicTables();
1747 // This has so far only been implemented for 64-bit MachO.
1748 bool X86TargetLowering::useLoadStackGuardNode() const {
1749 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1752 TargetLoweringBase::LegalizeTypeAction
1753 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1754 if (ExperimentalVectorWideningLegalization &&
1755 VT.getVectorNumElements() != 1 &&
1756 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1757 return TypeWidenVector;
1759 return TargetLoweringBase::getPreferredVectorAction(VT);
1762 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1765 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1767 const unsigned NumElts = VT.getVectorNumElements();
1768 const EVT EltVT = VT.getVectorElementType();
1769 if (VT.is512BitVector()) {
1770 if (Subtarget->hasAVX512())
1771 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1772 EltVT == MVT::f32 || EltVT == MVT::f64)
1774 case 8: return MVT::v8i1;
1775 case 16: return MVT::v16i1;
1777 if (Subtarget->hasBWI())
1778 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1780 case 32: return MVT::v32i1;
1781 case 64: return MVT::v64i1;
1785 if (VT.is256BitVector() || VT.is128BitVector()) {
1786 if (Subtarget->hasVLX())
1787 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1788 EltVT == MVT::f32 || EltVT == MVT::f64)
1790 case 2: return MVT::v2i1;
1791 case 4: return MVT::v4i1;
1792 case 8: return MVT::v8i1;
1794 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1795 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1797 case 8: return MVT::v8i1;
1798 case 16: return MVT::v16i1;
1799 case 32: return MVT::v32i1;
1803 return VT.changeVectorElementTypeToInteger();
1806 /// Helper for getByValTypeAlignment to determine
1807 /// the desired ByVal argument alignment.
1808 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1811 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1812 if (VTy->getBitWidth() == 128)
1814 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1815 unsigned EltAlign = 0;
1816 getMaxByValAlign(ATy->getElementType(), EltAlign);
1817 if (EltAlign > MaxAlign)
1818 MaxAlign = EltAlign;
1819 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1820 for (auto *EltTy : STy->elements()) {
1821 unsigned EltAlign = 0;
1822 getMaxByValAlign(EltTy, EltAlign);
1823 if (EltAlign > MaxAlign)
1824 MaxAlign = EltAlign;
1831 /// Return the desired alignment for ByVal aggregate
1832 /// function arguments in the caller parameter area. For X86, aggregates
1833 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1834 /// are at 4-byte boundaries.
1835 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1836 const DataLayout &DL) const {
1837 if (Subtarget->is64Bit()) {
1838 // Max of 8 and alignment of type.
1839 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1846 if (Subtarget->hasSSE1())
1847 getMaxByValAlign(Ty, Align);
1851 /// Returns the target specific optimal type for load
1852 /// and store operations as a result of memset, memcpy, and memmove
1853 /// lowering. If DstAlign is zero that means it's safe to destination
1854 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1855 /// means there isn't a need to check it against alignment requirement,
1856 /// probably because the source does not need to be loaded. If 'IsMemset' is
1857 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1858 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1859 /// source is constant so it does not need to be loaded.
1860 /// It returns EVT::Other if the type should be determined using generic
1861 /// target-independent logic.
1863 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1864 unsigned DstAlign, unsigned SrcAlign,
1865 bool IsMemset, bool ZeroMemset,
1867 MachineFunction &MF) const {
1868 const Function *F = MF.getFunction();
1869 if ((!IsMemset || ZeroMemset) &&
1870 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1872 (!Subtarget->isUnalignedMem16Slow() ||
1873 ((DstAlign == 0 || DstAlign >= 16) &&
1874 (SrcAlign == 0 || SrcAlign >= 16)))) {
1876 // FIXME: Check if unaligned 32-byte accesses are slow.
1877 if (Subtarget->hasInt256())
1879 if (Subtarget->hasFp256())
1882 if (Subtarget->hasSSE2())
1884 if (Subtarget->hasSSE1())
1886 } else if (!MemcpyStrSrc && Size >= 8 &&
1887 !Subtarget->is64Bit() &&
1888 Subtarget->hasSSE2()) {
1889 // Do not use f64 to lower memcpy if source is string constant. It's
1890 // better to use i32 to avoid the loads.
1894 // This is a compromise. If we reach here, unaligned accesses may be slow on
1895 // this target. However, creating smaller, aligned accesses could be even
1896 // slower and would certainly be a lot more code.
1897 if (Subtarget->is64Bit() && Size >= 8)
1902 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1904 return X86ScalarSSEf32;
1905 else if (VT == MVT::f64)
1906 return X86ScalarSSEf64;
1911 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1916 if (VT.getSizeInBits() == 256)
1917 *Fast = !Subtarget->isUnalignedMem32Slow();
1919 // FIXME: We should always return that 8-byte and under accesses are fast.
1920 // That is what other x86 lowering code assumes.
1921 *Fast = !Subtarget->isUnalignedMem16Slow();
1926 /// Return the entry encoding for a jump table in the
1927 /// current function. The returned value is a member of the
1928 /// MachineJumpTableInfo::JTEntryKind enum.
1929 unsigned X86TargetLowering::getJumpTableEncoding() const {
1930 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1932 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1933 Subtarget->isPICStyleGOT())
1934 return MachineJumpTableInfo::EK_Custom32;
1936 // Otherwise, use the normal jump table encoding heuristics.
1937 return TargetLowering::getJumpTableEncoding();
1940 bool X86TargetLowering::useSoftFloat() const {
1941 return Subtarget->useSoftFloat();
1945 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1946 const MachineBasicBlock *MBB,
1947 unsigned uid,MCContext &Ctx) const{
1948 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1949 Subtarget->isPICStyleGOT());
1950 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1952 return MCSymbolRefExpr::create(MBB->getSymbol(),
1953 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1956 /// Returns relocation base for the given PIC jumptable.
1957 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1958 SelectionDAG &DAG) const {
1959 if (!Subtarget->is64Bit())
1960 // This doesn't have SDLoc associated with it, but is not really the
1961 // same as a Register.
1962 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1963 getPointerTy(DAG.getDataLayout()));
1967 /// This returns the relocation base for the given PIC jumptable,
1968 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1969 const MCExpr *X86TargetLowering::
1970 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1971 MCContext &Ctx) const {
1972 // X86-64 uses RIP relative addressing based on the jump table label.
1973 if (Subtarget->isPICStyleRIPRel())
1974 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1976 // Otherwise, the reference is relative to the PIC base.
1977 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1980 std::pair<const TargetRegisterClass *, uint8_t>
1981 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1983 const TargetRegisterClass *RRC = nullptr;
1985 switch (VT.SimpleTy) {
1987 return TargetLowering::findRepresentativeClass(TRI, VT);
1988 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1989 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1992 RRC = &X86::VR64RegClass;
1994 case MVT::f32: case MVT::f64:
1995 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1996 case MVT::v4f32: case MVT::v2f64:
1997 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1999 RRC = &X86::VR128RegClass;
2002 return std::make_pair(RRC, Cost);
2005 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2006 unsigned &Offset) const {
2007 if (!Subtarget->isTargetLinux())
2010 if (Subtarget->is64Bit()) {
2011 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2013 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2025 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2026 unsigned DestAS) const {
2027 assert(SrcAS != DestAS && "Expected different address spaces!");
2029 return SrcAS < 256 && DestAS < 256;
2032 //===----------------------------------------------------------------------===//
2033 // Return Value Calling Convention Implementation
2034 //===----------------------------------------------------------------------===//
2036 #include "X86GenCallingConv.inc"
2039 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2040 MachineFunction &MF, bool isVarArg,
2041 const SmallVectorImpl<ISD::OutputArg> &Outs,
2042 LLVMContext &Context) const {
2043 SmallVector<CCValAssign, 16> RVLocs;
2044 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2045 return CCInfo.CheckReturn(Outs, RetCC_X86);
2048 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2049 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2054 X86TargetLowering::LowerReturn(SDValue Chain,
2055 CallingConv::ID CallConv, bool isVarArg,
2056 const SmallVectorImpl<ISD::OutputArg> &Outs,
2057 const SmallVectorImpl<SDValue> &OutVals,
2058 SDLoc dl, SelectionDAG &DAG) const {
2059 MachineFunction &MF = DAG.getMachineFunction();
2060 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2062 SmallVector<CCValAssign, 16> RVLocs;
2063 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2064 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2067 SmallVector<SDValue, 6> RetOps;
2068 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2069 // Operand #1 = Bytes To Pop
2070 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2073 // Copy the result values into the output registers.
2074 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2075 CCValAssign &VA = RVLocs[i];
2076 assert(VA.isRegLoc() && "Can only return in registers!");
2077 SDValue ValToCopy = OutVals[i];
2078 EVT ValVT = ValToCopy.getValueType();
2080 // Promote values to the appropriate types.
2081 if (VA.getLocInfo() == CCValAssign::SExt)
2082 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2083 else if (VA.getLocInfo() == CCValAssign::ZExt)
2084 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2085 else if (VA.getLocInfo() == CCValAssign::AExt) {
2086 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2087 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2089 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2091 else if (VA.getLocInfo() == CCValAssign::BCvt)
2092 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2094 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2095 "Unexpected FP-extend for return value.");
2097 // If this is x86-64, and we disabled SSE, we can't return FP values,
2098 // or SSE or MMX vectors.
2099 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2100 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2101 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2102 report_fatal_error("SSE register return with SSE disabled");
2104 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2105 // llvm-gcc has never done it right and no one has noticed, so this
2106 // should be OK for now.
2107 if (ValVT == MVT::f64 &&
2108 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2109 report_fatal_error("SSE2 register return with SSE2 disabled");
2111 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2112 // the RET instruction and handled by the FP Stackifier.
2113 if (VA.getLocReg() == X86::FP0 ||
2114 VA.getLocReg() == X86::FP1) {
2115 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2116 // change the value to the FP stack register class.
2117 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2118 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2119 RetOps.push_back(ValToCopy);
2120 // Don't emit a copytoreg.
2124 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2125 // which is returned in RAX / RDX.
2126 if (Subtarget->is64Bit()) {
2127 if (ValVT == MVT::x86mmx) {
2128 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2129 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2130 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2132 // If we don't have SSE2 available, convert to v4f32 so the generated
2133 // register is legal.
2134 if (!Subtarget->hasSSE2())
2135 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2140 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2141 Flag = Chain.getValue(1);
2142 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2145 // All x86 ABIs require that for returning structs by value we copy
2146 // the sret argument into %rax/%eax (depending on ABI) for the return.
2147 // We saved the argument into a virtual register in the entry block,
2148 // so now we copy the value out and into %rax/%eax.
2150 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2151 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2152 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2153 // either case FuncInfo->setSRetReturnReg() will have been called.
2154 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2155 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2156 getPointerTy(MF.getDataLayout()));
2159 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2160 X86::RAX : X86::EAX;
2161 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2162 Flag = Chain.getValue(1);
2164 // RAX/EAX now acts like a return value.
2166 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2169 RetOps[0] = Chain; // Update chain.
2171 // Add the flag if we have it.
2173 RetOps.push_back(Flag);
2175 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2178 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2179 if (N->getNumValues() != 1)
2181 if (!N->hasNUsesOfValue(1, 0))
2184 SDValue TCChain = Chain;
2185 SDNode *Copy = *N->use_begin();
2186 if (Copy->getOpcode() == ISD::CopyToReg) {
2187 // If the copy has a glue operand, we conservatively assume it isn't safe to
2188 // perform a tail call.
2189 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2191 TCChain = Copy->getOperand(0);
2192 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2195 bool HasRet = false;
2196 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2198 if (UI->getOpcode() != X86ISD::RET_FLAG)
2200 // If we are returning more than one value, we can definitely
2201 // not make a tail call see PR19530
2202 if (UI->getNumOperands() > 4)
2204 if (UI->getNumOperands() == 4 &&
2205 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2218 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2219 ISD::NodeType ExtendKind) const {
2221 // TODO: Is this also valid on 32-bit?
2222 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2223 ReturnMVT = MVT::i8;
2225 ReturnMVT = MVT::i32;
2227 EVT MinVT = getRegisterType(Context, ReturnMVT);
2228 return VT.bitsLT(MinVT) ? MinVT : VT;
2231 /// Lower the result values of a call into the
2232 /// appropriate copies out of appropriate physical registers.
2235 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2236 CallingConv::ID CallConv, bool isVarArg,
2237 const SmallVectorImpl<ISD::InputArg> &Ins,
2238 SDLoc dl, SelectionDAG &DAG,
2239 SmallVectorImpl<SDValue> &InVals) const {
2241 // Assign locations to each value returned by this call.
2242 SmallVector<CCValAssign, 16> RVLocs;
2243 bool Is64Bit = Subtarget->is64Bit();
2244 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2246 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2248 // Copy all of the result registers out of their specified physreg.
2249 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2250 CCValAssign &VA = RVLocs[i];
2251 EVT CopyVT = VA.getLocVT();
2253 // If this is x86-64, and we disabled SSE, we can't return FP values
2254 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2255 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2256 report_fatal_error("SSE register return with SSE disabled");
2259 // If we prefer to use the value in xmm registers, copy it out as f80 and
2260 // use a truncate to move it from fp stack reg to xmm reg.
2261 bool RoundAfterCopy = false;
2262 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2263 isScalarFPTypeInSSEReg(VA.getValVT())) {
2265 RoundAfterCopy = (CopyVT != VA.getLocVT());
2268 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2269 CopyVT, InFlag).getValue(1);
2270 SDValue Val = Chain.getValue(0);
2273 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2274 // This truncation won't change the value.
2275 DAG.getIntPtrConstant(1, dl));
2277 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2278 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2280 InFlag = Chain.getValue(2);
2281 InVals.push_back(Val);
2287 //===----------------------------------------------------------------------===//
2288 // C & StdCall & Fast Calling Convention implementation
2289 //===----------------------------------------------------------------------===//
2290 // StdCall calling convention seems to be standard for many Windows' API
2291 // routines and around. It differs from C calling convention just a little:
2292 // callee should clean up the stack, not caller. Symbols should be also
2293 // decorated in some fancy way :) It doesn't support any vector arguments.
2294 // For info on fast calling convention see Fast Calling Convention (tail call)
2295 // implementation LowerX86_32FastCCCallTo.
2297 /// CallIsStructReturn - Determines whether a call uses struct return
2299 enum StructReturnType {
2304 static StructReturnType
2305 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2307 return NotStructReturn;
2309 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2310 if (!Flags.isSRet())
2311 return NotStructReturn;
2312 if (Flags.isInReg())
2313 return RegStructReturn;
2314 return StackStructReturn;
2317 /// Determines whether a function uses struct return semantics.
2318 static StructReturnType
2319 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2321 return NotStructReturn;
2323 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2324 if (!Flags.isSRet())
2325 return NotStructReturn;
2326 if (Flags.isInReg())
2327 return RegStructReturn;
2328 return StackStructReturn;
2331 /// Make a copy of an aggregate at address specified by "Src" to address
2332 /// "Dst" with size and alignment information specified by the specific
2333 /// parameter attribute. The copy will be passed as a byval function parameter.
2335 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2336 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2338 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2340 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2341 /*isVolatile*/false, /*AlwaysInline=*/true,
2342 /*isTailCall*/false,
2343 MachinePointerInfo(), MachinePointerInfo());
2346 /// Return true if the calling convention is one that
2347 /// supports tail call optimization.
2348 static bool IsTailCallConvention(CallingConv::ID CC) {
2349 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2350 CC == CallingConv::HiPE);
2353 /// \brief Return true if the calling convention is a C calling convention.
2354 static bool IsCCallConvention(CallingConv::ID CC) {
2355 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2356 CC == CallingConv::X86_64_SysV);
2359 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2362 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2366 CallingConv::ID CalleeCC = CS.getCallingConv();
2367 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2373 /// Return true if the function is being made into
2374 /// a tailcall target by changing its ABI.
2375 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2376 bool GuaranteedTailCallOpt) {
2377 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2381 X86TargetLowering::LowerMemArgument(SDValue Chain,
2382 CallingConv::ID CallConv,
2383 const SmallVectorImpl<ISD::InputArg> &Ins,
2384 SDLoc dl, SelectionDAG &DAG,
2385 const CCValAssign &VA,
2386 MachineFrameInfo *MFI,
2388 // Create the nodes corresponding to a load from this parameter slot.
2389 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2390 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2391 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2392 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2395 // If value is passed by pointer we have address passed instead of the value
2397 bool ExtendedInMem = VA.isExtInLoc() &&
2398 VA.getValVT().getScalarType() == MVT::i1;
2400 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2401 ValVT = VA.getLocVT();
2403 ValVT = VA.getValVT();
2405 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2406 // changed with more analysis.
2407 // In case of tail call optimization mark all arguments mutable. Since they
2408 // could be overwritten by lowering of arguments in case of a tail call.
2409 if (Flags.isByVal()) {
2410 unsigned Bytes = Flags.getByValSize();
2411 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2412 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2413 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2415 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2416 VA.getLocMemOffset(), isImmutable);
2417 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2418 SDValue Val = DAG.getLoad(
2419 ValVT, dl, Chain, FIN,
2420 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2422 return ExtendedInMem ?
2423 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2427 // FIXME: Get this from tablegen.
2428 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2429 const X86Subtarget *Subtarget) {
2430 assert(Subtarget->is64Bit());
2432 if (Subtarget->isCallingConvWin64(CallConv)) {
2433 static const MCPhysReg GPR64ArgRegsWin64[] = {
2434 X86::RCX, X86::RDX, X86::R8, X86::R9
2436 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2439 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2440 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2442 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2445 // FIXME: Get this from tablegen.
2446 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2447 CallingConv::ID CallConv,
2448 const X86Subtarget *Subtarget) {
2449 assert(Subtarget->is64Bit());
2450 if (Subtarget->isCallingConvWin64(CallConv)) {
2451 // The XMM registers which might contain var arg parameters are shadowed
2452 // in their paired GPR. So we only need to save the GPR to their home
2454 // TODO: __vectorcall will change this.
2458 const Function *Fn = MF.getFunction();
2459 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2460 bool isSoftFloat = Subtarget->useSoftFloat();
2461 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2462 "SSE register cannot be used when SSE is disabled!");
2463 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2464 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2468 static const MCPhysReg XMMArgRegs64Bit[] = {
2469 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2470 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2472 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2476 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2477 CallingConv::ID CallConv,
2479 const SmallVectorImpl<ISD::InputArg> &Ins,
2482 SmallVectorImpl<SDValue> &InVals)
2484 MachineFunction &MF = DAG.getMachineFunction();
2485 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2486 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2488 const Function* Fn = MF.getFunction();
2489 if (Fn->hasExternalLinkage() &&
2490 Subtarget->isTargetCygMing() &&
2491 Fn->getName() == "main")
2492 FuncInfo->setForceFramePointer(true);
2494 MachineFrameInfo *MFI = MF.getFrameInfo();
2495 bool Is64Bit = Subtarget->is64Bit();
2496 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2498 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2499 "Var args not supported with calling convention fastcc, ghc or hipe");
2501 // Assign locations to all of the incoming arguments.
2502 SmallVector<CCValAssign, 16> ArgLocs;
2503 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2505 // Allocate shadow area for Win64
2507 CCInfo.AllocateStack(32, 8);
2509 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2511 unsigned LastVal = ~0U;
2513 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2514 CCValAssign &VA = ArgLocs[i];
2515 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2517 assert(VA.getValNo() != LastVal &&
2518 "Don't support value assigned to multiple locs yet");
2520 LastVal = VA.getValNo();
2522 if (VA.isRegLoc()) {
2523 EVT RegVT = VA.getLocVT();
2524 const TargetRegisterClass *RC;
2525 if (RegVT == MVT::i32)
2526 RC = &X86::GR32RegClass;
2527 else if (Is64Bit && RegVT == MVT::i64)
2528 RC = &X86::GR64RegClass;
2529 else if (RegVT == MVT::f32)
2530 RC = &X86::FR32RegClass;
2531 else if (RegVT == MVT::f64)
2532 RC = &X86::FR64RegClass;
2533 else if (RegVT.is512BitVector())
2534 RC = &X86::VR512RegClass;
2535 else if (RegVT.is256BitVector())
2536 RC = &X86::VR256RegClass;
2537 else if (RegVT.is128BitVector())
2538 RC = &X86::VR128RegClass;
2539 else if (RegVT == MVT::x86mmx)
2540 RC = &X86::VR64RegClass;
2541 else if (RegVT == MVT::i1)
2542 RC = &X86::VK1RegClass;
2543 else if (RegVT == MVT::v8i1)
2544 RC = &X86::VK8RegClass;
2545 else if (RegVT == MVT::v16i1)
2546 RC = &X86::VK16RegClass;
2547 else if (RegVT == MVT::v32i1)
2548 RC = &X86::VK32RegClass;
2549 else if (RegVT == MVT::v64i1)
2550 RC = &X86::VK64RegClass;
2552 llvm_unreachable("Unknown argument type!");
2554 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2555 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2557 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2558 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2560 if (VA.getLocInfo() == CCValAssign::SExt)
2561 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2562 DAG.getValueType(VA.getValVT()));
2563 else if (VA.getLocInfo() == CCValAssign::ZExt)
2564 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2565 DAG.getValueType(VA.getValVT()));
2566 else if (VA.getLocInfo() == CCValAssign::BCvt)
2567 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2569 if (VA.isExtInLoc()) {
2570 // Handle MMX values passed in XMM regs.
2571 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2572 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2574 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2577 assert(VA.isMemLoc());
2578 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2581 // If value is passed via pointer - do a load.
2582 if (VA.getLocInfo() == CCValAssign::Indirect)
2583 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2584 MachinePointerInfo(), false, false, false, 0);
2586 InVals.push_back(ArgValue);
2589 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2590 // All x86 ABIs require that for returning structs by value we copy the
2591 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2592 // the argument into a virtual register so that we can access it from the
2594 if (Ins[i].Flags.isSRet()) {
2595 unsigned Reg = FuncInfo->getSRetReturnReg();
2597 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2598 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2599 FuncInfo->setSRetReturnReg(Reg);
2601 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2602 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2607 unsigned StackSize = CCInfo.getNextStackOffset();
2608 // Align stack specially for tail calls.
2609 if (FuncIsMadeTailCallSafe(CallConv,
2610 MF.getTarget().Options.GuaranteedTailCallOpt))
2611 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2613 // If the function takes variable number of arguments, make a frame index for
2614 // the start of the first vararg value... for expansion of llvm.va_start. We
2615 // can skip this if there are no va_start calls.
2616 if (MFI->hasVAStart() &&
2617 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2618 CallConv != CallingConv::X86_ThisCall))) {
2619 FuncInfo->setVarArgsFrameIndex(
2620 MFI->CreateFixedObject(1, StackSize, true));
2623 MachineModuleInfo &MMI = MF.getMMI();
2624 const Function *WinEHParent = nullptr;
2625 if (MMI.hasWinEHFuncInfo(Fn))
2626 WinEHParent = MMI.getWinEHParent(Fn);
2627 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2628 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2630 // Figure out if XMM registers are in use.
2631 assert(!(Subtarget->useSoftFloat() &&
2632 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2633 "SSE register cannot be used when SSE is disabled!");
2635 // 64-bit calling conventions support varargs and register parameters, so we
2636 // have to do extra work to spill them in the prologue.
2637 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2638 // Find the first unallocated argument registers.
2639 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2640 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2641 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2642 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2643 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2644 "SSE register cannot be used when SSE is disabled!");
2646 // Gather all the live in physical registers.
2647 SmallVector<SDValue, 6> LiveGPRs;
2648 SmallVector<SDValue, 8> LiveXMMRegs;
2650 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2651 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2653 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2655 if (!ArgXMMs.empty()) {
2656 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2657 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2658 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2659 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2660 LiveXMMRegs.push_back(
2661 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2666 // Get to the caller-allocated home save location. Add 8 to account
2667 // for the return address.
2668 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2669 FuncInfo->setRegSaveFrameIndex(
2670 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2671 // Fixup to set vararg frame on shadow area (4 x i64).
2673 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2675 // For X86-64, if there are vararg parameters that are passed via
2676 // registers, then we must store them to their spots on the stack so
2677 // they may be loaded by deferencing the result of va_next.
2678 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2679 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2680 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2681 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2684 // Store the integer parameter registers.
2685 SmallVector<SDValue, 8> MemOps;
2686 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2687 getPointerTy(DAG.getDataLayout()));
2688 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2689 for (SDValue Val : LiveGPRs) {
2690 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2691 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2693 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2694 MachinePointerInfo::getFixedStack(
2695 DAG.getMachineFunction(),
2696 FuncInfo->getRegSaveFrameIndex(), Offset),
2698 MemOps.push_back(Store);
2702 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2703 // Now store the XMM (fp + vector) parameter registers.
2704 SmallVector<SDValue, 12> SaveXMMOps;
2705 SaveXMMOps.push_back(Chain);
2706 SaveXMMOps.push_back(ALVal);
2707 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2708 FuncInfo->getRegSaveFrameIndex(), dl));
2709 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2710 FuncInfo->getVarArgsFPOffset(), dl));
2711 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2713 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2714 MVT::Other, SaveXMMOps));
2717 if (!MemOps.empty())
2718 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2719 } else if (IsWin64 && IsWinEHOutlined) {
2720 // Get to the caller-allocated home save location. Add 8 to account
2721 // for the return address.
2722 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2723 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2724 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2726 MMI.getWinEHFuncInfo(Fn)
2727 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2728 FuncInfo->getRegSaveFrameIndex();
2730 // Store the second integer parameter (rdx) into rsp+16 relative to the
2731 // stack pointer at the entry of the function.
2732 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2733 getPointerTy(DAG.getDataLayout()));
2734 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2735 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2736 Chain = DAG.getStore(
2737 Val.getValue(1), dl, Val, RSFIN,
2738 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2739 FuncInfo->getRegSaveFrameIndex()),
2740 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2743 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2744 // Find the largest legal vector type.
2745 MVT VecVT = MVT::Other;
2746 // FIXME: Only some x86_32 calling conventions support AVX512.
2747 if (Subtarget->hasAVX512() &&
2748 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2749 CallConv == CallingConv::Intel_OCL_BI)))
2750 VecVT = MVT::v16f32;
2751 else if (Subtarget->hasAVX())
2753 else if (Subtarget->hasSSE2())
2756 // We forward some GPRs and some vector types.
2757 SmallVector<MVT, 2> RegParmTypes;
2758 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2759 RegParmTypes.push_back(IntVT);
2760 if (VecVT != MVT::Other)
2761 RegParmTypes.push_back(VecVT);
2763 // Compute the set of forwarded registers. The rest are scratch.
2764 SmallVectorImpl<ForwardedRegister> &Forwards =
2765 FuncInfo->getForwardedMustTailRegParms();
2766 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2768 // Conservatively forward AL on x86_64, since it might be used for varargs.
2769 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2770 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2771 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2774 // Copy all forwards from physical to virtual registers.
2775 for (ForwardedRegister &F : Forwards) {
2776 // FIXME: Can we use a less constrained schedule?
2777 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2778 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2779 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2783 // Some CCs need callee pop.
2784 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2785 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2786 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2788 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2789 // If this is an sret function, the return should pop the hidden pointer.
2790 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2791 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2792 argsAreStructReturn(Ins) == StackStructReturn)
2793 FuncInfo->setBytesToPopOnReturn(4);
2797 // RegSaveFrameIndex is X86-64 only.
2798 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2799 if (CallConv == CallingConv::X86_FastCall ||
2800 CallConv == CallingConv::X86_ThisCall)
2801 // fastcc functions can't have varargs.
2802 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2805 FuncInfo->setArgumentStackSize(StackSize);
2807 if (IsWinEHParent) {
2809 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2810 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2811 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2812 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2813 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2814 MachinePointerInfo::getFixedStack(
2815 DAG.getMachineFunction(), UnwindHelpFI),
2816 /*isVolatile=*/true,
2817 /*isNonTemporal=*/false, /*Alignment=*/0);
2819 // Functions using Win32 EH are considered to have opaque SP adjustments
2820 // to force local variables to be addressed from the frame or base
2822 MFI->setHasOpaqueSPAdjustment(true);
2830 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2831 SDValue StackPtr, SDValue Arg,
2832 SDLoc dl, SelectionDAG &DAG,
2833 const CCValAssign &VA,
2834 ISD::ArgFlagsTy Flags) const {
2835 unsigned LocMemOffset = VA.getLocMemOffset();
2836 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2837 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2839 if (Flags.isByVal())
2840 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2842 return DAG.getStore(
2843 Chain, dl, Arg, PtrOff,
2844 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2848 /// Emit a load of return address if tail call
2849 /// optimization is performed and it is required.
2851 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2852 SDValue &OutRetAddr, SDValue Chain,
2853 bool IsTailCall, bool Is64Bit,
2854 int FPDiff, SDLoc dl) const {
2855 // Adjust the Return address stack slot.
2856 EVT VT = getPointerTy(DAG.getDataLayout());
2857 OutRetAddr = getReturnAddressFrameIndex(DAG);
2859 // Load the "old" Return address.
2860 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2861 false, false, false, 0);
2862 return SDValue(OutRetAddr.getNode(), 1);
2865 /// Emit a store of the return address if tail call
2866 /// optimization is performed and it is required (FPDiff!=0).
2867 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2868 SDValue Chain, SDValue RetAddrFrIdx,
2869 EVT PtrVT, unsigned SlotSize,
2870 int FPDiff, SDLoc dl) {
2871 // Store the return address to the appropriate stack slot.
2872 if (!FPDiff) return Chain;
2873 // Calculate the new stack slot for the return address.
2874 int NewReturnAddrFI =
2875 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2877 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2878 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2879 MachinePointerInfo::getFixedStack(
2880 DAG.getMachineFunction(), NewReturnAddrFI),
2885 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2886 /// operation of specified width.
2887 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2889 unsigned NumElems = VT.getVectorNumElements();
2890 SmallVector<int, 8> Mask;
2891 Mask.push_back(NumElems);
2892 for (unsigned i = 1; i != NumElems; ++i)
2894 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2898 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2899 SmallVectorImpl<SDValue> &InVals) const {
2900 SelectionDAG &DAG = CLI.DAG;
2902 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2903 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2904 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2905 SDValue Chain = CLI.Chain;
2906 SDValue Callee = CLI.Callee;
2907 CallingConv::ID CallConv = CLI.CallConv;
2908 bool &isTailCall = CLI.IsTailCall;
2909 bool isVarArg = CLI.IsVarArg;
2911 MachineFunction &MF = DAG.getMachineFunction();
2912 bool Is64Bit = Subtarget->is64Bit();
2913 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2914 StructReturnType SR = callIsStructReturn(Outs);
2915 bool IsSibcall = false;
2916 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2917 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2919 if (Attr.getValueAsString() == "true")
2922 if (Subtarget->isPICStyleGOT() &&
2923 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2924 // If we are using a GOT, disable tail calls to external symbols with
2925 // default visibility. Tail calling such a symbol requires using a GOT
2926 // relocation, which forces early binding of the symbol. This breaks code
2927 // that require lazy function symbol resolution. Using musttail or
2928 // GuaranteedTailCallOpt will override this.
2929 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2930 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2931 G->getGlobal()->hasDefaultVisibility()))
2935 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2937 // Force this to be a tail call. The verifier rules are enough to ensure
2938 // that we can lower this successfully without moving the return address
2941 } else if (isTailCall) {
2942 // Check if it's really possible to do a tail call.
2943 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2944 isVarArg, SR != NotStructReturn,
2945 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2946 Outs, OutVals, Ins, DAG);
2948 // Sibcalls are automatically detected tailcalls which do not require
2950 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2957 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2958 "Var args not supported with calling convention fastcc, ghc or hipe");
2960 // Analyze operands of the call, assigning locations to each operand.
2961 SmallVector<CCValAssign, 16> ArgLocs;
2962 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2964 // Allocate shadow area for Win64
2966 CCInfo.AllocateStack(32, 8);
2968 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2970 // Get a count of how many bytes are to be pushed on the stack.
2971 unsigned NumBytes = CCInfo.getNextStackOffset();
2973 // This is a sibcall. The memory operands are available in caller's
2974 // own caller's stack.
2976 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2977 IsTailCallConvention(CallConv))
2978 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2981 if (isTailCall && !IsSibcall && !IsMustTail) {
2982 // Lower arguments at fp - stackoffset + fpdiff.
2983 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2985 FPDiff = NumBytesCallerPushed - NumBytes;
2987 // Set the delta of movement of the returnaddr stackslot.
2988 // But only set if delta is greater than previous delta.
2989 if (FPDiff < X86Info->getTCReturnAddrDelta())
2990 X86Info->setTCReturnAddrDelta(FPDiff);
2993 unsigned NumBytesToPush = NumBytes;
2994 unsigned NumBytesToPop = NumBytes;
2996 // If we have an inalloca argument, all stack space has already been allocated
2997 // for us and be right at the top of the stack. We don't support multiple
2998 // arguments passed in memory when using inalloca.
2999 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3001 if (!ArgLocs.back().isMemLoc())
3002 report_fatal_error("cannot use inalloca attribute on a register "
3004 if (ArgLocs.back().getLocMemOffset() != 0)
3005 report_fatal_error("any parameter with the inalloca attribute must be "
3006 "the only memory argument");
3010 Chain = DAG.getCALLSEQ_START(
3011 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3013 SDValue RetAddrFrIdx;
3014 // Load return address for tail calls.
3015 if (isTailCall && FPDiff)
3016 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3017 Is64Bit, FPDiff, dl);
3019 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3020 SmallVector<SDValue, 8> MemOpChains;
3023 // Walk the register/memloc assignments, inserting copies/loads. In the case
3024 // of tail call optimization arguments are handle later.
3025 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3026 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3027 // Skip inalloca arguments, they have already been written.
3028 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3029 if (Flags.isInAlloca())
3032 CCValAssign &VA = ArgLocs[i];
3033 EVT RegVT = VA.getLocVT();
3034 SDValue Arg = OutVals[i];
3035 bool isByVal = Flags.isByVal();
3037 // Promote the value if needed.
3038 switch (VA.getLocInfo()) {
3039 default: llvm_unreachable("Unknown loc info!");
3040 case CCValAssign::Full: break;
3041 case CCValAssign::SExt:
3042 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3044 case CCValAssign::ZExt:
3045 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3047 case CCValAssign::AExt:
3048 if (Arg.getValueType().isVector() &&
3049 Arg.getValueType().getScalarType() == MVT::i1)
3050 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3051 else if (RegVT.is128BitVector()) {
3052 // Special case: passing MMX values in XMM registers.
3053 Arg = DAG.getBitcast(MVT::i64, Arg);
3054 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3055 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3057 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3059 case CCValAssign::BCvt:
3060 Arg = DAG.getBitcast(RegVT, Arg);
3062 case CCValAssign::Indirect: {
3063 // Store the argument.
3064 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3065 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3066 Chain = DAG.getStore(
3067 Chain, dl, Arg, SpillSlot,
3068 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3075 if (VA.isRegLoc()) {
3076 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3077 if (isVarArg && IsWin64) {
3078 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3079 // shadow reg if callee is a varargs function.
3080 unsigned ShadowReg = 0;
3081 switch (VA.getLocReg()) {
3082 case X86::XMM0: ShadowReg = X86::RCX; break;
3083 case X86::XMM1: ShadowReg = X86::RDX; break;
3084 case X86::XMM2: ShadowReg = X86::R8; break;
3085 case X86::XMM3: ShadowReg = X86::R9; break;
3088 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3090 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3091 assert(VA.isMemLoc());
3092 if (!StackPtr.getNode())
3093 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3094 getPointerTy(DAG.getDataLayout()));
3095 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3096 dl, DAG, VA, Flags));
3100 if (!MemOpChains.empty())
3101 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3103 if (Subtarget->isPICStyleGOT()) {
3104 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3107 RegsToPass.push_back(std::make_pair(
3108 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3109 getPointerTy(DAG.getDataLayout()))));
3111 // If we are tail calling and generating PIC/GOT style code load the
3112 // address of the callee into ECX. The value in ecx is used as target of
3113 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3114 // for tail calls on PIC/GOT architectures. Normally we would just put the
3115 // address of GOT into ebx and then call target@PLT. But for tail calls
3116 // ebx would be restored (since ebx is callee saved) before jumping to the
3119 // Note: The actual moving to ECX is done further down.
3120 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3121 if (G && !G->getGlobal()->hasLocalLinkage() &&
3122 G->getGlobal()->hasDefaultVisibility())
3123 Callee = LowerGlobalAddress(Callee, DAG);
3124 else if (isa<ExternalSymbolSDNode>(Callee))
3125 Callee = LowerExternalSymbol(Callee, DAG);
3129 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3130 // From AMD64 ABI document:
3131 // For calls that may call functions that use varargs or stdargs
3132 // (prototype-less calls or calls to functions containing ellipsis (...) in
3133 // the declaration) %al is used as hidden argument to specify the number
3134 // of SSE registers used. The contents of %al do not need to match exactly
3135 // the number of registers, but must be an ubound on the number of SSE
3136 // registers used and is in the range 0 - 8 inclusive.
3138 // Count the number of XMM registers allocated.
3139 static const MCPhysReg XMMArgRegs[] = {
3140 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3141 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3143 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3144 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3145 && "SSE registers cannot be used when SSE is disabled");
3147 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3148 DAG.getConstant(NumXMMRegs, dl,
3152 if (isVarArg && IsMustTail) {
3153 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3154 for (const auto &F : Forwards) {
3155 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3156 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3160 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3161 // don't need this because the eligibility check rejects calls that require
3162 // shuffling arguments passed in memory.
3163 if (!IsSibcall && isTailCall) {
3164 // Force all the incoming stack arguments to be loaded from the stack
3165 // before any new outgoing arguments are stored to the stack, because the
3166 // outgoing stack slots may alias the incoming argument stack slots, and
3167 // the alias isn't otherwise explicit. This is slightly more conservative
3168 // than necessary, because it means that each store effectively depends
3169 // on every argument instead of just those arguments it would clobber.
3170 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3172 SmallVector<SDValue, 8> MemOpChains2;
3175 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3176 CCValAssign &VA = ArgLocs[i];
3179 assert(VA.isMemLoc());
3180 SDValue Arg = OutVals[i];
3181 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3182 // Skip inalloca arguments. They don't require any work.
3183 if (Flags.isInAlloca())
3185 // Create frame index.
3186 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3187 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3188 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3189 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3191 if (Flags.isByVal()) {
3192 // Copy relative to framepointer.
3193 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3194 if (!StackPtr.getNode())
3195 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3196 getPointerTy(DAG.getDataLayout()));
3197 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3200 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3204 // Store relative to framepointer.
3205 MemOpChains2.push_back(DAG.getStore(
3206 ArgChain, dl, Arg, FIN,
3207 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3212 if (!MemOpChains2.empty())
3213 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3215 // Store the return address to the appropriate stack slot.
3216 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3217 getPointerTy(DAG.getDataLayout()),
3218 RegInfo->getSlotSize(), FPDiff, dl);
3221 // Build a sequence of copy-to-reg nodes chained together with token chain
3222 // and flag operands which copy the outgoing args into registers.
3224 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3225 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3226 RegsToPass[i].second, InFlag);
3227 InFlag = Chain.getValue(1);
3230 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3231 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3232 // In the 64-bit large code model, we have to make all calls
3233 // through a register, since the call instruction's 32-bit
3234 // pc-relative offset may not be large enough to hold the whole
3236 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3237 // If the callee is a GlobalAddress node (quite common, every direct call
3238 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3240 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3242 // We should use extra load for direct calls to dllimported functions in
3244 const GlobalValue *GV = G->getGlobal();
3245 if (!GV->hasDLLImportStorageClass()) {
3246 unsigned char OpFlags = 0;
3247 bool ExtraLoad = false;
3248 unsigned WrapperKind = ISD::DELETED_NODE;
3250 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3251 // external symbols most go through the PLT in PIC mode. If the symbol
3252 // has hidden or protected visibility, or if it is static or local, then
3253 // we don't need to use the PLT - we can directly call it.
3254 if (Subtarget->isTargetELF() &&
3255 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3256 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3257 OpFlags = X86II::MO_PLT;
3258 } else if (Subtarget->isPICStyleStubAny() &&
3259 !GV->isStrongDefinitionForLinker() &&
3260 (!Subtarget->getTargetTriple().isMacOSX() ||
3261 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3262 // PC-relative references to external symbols should go through $stub,
3263 // unless we're building with the leopard linker or later, which
3264 // automatically synthesizes these stubs.
3265 OpFlags = X86II::MO_DARWIN_STUB;
3266 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3267 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3268 // If the function is marked as non-lazy, generate an indirect call
3269 // which loads from the GOT directly. This avoids runtime overhead
3270 // at the cost of eager binding (and one extra byte of encoding).
3271 OpFlags = X86II::MO_GOTPCREL;
3272 WrapperKind = X86ISD::WrapperRIP;
3276 Callee = DAG.getTargetGlobalAddress(
3277 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3279 // Add a wrapper if needed.
3280 if (WrapperKind != ISD::DELETED_NODE)
3281 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3282 getPointerTy(DAG.getDataLayout()), Callee);
3283 // Add extra indirection if needed.
3285 Callee = DAG.getLoad(
3286 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3287 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3290 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3291 unsigned char OpFlags = 0;
3293 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3294 // external symbols should go through the PLT.
3295 if (Subtarget->isTargetELF() &&
3296 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3297 OpFlags = X86II::MO_PLT;
3298 } else if (Subtarget->isPICStyleStubAny() &&
3299 (!Subtarget->getTargetTriple().isMacOSX() ||
3300 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3301 // PC-relative references to external symbols should go through $stub,
3302 // unless we're building with the leopard linker or later, which
3303 // automatically synthesizes these stubs.
3304 OpFlags = X86II::MO_DARWIN_STUB;
3307 Callee = DAG.getTargetExternalSymbol(
3308 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3309 } else if (Subtarget->isTarget64BitILP32() &&
3310 Callee->getValueType(0) == MVT::i32) {
3311 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3312 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3315 // Returns a chain & a flag for retval copy to use.
3316 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3317 SmallVector<SDValue, 8> Ops;
3319 if (!IsSibcall && isTailCall) {
3320 Chain = DAG.getCALLSEQ_END(Chain,
3321 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3322 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3323 InFlag = Chain.getValue(1);
3326 Ops.push_back(Chain);
3327 Ops.push_back(Callee);
3330 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3332 // Add argument registers to the end of the list so that they are known live
3334 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3335 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3336 RegsToPass[i].second.getValueType()));
3338 // Add a register mask operand representing the call-preserved registers.
3339 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3340 assert(Mask && "Missing call preserved mask for calling convention");
3342 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3343 // the function clobbers all registers. If an exception is thrown, the runtime
3344 // will not restore CSRs.
3345 // FIXME: Model this more precisely so that we can register allocate across
3346 // the normal edge and spill and fill across the exceptional edge.
3347 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3348 const Function *CallerFn = MF.getFunction();
3349 EHPersonality Pers =
3350 CallerFn->hasPersonalityFn()
3351 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3352 : EHPersonality::Unknown;
3353 if (isMSVCEHPersonality(Pers))
3354 Mask = RegInfo->getNoPreservedMask();
3357 Ops.push_back(DAG.getRegisterMask(Mask));
3359 if (InFlag.getNode())
3360 Ops.push_back(InFlag);
3364 //// If this is the first return lowered for this function, add the regs
3365 //// to the liveout set for the function.
3366 // This isn't right, although it's probably harmless on x86; liveouts
3367 // should be computed from returns not tail calls. Consider a void
3368 // function making a tail call to a function returning int.
3369 MF.getFrameInfo()->setHasTailCall();
3370 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3373 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3374 InFlag = Chain.getValue(1);
3376 // Create the CALLSEQ_END node.
3377 unsigned NumBytesForCalleeToPop;
3378 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3379 DAG.getTarget().Options.GuaranteedTailCallOpt))
3380 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3381 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3382 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3383 SR == StackStructReturn)
3384 // If this is a call to a struct-return function, the callee
3385 // pops the hidden struct pointer, so we have to push it back.
3386 // This is common for Darwin/X86, Linux & Mingw32 targets.
3387 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3388 NumBytesForCalleeToPop = 4;
3390 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3392 // Returns a flag for retval copy to use.
3394 Chain = DAG.getCALLSEQ_END(Chain,
3395 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3396 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3399 InFlag = Chain.getValue(1);
3402 // Handle result values, copying them out of physregs into vregs that we
3404 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3405 Ins, dl, DAG, InVals);
3408 //===----------------------------------------------------------------------===//
3409 // Fast Calling Convention (tail call) implementation
3410 //===----------------------------------------------------------------------===//
3412 // Like std call, callee cleans arguments, convention except that ECX is
3413 // reserved for storing the tail called function address. Only 2 registers are
3414 // free for argument passing (inreg). Tail call optimization is performed
3416 // * tailcallopt is enabled
3417 // * caller/callee are fastcc
3418 // On X86_64 architecture with GOT-style position independent code only local
3419 // (within module) calls are supported at the moment.
3420 // To keep the stack aligned according to platform abi the function
3421 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3422 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3423 // If a tail called function callee has more arguments than the caller the
3424 // caller needs to make sure that there is room to move the RETADDR to. This is
3425 // achieved by reserving an area the size of the argument delta right after the
3426 // original RETADDR, but before the saved framepointer or the spilled registers
3427 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3439 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3442 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3443 SelectionDAG& DAG) const {
3444 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3445 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3446 unsigned StackAlignment = TFI.getStackAlignment();
3447 uint64_t AlignMask = StackAlignment - 1;
3448 int64_t Offset = StackSize;
3449 unsigned SlotSize = RegInfo->getSlotSize();
3450 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3451 // Number smaller than 12 so just add the difference.
3452 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3454 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3455 Offset = ((~AlignMask) & Offset) + StackAlignment +
3456 (StackAlignment-SlotSize);
3461 /// Return true if the given stack call argument is already available in the
3462 /// same position (relatively) of the caller's incoming argument stack.
3464 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3465 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3466 const X86InstrInfo *TII) {
3467 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3469 if (Arg.getOpcode() == ISD::CopyFromReg) {
3470 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3471 if (!TargetRegisterInfo::isVirtualRegister(VR))
3473 MachineInstr *Def = MRI->getVRegDef(VR);
3476 if (!Flags.isByVal()) {
3477 if (!TII->isLoadFromStackSlot(Def, FI))
3480 unsigned Opcode = Def->getOpcode();
3481 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3482 Opcode == X86::LEA64_32r) &&
3483 Def->getOperand(1).isFI()) {
3484 FI = Def->getOperand(1).getIndex();
3485 Bytes = Flags.getByValSize();
3489 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3490 if (Flags.isByVal())
3491 // ByVal argument is passed in as a pointer but it's now being
3492 // dereferenced. e.g.
3493 // define @foo(%struct.X* %A) {
3494 // tail call @bar(%struct.X* byval %A)
3497 SDValue Ptr = Ld->getBasePtr();
3498 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3501 FI = FINode->getIndex();
3502 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3503 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3504 FI = FINode->getIndex();
3505 Bytes = Flags.getByValSize();
3509 assert(FI != INT_MAX);
3510 if (!MFI->isFixedObjectIndex(FI))
3512 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3515 /// Check whether the call is eligible for tail call optimization. Targets
3516 /// that want to do tail call optimization should implement this function.
3518 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3519 CallingConv::ID CalleeCC,
3521 bool isCalleeStructRet,
3522 bool isCallerStructRet,
3524 const SmallVectorImpl<ISD::OutputArg> &Outs,
3525 const SmallVectorImpl<SDValue> &OutVals,
3526 const SmallVectorImpl<ISD::InputArg> &Ins,
3527 SelectionDAG &DAG) const {
3528 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3531 // If -tailcallopt is specified, make fastcc functions tail-callable.
3532 const MachineFunction &MF = DAG.getMachineFunction();
3533 const Function *CallerF = MF.getFunction();
3535 // If the function return type is x86_fp80 and the callee return type is not,
3536 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3537 // perform a tailcall optimization here.
3538 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3541 CallingConv::ID CallerCC = CallerF->getCallingConv();
3542 bool CCMatch = CallerCC == CalleeCC;
3543 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3544 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3546 // Win64 functions have extra shadow space for argument homing. Don't do the
3547 // sibcall if the caller and callee have mismatched expectations for this
3549 if (IsCalleeWin64 != IsCallerWin64)
3552 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3553 if (IsTailCallConvention(CalleeCC) && CCMatch)
3558 // Look for obvious safe cases to perform tail call optimization that do not
3559 // require ABI changes. This is what gcc calls sibcall.
3561 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3562 // emit a special epilogue.
3563 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3564 if (RegInfo->needsStackRealignment(MF))
3567 // Also avoid sibcall optimization if either caller or callee uses struct
3568 // return semantics.
3569 if (isCalleeStructRet || isCallerStructRet)
3572 // An stdcall/thiscall caller is expected to clean up its arguments; the
3573 // callee isn't going to do that.
3574 // FIXME: this is more restrictive than needed. We could produce a tailcall
3575 // when the stack adjustment matches. For example, with a thiscall that takes
3576 // only one argument.
3577 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3578 CallerCC == CallingConv::X86_ThisCall))
3581 // Do not sibcall optimize vararg calls unless all arguments are passed via
3583 if (isVarArg && !Outs.empty()) {
3585 // Optimizing for varargs on Win64 is unlikely to be safe without
3586 // additional testing.
3587 if (IsCalleeWin64 || IsCallerWin64)
3590 SmallVector<CCValAssign, 16> ArgLocs;
3591 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3594 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3595 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3596 if (!ArgLocs[i].isRegLoc())
3600 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3601 // stack. Therefore, if it's not used by the call it is not safe to optimize
3602 // this into a sibcall.
3603 bool Unused = false;
3604 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3611 SmallVector<CCValAssign, 16> RVLocs;
3612 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3614 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3615 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3616 CCValAssign &VA = RVLocs[i];
3617 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3622 // If the calling conventions do not match, then we'd better make sure the
3623 // results are returned in the same way as what the caller expects.
3625 SmallVector<CCValAssign, 16> RVLocs1;
3626 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3628 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3630 SmallVector<CCValAssign, 16> RVLocs2;
3631 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3633 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3635 if (RVLocs1.size() != RVLocs2.size())
3637 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3638 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3640 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3642 if (RVLocs1[i].isRegLoc()) {
3643 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3646 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3652 // If the callee takes no arguments then go on to check the results of the
3654 if (!Outs.empty()) {
3655 // Check if stack adjustment is needed. For now, do not do this if any
3656 // argument is passed on the stack.
3657 SmallVector<CCValAssign, 16> ArgLocs;
3658 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3661 // Allocate shadow area for Win64
3663 CCInfo.AllocateStack(32, 8);
3665 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3666 if (CCInfo.getNextStackOffset()) {
3667 MachineFunction &MF = DAG.getMachineFunction();
3668 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3671 // Check if the arguments are already laid out in the right way as
3672 // the caller's fixed stack objects.
3673 MachineFrameInfo *MFI = MF.getFrameInfo();
3674 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3675 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3676 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3677 CCValAssign &VA = ArgLocs[i];
3678 SDValue Arg = OutVals[i];
3679 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3680 if (VA.getLocInfo() == CCValAssign::Indirect)
3682 if (!VA.isRegLoc()) {
3683 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3690 // If the tailcall address may be in a register, then make sure it's
3691 // possible to register allocate for it. In 32-bit, the call address can
3692 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3693 // callee-saved registers are restored. These happen to be the same
3694 // registers used to pass 'inreg' arguments so watch out for those.
3695 if (!Subtarget->is64Bit() &&
3696 ((!isa<GlobalAddressSDNode>(Callee) &&
3697 !isa<ExternalSymbolSDNode>(Callee)) ||
3698 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3699 unsigned NumInRegs = 0;
3700 // In PIC we need an extra register to formulate the address computation
3702 unsigned MaxInRegs =
3703 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3705 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3706 CCValAssign &VA = ArgLocs[i];
3709 unsigned Reg = VA.getLocReg();
3712 case X86::EAX: case X86::EDX: case X86::ECX:
3713 if (++NumInRegs == MaxInRegs)
3725 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3726 const TargetLibraryInfo *libInfo) const {
3727 return X86::createFastISel(funcInfo, libInfo);
3730 //===----------------------------------------------------------------------===//
3731 // Other Lowering Hooks
3732 //===----------------------------------------------------------------------===//
3734 static bool MayFoldLoad(SDValue Op) {
3735 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3738 static bool MayFoldIntoStore(SDValue Op) {
3739 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3742 static bool isTargetShuffle(unsigned Opcode) {
3744 default: return false;
3745 case X86ISD::BLENDI:
3746 case X86ISD::PSHUFB:
3747 case X86ISD::PSHUFD:
3748 case X86ISD::PSHUFHW:
3749 case X86ISD::PSHUFLW:
3751 case X86ISD::PALIGNR:
3752 case X86ISD::MOVLHPS:
3753 case X86ISD::MOVLHPD:
3754 case X86ISD::MOVHLPS:
3755 case X86ISD::MOVLPS:
3756 case X86ISD::MOVLPD:
3757 case X86ISD::MOVSHDUP:
3758 case X86ISD::MOVSLDUP:
3759 case X86ISD::MOVDDUP:
3762 case X86ISD::UNPCKL:
3763 case X86ISD::UNPCKH:
3764 case X86ISD::VPERMILPI:
3765 case X86ISD::VPERM2X128:
3766 case X86ISD::VPERMI:
3771 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3772 SDValue V1, unsigned TargetMask,
3773 SelectionDAG &DAG) {
3775 default: llvm_unreachable("Unknown x86 shuffle node");
3776 case X86ISD::PSHUFD:
3777 case X86ISD::PSHUFHW:
3778 case X86ISD::PSHUFLW:
3779 case X86ISD::VPERMILPI:
3780 case X86ISD::VPERMI:
3781 return DAG.getNode(Opc, dl, VT, V1,
3782 DAG.getConstant(TargetMask, dl, MVT::i8));
3786 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3787 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3789 default: llvm_unreachable("Unknown x86 shuffle node");
3790 case X86ISD::MOVLHPS:
3791 case X86ISD::MOVLHPD:
3792 case X86ISD::MOVHLPS:
3793 case X86ISD::MOVLPS:
3794 case X86ISD::MOVLPD:
3797 case X86ISD::UNPCKL:
3798 case X86ISD::UNPCKH:
3799 return DAG.getNode(Opc, dl, VT, V1, V2);
3803 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3804 MachineFunction &MF = DAG.getMachineFunction();
3805 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3806 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3807 int ReturnAddrIndex = FuncInfo->getRAIndex();
3809 if (ReturnAddrIndex == 0) {
3810 // Set up a frame object for the return address.
3811 unsigned SlotSize = RegInfo->getSlotSize();
3812 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3815 FuncInfo->setRAIndex(ReturnAddrIndex);
3818 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3821 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3822 bool hasSymbolicDisplacement) {
3823 // Offset should fit into 32 bit immediate field.
3824 if (!isInt<32>(Offset))
3827 // If we don't have a symbolic displacement - we don't have any extra
3829 if (!hasSymbolicDisplacement)
3832 // FIXME: Some tweaks might be needed for medium code model.
3833 if (M != CodeModel::Small && M != CodeModel::Kernel)
3836 // For small code model we assume that latest object is 16MB before end of 31
3837 // bits boundary. We may also accept pretty large negative constants knowing
3838 // that all objects are in the positive half of address space.
3839 if (M == CodeModel::Small && Offset < 16*1024*1024)
3842 // For kernel code model we know that all object resist in the negative half
3843 // of 32bits address space. We may not accept negative offsets, since they may
3844 // be just off and we may accept pretty large positive ones.
3845 if (M == CodeModel::Kernel && Offset >= 0)
3851 /// Determines whether the callee is required to pop its own arguments.
3852 /// Callee pop is necessary to support tail calls.
3853 bool X86::isCalleePop(CallingConv::ID CallingConv,
3854 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3855 switch (CallingConv) {
3858 case CallingConv::X86_StdCall:
3859 case CallingConv::X86_FastCall:
3860 case CallingConv::X86_ThisCall:
3862 case CallingConv::Fast:
3863 case CallingConv::GHC:
3864 case CallingConv::HiPE:
3871 /// \brief Return true if the condition is an unsigned comparison operation.
3872 static bool isX86CCUnsigned(unsigned X86CC) {
3874 default: llvm_unreachable("Invalid integer condition!");
3875 case X86::COND_E: return true;
3876 case X86::COND_G: return false;
3877 case X86::COND_GE: return false;
3878 case X86::COND_L: return false;
3879 case X86::COND_LE: return false;
3880 case X86::COND_NE: return true;
3881 case X86::COND_B: return true;
3882 case X86::COND_A: return true;
3883 case X86::COND_BE: return true;
3884 case X86::COND_AE: return true;
3886 llvm_unreachable("covered switch fell through?!");
3889 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3890 /// condition code, returning the condition code and the LHS/RHS of the
3891 /// comparison to make.
3892 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3893 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3895 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3896 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3897 // X > -1 -> X == 0, jump !sign.
3898 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3899 return X86::COND_NS;
3901 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3902 // X < 0 -> X == 0, jump on sign.
3905 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3907 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3908 return X86::COND_LE;
3912 switch (SetCCOpcode) {
3913 default: llvm_unreachable("Invalid integer condition!");
3914 case ISD::SETEQ: return X86::COND_E;
3915 case ISD::SETGT: return X86::COND_G;
3916 case ISD::SETGE: return X86::COND_GE;
3917 case ISD::SETLT: return X86::COND_L;
3918 case ISD::SETLE: return X86::COND_LE;
3919 case ISD::SETNE: return X86::COND_NE;
3920 case ISD::SETULT: return X86::COND_B;
3921 case ISD::SETUGT: return X86::COND_A;
3922 case ISD::SETULE: return X86::COND_BE;
3923 case ISD::SETUGE: return X86::COND_AE;
3927 // First determine if it is required or is profitable to flip the operands.
3929 // If LHS is a foldable load, but RHS is not, flip the condition.
3930 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3931 !ISD::isNON_EXTLoad(RHS.getNode())) {
3932 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3933 std::swap(LHS, RHS);
3936 switch (SetCCOpcode) {
3942 std::swap(LHS, RHS);
3946 // On a floating point condition, the flags are set as follows:
3948 // 0 | 0 | 0 | X > Y
3949 // 0 | 0 | 1 | X < Y
3950 // 1 | 0 | 0 | X == Y
3951 // 1 | 1 | 1 | unordered
3952 switch (SetCCOpcode) {
3953 default: llvm_unreachable("Condcode should be pre-legalized away");
3955 case ISD::SETEQ: return X86::COND_E;
3956 case ISD::SETOLT: // flipped
3958 case ISD::SETGT: return X86::COND_A;
3959 case ISD::SETOLE: // flipped
3961 case ISD::SETGE: return X86::COND_AE;
3962 case ISD::SETUGT: // flipped
3964 case ISD::SETLT: return X86::COND_B;
3965 case ISD::SETUGE: // flipped
3967 case ISD::SETLE: return X86::COND_BE;
3969 case ISD::SETNE: return X86::COND_NE;
3970 case ISD::SETUO: return X86::COND_P;
3971 case ISD::SETO: return X86::COND_NP;
3973 case ISD::SETUNE: return X86::COND_INVALID;
3977 /// Is there a floating point cmov for the specific X86 condition code?
3978 /// Current x86 isa includes the following FP cmov instructions:
3979 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3980 static bool hasFPCMov(unsigned X86CC) {
3996 /// Returns true if the target can instruction select the
3997 /// specified FP immediate natively. If false, the legalizer will
3998 /// materialize the FP immediate as a load from a constant pool.
3999 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4000 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4001 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4007 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4008 ISD::LoadExtType ExtTy,
4010 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4011 // relocation target a movq or addq instruction: don't let the load shrink.
4012 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4013 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4014 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4015 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4019 /// \brief Returns true if it is beneficial to convert a load of a constant
4020 /// to just the constant itself.
4021 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4023 assert(Ty->isIntegerTy());
4025 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4026 if (BitSize == 0 || BitSize > 64)
4031 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4032 unsigned Index) const {
4033 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4036 return (Index == 0 || Index == ResVT.getVectorNumElements());
4039 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4040 // Speculate cttz only if we can directly use TZCNT.
4041 return Subtarget->hasBMI();
4044 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4045 // Speculate ctlz only if we can directly use LZCNT.
4046 return Subtarget->hasLZCNT();
4049 /// Return true if every element in Mask, beginning
4050 /// from position Pos and ending in Pos+Size is undef.
4051 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4052 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4058 /// Return true if Val is undef or if its value falls within the
4059 /// specified range (L, H].
4060 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4061 return (Val < 0) || (Val >= Low && Val < Hi);
4064 /// Val is either less than zero (undef) or equal to the specified value.
4065 static bool isUndefOrEqual(int Val, int CmpVal) {
4066 return (Val < 0 || Val == CmpVal);
4069 /// Return true if every element in Mask, beginning
4070 /// from position Pos and ending in Pos+Size, falls within the specified
4071 /// sequential range (Low, Low+Size]. or is undef.
4072 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4073 unsigned Pos, unsigned Size, int Low) {
4074 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4075 if (!isUndefOrEqual(Mask[i], Low))
4080 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4081 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4082 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4083 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4084 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4087 // The index should be aligned on a vecWidth-bit boundary.
4089 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4091 MVT VT = N->getSimpleValueType(0);
4092 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4093 bool Result = (Index * ElSize) % vecWidth == 0;
4098 /// Return true if the specified INSERT_SUBVECTOR
4099 /// operand specifies a subvector insert that is suitable for input to
4100 /// insertion of 128 or 256-bit subvectors
4101 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4102 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4103 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4105 // The index should be aligned on a vecWidth-bit boundary.
4107 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4109 MVT VT = N->getSimpleValueType(0);
4110 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4111 bool Result = (Index * ElSize) % vecWidth == 0;
4116 bool X86::isVINSERT128Index(SDNode *N) {
4117 return isVINSERTIndex(N, 128);
4120 bool X86::isVINSERT256Index(SDNode *N) {
4121 return isVINSERTIndex(N, 256);
4124 bool X86::isVEXTRACT128Index(SDNode *N) {
4125 return isVEXTRACTIndex(N, 128);
4128 bool X86::isVEXTRACT256Index(SDNode *N) {
4129 return isVEXTRACTIndex(N, 256);
4132 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4133 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4134 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4135 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4138 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4140 MVT VecVT = N->getOperand(0).getSimpleValueType();
4141 MVT ElVT = VecVT.getVectorElementType();
4143 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4144 return Index / NumElemsPerChunk;
4147 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4148 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4149 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4150 llvm_unreachable("Illegal insert subvector for VINSERT");
4153 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4155 MVT VecVT = N->getSimpleValueType(0);
4156 MVT ElVT = VecVT.getVectorElementType();
4158 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4159 return Index / NumElemsPerChunk;
4162 /// Return the appropriate immediate to extract the specified
4163 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4164 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4165 return getExtractVEXTRACTImmediate(N, 128);
4168 /// Return the appropriate immediate to extract the specified
4169 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4170 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4171 return getExtractVEXTRACTImmediate(N, 256);
4174 /// Return the appropriate immediate to insert at the specified
4175 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4176 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4177 return getInsertVINSERTImmediate(N, 128);
4180 /// Return the appropriate immediate to insert at the specified
4181 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4182 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4183 return getInsertVINSERTImmediate(N, 256);
4186 /// Returns true if Elt is a constant integer zero
4187 static bool isZero(SDValue V) {
4188 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4189 return C && C->isNullValue();
4192 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4193 bool X86::isZeroNode(SDValue Elt) {
4196 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4197 return CFP->getValueAPF().isPosZero();
4201 /// Returns a vector of specified type with all zero elements.
4202 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4203 SelectionDAG &DAG, SDLoc dl) {
4204 assert(VT.isVector() && "Expected a vector type");
4206 // Always build SSE zero vectors as <4 x i32> bitcasted
4207 // to their dest type. This ensures they get CSE'd.
4209 if (VT.is128BitVector()) { // SSE
4210 if (Subtarget->hasSSE2()) { // SSE2
4211 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4212 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4214 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4215 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4217 } else if (VT.is256BitVector()) { // AVX
4218 if (Subtarget->hasInt256()) { // AVX2
4219 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4220 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4221 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4223 // 256-bit logic and arithmetic instructions in AVX are all
4224 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4225 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4226 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4227 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4229 } else if (VT.is512BitVector()) { // AVX-512
4230 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4231 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4232 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4233 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4234 } else if (VT.getScalarType() == MVT::i1) {
4236 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4237 && "Unexpected vector type");
4238 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4239 && "Unexpected vector type");
4240 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4241 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4242 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4244 llvm_unreachable("Unexpected vector type");
4246 return DAG.getBitcast(VT, Vec);
4249 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4250 SelectionDAG &DAG, SDLoc dl,
4251 unsigned vectorWidth) {
4252 assert((vectorWidth == 128 || vectorWidth == 256) &&
4253 "Unsupported vector width");
4254 EVT VT = Vec.getValueType();
4255 EVT ElVT = VT.getVectorElementType();
4256 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4257 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4258 VT.getVectorNumElements()/Factor);
4260 // Extract from UNDEF is UNDEF.
4261 if (Vec.getOpcode() == ISD::UNDEF)
4262 return DAG.getUNDEF(ResultVT);
4264 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4265 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4267 // This is the index of the first element of the vectorWidth-bit chunk
4269 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4272 // If the input is a buildvector just emit a smaller one.
4273 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4274 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4275 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4278 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4282 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4283 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4284 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4285 /// instructions or a simple subregister reference. Idx is an index in the
4286 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4287 /// lowering EXTRACT_VECTOR_ELT operations easier.
4288 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4289 SelectionDAG &DAG, SDLoc dl) {
4290 assert((Vec.getValueType().is256BitVector() ||
4291 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4292 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4295 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4296 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4297 SelectionDAG &DAG, SDLoc dl) {
4298 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4299 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4302 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4303 unsigned IdxVal, SelectionDAG &DAG,
4304 SDLoc dl, unsigned vectorWidth) {
4305 assert((vectorWidth == 128 || vectorWidth == 256) &&
4306 "Unsupported vector width");
4307 // Inserting UNDEF is Result
4308 if (Vec.getOpcode() == ISD::UNDEF)
4310 EVT VT = Vec.getValueType();
4311 EVT ElVT = VT.getVectorElementType();
4312 EVT ResultVT = Result.getValueType();
4314 // Insert the relevant vectorWidth bits.
4315 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4317 // This is the index of the first element of the vectorWidth-bit chunk
4319 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4322 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4323 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4326 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4327 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4328 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4329 /// simple superregister reference. Idx is an index in the 128 bits
4330 /// we want. It need not be aligned to a 128-bit boundary. That makes
4331 /// lowering INSERT_VECTOR_ELT operations easier.
4332 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4333 SelectionDAG &DAG, SDLoc dl) {
4334 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4336 // For insertion into the zero index (low half) of a 256-bit vector, it is
4337 // more efficient to generate a blend with immediate instead of an insert*128.
4338 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4339 // extend the subvector to the size of the result vector. Make sure that
4340 // we are not recursing on that node by checking for undef here.
4341 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4342 Result.getOpcode() != ISD::UNDEF) {
4343 EVT ResultVT = Result.getValueType();
4344 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4345 SDValue Undef = DAG.getUNDEF(ResultVT);
4346 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4349 // The blend instruction, and therefore its mask, depend on the data type.
4350 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4351 if (ScalarType.isFloatingPoint()) {
4352 // Choose either vblendps (float) or vblendpd (double).
4353 unsigned ScalarSize = ScalarType.getSizeInBits();
4354 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4355 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4356 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4357 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4360 const X86Subtarget &Subtarget =
4361 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4363 // AVX2 is needed for 256-bit integer blend support.
4364 // Integers must be cast to 32-bit because there is only vpblendd;
4365 // vpblendw can't be used for this because it has a handicapped mask.
4367 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4368 // is still more efficient than using the wrong domain vinsertf128 that
4369 // will be created by InsertSubVector().
4370 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4372 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4373 Vec256 = DAG.getBitcast(CastVT, Vec256);
4374 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4375 return DAG.getBitcast(ResultVT, Vec256);
4378 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4381 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4382 SelectionDAG &DAG, SDLoc dl) {
4383 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4384 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4387 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4388 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4389 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4390 /// large BUILD_VECTORS.
4391 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4392 unsigned NumElems, SelectionDAG &DAG,
4394 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4395 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4398 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4399 unsigned NumElems, SelectionDAG &DAG,
4401 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4402 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4405 /// Returns a vector of specified type with all bits set.
4406 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4407 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4408 /// Then bitcast to their original type, ensuring they get CSE'd.
4409 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4411 assert(VT.isVector() && "Expected a vector type");
4413 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4415 if (VT.is256BitVector()) {
4416 if (HasInt256) { // AVX2
4417 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4418 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4420 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4421 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4423 } else if (VT.is128BitVector()) {
4424 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4426 llvm_unreachable("Unexpected vector type");
4428 return DAG.getBitcast(VT, Vec);
4431 /// Returns a vector_shuffle node for an unpackl operation.
4432 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4434 unsigned NumElems = VT.getVectorNumElements();
4435 SmallVector<int, 8> Mask;
4436 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4438 Mask.push_back(i + NumElems);
4440 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4443 /// Returns a vector_shuffle node for an unpackh operation.
4444 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4446 unsigned NumElems = VT.getVectorNumElements();
4447 SmallVector<int, 8> Mask;
4448 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4449 Mask.push_back(i + Half);
4450 Mask.push_back(i + NumElems + Half);
4452 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4455 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4456 /// This produces a shuffle where the low element of V2 is swizzled into the
4457 /// zero/undef vector, landing at element Idx.
4458 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4459 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4461 const X86Subtarget *Subtarget,
4462 SelectionDAG &DAG) {
4463 MVT VT = V2.getSimpleValueType();
4465 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4466 unsigned NumElems = VT.getVectorNumElements();
4467 SmallVector<int, 16> MaskVec;
4468 for (unsigned i = 0; i != NumElems; ++i)
4469 // If this is the insertion idx, put the low elt of V2 here.
4470 MaskVec.push_back(i == Idx ? NumElems : i);
4471 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4474 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4475 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4476 /// uses one source. Note that this will set IsUnary for shuffles which use a
4477 /// single input multiple times, and in those cases it will
4478 /// adjust the mask to only have indices within that single input.
4479 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4480 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4481 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4482 unsigned NumElems = VT.getVectorNumElements();
4486 bool IsFakeUnary = false;
4487 switch(N->getOpcode()) {
4488 case X86ISD::BLENDI:
4489 ImmN = N->getOperand(N->getNumOperands()-1);
4490 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4493 ImmN = N->getOperand(N->getNumOperands()-1);
4494 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4497 case X86ISD::UNPCKH:
4498 DecodeUNPCKHMask(VT, Mask);
4499 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4501 case X86ISD::UNPCKL:
4502 DecodeUNPCKLMask(VT, Mask);
4503 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4505 case X86ISD::MOVHLPS:
4506 DecodeMOVHLPSMask(NumElems, Mask);
4507 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4509 case X86ISD::MOVLHPS:
4510 DecodeMOVLHPSMask(NumElems, Mask);
4511 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4513 case X86ISD::PALIGNR:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517 case X86ISD::PSHUFD:
4518 case X86ISD::VPERMILPI:
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523 case X86ISD::PSHUFHW:
4524 ImmN = N->getOperand(N->getNumOperands()-1);
4525 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4528 case X86ISD::PSHUFLW:
4529 ImmN = N->getOperand(N->getNumOperands()-1);
4530 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4533 case X86ISD::PSHUFB: {
4535 SDValue MaskNode = N->getOperand(1);
4536 while (MaskNode->getOpcode() == ISD::BITCAST)
4537 MaskNode = MaskNode->getOperand(0);
4539 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4540 // If we have a build-vector, then things are easy.
4541 EVT VT = MaskNode.getValueType();
4542 assert(VT.isVector() &&
4543 "Can't produce a non-vector with a build_vector!");
4544 if (!VT.isInteger())
4547 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4549 SmallVector<uint64_t, 32> RawMask;
4550 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4551 SDValue Op = MaskNode->getOperand(i);
4552 if (Op->getOpcode() == ISD::UNDEF) {
4553 RawMask.push_back((uint64_t)SM_SentinelUndef);
4556 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4559 APInt MaskElement = CN->getAPIntValue();
4561 // We now have to decode the element which could be any integer size and
4562 // extract each byte of it.
4563 for (int j = 0; j < NumBytesPerElement; ++j) {
4564 // Note that this is x86 and so always little endian: the low byte is
4565 // the first byte of the mask.
4566 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4567 MaskElement = MaskElement.lshr(8);
4570 DecodePSHUFBMask(RawMask, Mask);
4574 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4578 SDValue Ptr = MaskLoad->getBasePtr();
4579 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4580 Ptr->getOpcode() == X86ISD::WrapperRIP)
4581 Ptr = Ptr->getOperand(0);
4583 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4584 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4587 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4588 DecodePSHUFBMask(C, Mask);
4596 case X86ISD::VPERMI:
4597 ImmN = N->getOperand(N->getNumOperands()-1);
4598 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4603 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4605 case X86ISD::VPERM2X128:
4606 ImmN = N->getOperand(N->getNumOperands()-1);
4607 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4608 if (Mask.empty()) return false;
4609 // Mask only contains negative index if an element is zero.
4610 if (std::any_of(Mask.begin(), Mask.end(),
4611 [](int M){ return M == SM_SentinelZero; }))
4614 case X86ISD::MOVSLDUP:
4615 DecodeMOVSLDUPMask(VT, Mask);
4618 case X86ISD::MOVSHDUP:
4619 DecodeMOVSHDUPMask(VT, Mask);
4622 case X86ISD::MOVDDUP:
4623 DecodeMOVDDUPMask(VT, Mask);
4626 case X86ISD::MOVLHPD:
4627 case X86ISD::MOVLPD:
4628 case X86ISD::MOVLPS:
4629 // Not yet implemented
4631 default: llvm_unreachable("unknown target shuffle node");
4634 // If we have a fake unary shuffle, the shuffle mask is spread across two
4635 // inputs that are actually the same node. Re-map the mask to always point
4636 // into the first input.
4639 if (M >= (int)Mask.size())
4645 /// Returns the scalar element that will make up the ith
4646 /// element of the result of the vector shuffle.
4647 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4650 return SDValue(); // Limit search depth.
4652 SDValue V = SDValue(N, 0);
4653 EVT VT = V.getValueType();
4654 unsigned Opcode = V.getOpcode();
4656 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4657 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4658 int Elt = SV->getMaskElt(Index);
4661 return DAG.getUNDEF(VT.getVectorElementType());
4663 unsigned NumElems = VT.getVectorNumElements();
4664 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4665 : SV->getOperand(1);
4666 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4669 // Recurse into target specific vector shuffles to find scalars.
4670 if (isTargetShuffle(Opcode)) {
4671 MVT ShufVT = V.getSimpleValueType();
4672 unsigned NumElems = ShufVT.getVectorNumElements();
4673 SmallVector<int, 16> ShuffleMask;
4676 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4679 int Elt = ShuffleMask[Index];
4681 return DAG.getUNDEF(ShufVT.getVectorElementType());
4683 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4685 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4689 // Actual nodes that may contain scalar elements
4690 if (Opcode == ISD::BITCAST) {
4691 V = V.getOperand(0);
4692 EVT SrcVT = V.getValueType();
4693 unsigned NumElems = VT.getVectorNumElements();
4695 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4699 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4700 return (Index == 0) ? V.getOperand(0)
4701 : DAG.getUNDEF(VT.getVectorElementType());
4703 if (V.getOpcode() == ISD::BUILD_VECTOR)
4704 return V.getOperand(Index);
4709 /// Custom lower build_vector of v16i8.
4710 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4711 unsigned NumNonZero, unsigned NumZero,
4713 const X86Subtarget* Subtarget,
4714 const TargetLowering &TLI) {
4722 // SSE4.1 - use PINSRB to insert each byte directly.
4723 if (Subtarget->hasSSE41()) {
4724 for (unsigned i = 0; i < 16; ++i) {
4725 bool isNonZero = (NonZeros & (1 << i)) != 0;
4729 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4731 V = DAG.getUNDEF(MVT::v16i8);
4734 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4735 MVT::v16i8, V, Op.getOperand(i),
4736 DAG.getIntPtrConstant(i, dl));
4743 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4744 for (unsigned i = 0; i < 16; ++i) {
4745 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4746 if (ThisIsNonZero && First) {
4748 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4750 V = DAG.getUNDEF(MVT::v8i16);
4755 SDValue ThisElt, LastElt;
4756 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4757 if (LastIsNonZero) {
4758 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4759 MVT::i16, Op.getOperand(i-1));
4761 if (ThisIsNonZero) {
4762 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4763 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4764 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4766 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4770 if (ThisElt.getNode())
4771 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4772 DAG.getIntPtrConstant(i/2, dl));
4776 return DAG.getBitcast(MVT::v16i8, V);
4779 /// Custom lower build_vector of v8i16.
4780 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4781 unsigned NumNonZero, unsigned NumZero,
4783 const X86Subtarget* Subtarget,
4784 const TargetLowering &TLI) {
4791 for (unsigned i = 0; i < 8; ++i) {
4792 bool isNonZero = (NonZeros & (1 << i)) != 0;
4796 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4798 V = DAG.getUNDEF(MVT::v8i16);
4801 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4802 MVT::v8i16, V, Op.getOperand(i),
4803 DAG.getIntPtrConstant(i, dl));
4810 /// Custom lower build_vector of v4i32 or v4f32.
4811 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4812 const X86Subtarget *Subtarget,
4813 const TargetLowering &TLI) {
4814 // Find all zeroable elements.
4815 std::bitset<4> Zeroable;
4816 for (int i=0; i < 4; ++i) {
4817 SDValue Elt = Op->getOperand(i);
4818 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4820 assert(Zeroable.size() - Zeroable.count() > 1 &&
4821 "We expect at least two non-zero elements!");
4823 // We only know how to deal with build_vector nodes where elements are either
4824 // zeroable or extract_vector_elt with constant index.
4825 SDValue FirstNonZero;
4826 unsigned FirstNonZeroIdx;
4827 for (unsigned i=0; i < 4; ++i) {
4830 SDValue Elt = Op->getOperand(i);
4831 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4832 !isa<ConstantSDNode>(Elt.getOperand(1)))
4834 // Make sure that this node is extracting from a 128-bit vector.
4835 MVT VT = Elt.getOperand(0).getSimpleValueType();
4836 if (!VT.is128BitVector())
4838 if (!FirstNonZero.getNode()) {
4840 FirstNonZeroIdx = i;
4844 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4845 SDValue V1 = FirstNonZero.getOperand(0);
4846 MVT VT = V1.getSimpleValueType();
4848 // See if this build_vector can be lowered as a blend with zero.
4850 unsigned EltMaskIdx, EltIdx;
4852 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4853 if (Zeroable[EltIdx]) {
4854 // The zero vector will be on the right hand side.
4855 Mask[EltIdx] = EltIdx+4;
4859 Elt = Op->getOperand(EltIdx);
4860 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4861 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4862 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4864 Mask[EltIdx] = EltIdx;
4868 // Let the shuffle legalizer deal with blend operations.
4869 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4870 if (V1.getSimpleValueType() != VT)
4871 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4872 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4875 // See if we can lower this build_vector to a INSERTPS.
4876 if (!Subtarget->hasSSE41())
4879 SDValue V2 = Elt.getOperand(0);
4880 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4883 bool CanFold = true;
4884 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4888 SDValue Current = Op->getOperand(i);
4889 SDValue SrcVector = Current->getOperand(0);
4892 CanFold = SrcVector == V1 &&
4893 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4899 assert(V1.getNode() && "Expected at least two non-zero elements!");
4900 if (V1.getSimpleValueType() != MVT::v4f32)
4901 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4902 if (V2.getSimpleValueType() != MVT::v4f32)
4903 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4905 // Ok, we can emit an INSERTPS instruction.
4906 unsigned ZMask = Zeroable.to_ulong();
4908 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4909 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4911 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4912 DAG.getIntPtrConstant(InsertPSMask, DL));
4913 return DAG.getBitcast(VT, Result);
4916 /// Return a vector logical shift node.
4917 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4918 unsigned NumBits, SelectionDAG &DAG,
4919 const TargetLowering &TLI, SDLoc dl) {
4920 assert(VT.is128BitVector() && "Unknown type for VShift");
4921 MVT ShVT = MVT::v2i64;
4922 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4923 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4924 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4925 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4926 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4927 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4931 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4933 // Check if the scalar load can be widened into a vector load. And if
4934 // the address is "base + cst" see if the cst can be "absorbed" into
4935 // the shuffle mask.
4936 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4937 SDValue Ptr = LD->getBasePtr();
4938 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4940 EVT PVT = LD->getValueType(0);
4941 if (PVT != MVT::i32 && PVT != MVT::f32)
4946 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4947 FI = FINode->getIndex();
4949 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4950 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4951 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4952 Offset = Ptr.getConstantOperandVal(1);
4953 Ptr = Ptr.getOperand(0);
4958 // FIXME: 256-bit vector instructions don't require a strict alignment,
4959 // improve this code to support it better.
4960 unsigned RequiredAlign = VT.getSizeInBits()/8;
4961 SDValue Chain = LD->getChain();
4962 // Make sure the stack object alignment is at least 16 or 32.
4963 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4964 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4965 if (MFI->isFixedObjectIndex(FI)) {
4966 // Can't change the alignment. FIXME: It's possible to compute
4967 // the exact stack offset and reference FI + adjust offset instead.
4968 // If someone *really* cares about this. That's the way to implement it.
4971 MFI->setObjectAlignment(FI, RequiredAlign);
4975 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4976 // Ptr + (Offset & ~15).
4979 if ((Offset % RequiredAlign) & 3)
4981 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
4984 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4985 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4988 int EltNo = (Offset - StartOffset) >> 2;
4989 unsigned NumElems = VT.getVectorNumElements();
4991 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4992 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4993 LD->getPointerInfo().getWithOffset(StartOffset),
4994 false, false, false, 0);
4996 SmallVector<int, 8> Mask(NumElems, EltNo);
4998 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5004 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5005 /// elements can be replaced by a single large load which has the same value as
5006 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5008 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5010 /// FIXME: we'd also like to handle the case where the last elements are zero
5011 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5012 /// There's even a handy isZeroNode for that purpose.
5013 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5014 SDLoc &DL, SelectionDAG &DAG,
5015 bool isAfterLegalize) {
5016 unsigned NumElems = Elts.size();
5018 LoadSDNode *LDBase = nullptr;
5019 unsigned LastLoadedElt = -1U;
5021 // For each element in the initializer, see if we've found a load or an undef.
5022 // If we don't find an initial load element, or later load elements are
5023 // non-consecutive, bail out.
5024 for (unsigned i = 0; i < NumElems; ++i) {
5025 SDValue Elt = Elts[i];
5026 // Look through a bitcast.
5027 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5028 Elt = Elt.getOperand(0);
5029 if (!Elt.getNode() ||
5030 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5033 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5035 LDBase = cast<LoadSDNode>(Elt.getNode());
5039 if (Elt.getOpcode() == ISD::UNDEF)
5042 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5043 EVT LdVT = Elt.getValueType();
5044 // Each loaded element must be the correct fractional portion of the
5045 // requested vector load.
5046 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5048 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5053 // If we have found an entire vector of loads and undefs, then return a large
5054 // load of the entire vector width starting at the base pointer. If we found
5055 // consecutive loads for the low half, generate a vzext_load node.
5056 if (LastLoadedElt == NumElems - 1) {
5057 assert(LDBase && "Did not find base load for merging consecutive loads");
5058 EVT EltVT = LDBase->getValueType(0);
5059 // Ensure that the input vector size for the merged loads matches the
5060 // cumulative size of the input elements.
5061 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5064 if (isAfterLegalize &&
5065 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5068 SDValue NewLd = SDValue();
5070 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5071 LDBase->getPointerInfo(), LDBase->isVolatile(),
5072 LDBase->isNonTemporal(), LDBase->isInvariant(),
5073 LDBase->getAlignment());
5075 if (LDBase->hasAnyUseOfValue(1)) {
5076 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5078 SDValue(NewLd.getNode(), 1));
5079 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5080 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5081 SDValue(NewLd.getNode(), 1));
5087 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5088 //of a v4i32 / v4f32. It's probably worth generalizing.
5089 EVT EltVT = VT.getVectorElementType();
5090 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5091 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5092 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5093 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5095 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5096 LDBase->getPointerInfo(),
5097 LDBase->getAlignment(),
5098 false/*isVolatile*/, true/*ReadMem*/,
5101 // Make sure the newly-created LOAD is in the same position as LDBase in
5102 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5103 // update uses of LDBase's output chain to use the TokenFactor.
5104 if (LDBase->hasAnyUseOfValue(1)) {
5105 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5106 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5107 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5108 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5109 SDValue(ResNode.getNode(), 1));
5112 return DAG.getBitcast(VT, ResNode);
5117 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5118 /// to generate a splat value for the following cases:
5119 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5120 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5121 /// a scalar load, or a constant.
5122 /// The VBROADCAST node is returned when a pattern is found,
5123 /// or SDValue() otherwise.
5124 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5125 SelectionDAG &DAG) {
5126 // VBROADCAST requires AVX.
5127 // TODO: Splats could be generated for non-AVX CPUs using SSE
5128 // instructions, but there's less potential gain for only 128-bit vectors.
5129 if (!Subtarget->hasAVX())
5132 MVT VT = Op.getSimpleValueType();
5135 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5136 "Unsupported vector type for broadcast.");
5141 switch (Op.getOpcode()) {
5143 // Unknown pattern found.
5146 case ISD::BUILD_VECTOR: {
5147 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5148 BitVector UndefElements;
5149 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5151 // We need a splat of a single value to use broadcast, and it doesn't
5152 // make any sense if the value is only in one element of the vector.
5153 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5157 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5158 Ld.getOpcode() == ISD::ConstantFP);
5160 // Make sure that all of the users of a non-constant load are from the
5161 // BUILD_VECTOR node.
5162 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5167 case ISD::VECTOR_SHUFFLE: {
5168 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5170 // Shuffles must have a splat mask where the first element is
5172 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5175 SDValue Sc = Op.getOperand(0);
5176 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5177 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5179 if (!Subtarget->hasInt256())
5182 // Use the register form of the broadcast instruction available on AVX2.
5183 if (VT.getSizeInBits() >= 256)
5184 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5185 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5188 Ld = Sc.getOperand(0);
5189 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5190 Ld.getOpcode() == ISD::ConstantFP);
5192 // The scalar_to_vector node and the suspected
5193 // load node must have exactly one user.
5194 // Constants may have multiple users.
5196 // AVX-512 has register version of the broadcast
5197 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5198 Ld.getValueType().getSizeInBits() >= 32;
5199 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5206 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5207 bool IsGE256 = (VT.getSizeInBits() >= 256);
5209 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5210 // instruction to save 8 or more bytes of constant pool data.
5211 // TODO: If multiple splats are generated to load the same constant,
5212 // it may be detrimental to overall size. There needs to be a way to detect
5213 // that condition to know if this is truly a size win.
5214 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5216 // Handle broadcasting a single constant scalar from the constant pool
5218 // On Sandybridge (no AVX2), it is still better to load a constant vector
5219 // from the constant pool and not to broadcast it from a scalar.
5220 // But override that restriction when optimizing for size.
5221 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5222 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5223 EVT CVT = Ld.getValueType();
5224 assert(!CVT.isVector() && "Must not broadcast a vector type");
5226 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5227 // For size optimization, also splat v2f64 and v2i64, and for size opt
5228 // with AVX2, also splat i8 and i16.
5229 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5230 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5231 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5232 const Constant *C = nullptr;
5233 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5234 C = CI->getConstantIntValue();
5235 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5236 C = CF->getConstantFPValue();
5238 assert(C && "Invalid constant type");
5240 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5242 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5243 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5245 CVT, dl, DAG.getEntryNode(), CP,
5246 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5247 false, false, Alignment);
5249 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5253 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5255 // Handle AVX2 in-register broadcasts.
5256 if (!IsLoad && Subtarget->hasInt256() &&
5257 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5258 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260 // The scalar source must be a normal load.
5264 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5265 (Subtarget->hasVLX() && ScalarSize == 64))
5266 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5268 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5269 // double since there is no vbroadcastsd xmm
5270 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5271 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5272 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5275 // Unsupported broadcast.
5279 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5280 /// underlying vector and index.
5282 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5284 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5286 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5287 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5290 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5292 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5294 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5295 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5298 // In this case the vector is the extract_subvector expression and the index
5299 // is 2, as specified by the shuffle.
5300 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5301 SDValue ShuffleVec = SVOp->getOperand(0);
5302 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5303 assert(ShuffleVecVT.getVectorElementType() ==
5304 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5306 int ShuffleIdx = SVOp->getMaskElt(Idx);
5307 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5308 ExtractedFromVec = ShuffleVec;
5314 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5315 MVT VT = Op.getSimpleValueType();
5317 // Skip if insert_vec_elt is not supported.
5318 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5319 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5323 unsigned NumElems = Op.getNumOperands();
5327 SmallVector<unsigned, 4> InsertIndices;
5328 SmallVector<int, 8> Mask(NumElems, -1);
5330 for (unsigned i = 0; i != NumElems; ++i) {
5331 unsigned Opc = Op.getOperand(i).getOpcode();
5333 if (Opc == ISD::UNDEF)
5336 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5337 // Quit if more than 1 elements need inserting.
5338 if (InsertIndices.size() > 1)
5341 InsertIndices.push_back(i);
5345 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5346 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5347 // Quit if non-constant index.
5348 if (!isa<ConstantSDNode>(ExtIdx))
5350 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5352 // Quit if extracted from vector of different type.
5353 if (ExtractedFromVec.getValueType() != VT)
5356 if (!VecIn1.getNode())
5357 VecIn1 = ExtractedFromVec;
5358 else if (VecIn1 != ExtractedFromVec) {
5359 if (!VecIn2.getNode())
5360 VecIn2 = ExtractedFromVec;
5361 else if (VecIn2 != ExtractedFromVec)
5362 // Quit if more than 2 vectors to shuffle
5366 if (ExtractedFromVec == VecIn1)
5368 else if (ExtractedFromVec == VecIn2)
5369 Mask[i] = Idx + NumElems;
5372 if (!VecIn1.getNode())
5375 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5376 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5377 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5378 unsigned Idx = InsertIndices[i];
5379 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5380 DAG.getIntPtrConstant(Idx, DL));
5386 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5387 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5388 Op.getScalarValueSizeInBits() == 1 &&
5389 "Can not convert non-constant vector");
5390 uint64_t Immediate = 0;
5391 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5392 SDValue In = Op.getOperand(idx);
5393 if (In.getOpcode() != ISD::UNDEF)
5394 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5398 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5399 return DAG.getConstant(Immediate, dl, VT);
5401 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5403 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5405 MVT VT = Op.getSimpleValueType();
5406 assert((VT.getVectorElementType() == MVT::i1) &&
5407 "Unexpected type in LowerBUILD_VECTORvXi1!");
5410 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5411 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5412 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5413 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5416 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5417 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5418 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5419 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5422 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5423 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5424 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5425 return DAG.getBitcast(VT, Imm);
5426 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5427 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5428 DAG.getIntPtrConstant(0, dl));
5431 // Vector has one or more non-const elements
5432 uint64_t Immediate = 0;
5433 SmallVector<unsigned, 16> NonConstIdx;
5434 bool IsSplat = true;
5435 bool HasConstElts = false;
5437 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5438 SDValue In = Op.getOperand(idx);
5439 if (In.getOpcode() == ISD::UNDEF)
5441 if (!isa<ConstantSDNode>(In))
5442 NonConstIdx.push_back(idx);
5444 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5445 HasConstElts = true;
5449 else if (In != Op.getOperand(SplatIdx))
5453 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5455 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5456 DAG.getConstant(1, dl, VT),
5457 DAG.getConstant(0, dl, VT));
5459 // insert elements one by one
5463 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5464 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5466 else if (HasConstElts)
5467 Imm = DAG.getConstant(0, dl, VT);
5469 Imm = DAG.getUNDEF(VT);
5470 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5471 DstVec = DAG.getBitcast(VT, Imm);
5473 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5474 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5475 DAG.getIntPtrConstant(0, dl));
5478 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5479 unsigned InsertIdx = NonConstIdx[i];
5480 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5481 Op.getOperand(InsertIdx),
5482 DAG.getIntPtrConstant(InsertIdx, dl));
5487 /// \brief Return true if \p N implements a horizontal binop and return the
5488 /// operands for the horizontal binop into V0 and V1.
5490 /// This is a helper function of LowerToHorizontalOp().
5491 /// This function checks that the build_vector \p N in input implements a
5492 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5493 /// operation to match.
5494 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5495 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5496 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5499 /// This function only analyzes elements of \p N whose indices are
5500 /// in range [BaseIdx, LastIdx).
5501 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5503 unsigned BaseIdx, unsigned LastIdx,
5504 SDValue &V0, SDValue &V1) {
5505 EVT VT = N->getValueType(0);
5507 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5508 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5509 "Invalid Vector in input!");
5511 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5512 bool CanFold = true;
5513 unsigned ExpectedVExtractIdx = BaseIdx;
5514 unsigned NumElts = LastIdx - BaseIdx;
5515 V0 = DAG.getUNDEF(VT);
5516 V1 = DAG.getUNDEF(VT);
5518 // Check if N implements a horizontal binop.
5519 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5520 SDValue Op = N->getOperand(i + BaseIdx);
5523 if (Op->getOpcode() == ISD::UNDEF) {
5524 // Update the expected vector extract index.
5525 if (i * 2 == NumElts)
5526 ExpectedVExtractIdx = BaseIdx;
5527 ExpectedVExtractIdx += 2;
5531 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5536 SDValue Op0 = Op.getOperand(0);
5537 SDValue Op1 = Op.getOperand(1);
5539 // Try to match the following pattern:
5540 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5541 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5542 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5543 Op0.getOperand(0) == Op1.getOperand(0) &&
5544 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5545 isa<ConstantSDNode>(Op1.getOperand(1)));
5549 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5550 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5552 if (i * 2 < NumElts) {
5553 if (V0.getOpcode() == ISD::UNDEF) {
5554 V0 = Op0.getOperand(0);
5555 if (V0.getValueType() != VT)
5559 if (V1.getOpcode() == ISD::UNDEF) {
5560 V1 = Op0.getOperand(0);
5561 if (V1.getValueType() != VT)
5564 if (i * 2 == NumElts)
5565 ExpectedVExtractIdx = BaseIdx;
5568 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5569 if (I0 == ExpectedVExtractIdx)
5570 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5571 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5572 // Try to match the following dag sequence:
5573 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5574 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5578 ExpectedVExtractIdx += 2;
5584 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5585 /// a concat_vector.
5587 /// This is a helper function of LowerToHorizontalOp().
5588 /// This function expects two 256-bit vectors called V0 and V1.
5589 /// At first, each vector is split into two separate 128-bit vectors.
5590 /// Then, the resulting 128-bit vectors are used to implement two
5591 /// horizontal binary operations.
5593 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5595 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5596 /// the two new horizontal binop.
5597 /// When Mode is set, the first horizontal binop dag node would take as input
5598 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5599 /// horizontal binop dag node would take as input the lower 128-bit of V1
5600 /// and the upper 128-bit of V1.
5602 /// HADD V0_LO, V0_HI
5603 /// HADD V1_LO, V1_HI
5605 /// Otherwise, the first horizontal binop dag node takes as input the lower
5606 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5607 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5609 /// HADD V0_LO, V1_LO
5610 /// HADD V0_HI, V1_HI
5612 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5613 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5614 /// the upper 128-bits of the result.
5615 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5616 SDLoc DL, SelectionDAG &DAG,
5617 unsigned X86Opcode, bool Mode,
5618 bool isUndefLO, bool isUndefHI) {
5619 EVT VT = V0.getValueType();
5620 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5621 "Invalid nodes in input!");
5623 unsigned NumElts = VT.getVectorNumElements();
5624 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5625 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5626 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5627 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5628 EVT NewVT = V0_LO.getValueType();
5630 SDValue LO = DAG.getUNDEF(NewVT);
5631 SDValue HI = DAG.getUNDEF(NewVT);
5634 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5635 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5636 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5637 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5638 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5640 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5641 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5642 V1_LO->getOpcode() != ISD::UNDEF))
5643 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5645 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5646 V1_HI->getOpcode() != ISD::UNDEF))
5647 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5650 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5653 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5655 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5656 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5657 EVT VT = BV->getValueType(0);
5658 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5659 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5663 unsigned NumElts = VT.getVectorNumElements();
5664 SDValue InVec0 = DAG.getUNDEF(VT);
5665 SDValue InVec1 = DAG.getUNDEF(VT);
5667 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5668 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5670 // Odd-numbered elements in the input build vector are obtained from
5671 // adding two integer/float elements.
5672 // Even-numbered elements in the input build vector are obtained from
5673 // subtracting two integer/float elements.
5674 unsigned ExpectedOpcode = ISD::FSUB;
5675 unsigned NextExpectedOpcode = ISD::FADD;
5676 bool AddFound = false;
5677 bool SubFound = false;
5679 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5680 SDValue Op = BV->getOperand(i);
5682 // Skip 'undef' values.
5683 unsigned Opcode = Op.getOpcode();
5684 if (Opcode == ISD::UNDEF) {
5685 std::swap(ExpectedOpcode, NextExpectedOpcode);
5689 // Early exit if we found an unexpected opcode.
5690 if (Opcode != ExpectedOpcode)
5693 SDValue Op0 = Op.getOperand(0);
5694 SDValue Op1 = Op.getOperand(1);
5696 // Try to match the following pattern:
5697 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5698 // Early exit if we cannot match that sequence.
5699 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5700 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5701 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5702 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5703 Op0.getOperand(1) != Op1.getOperand(1))
5706 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5710 // We found a valid add/sub node. Update the information accordingly.
5716 // Update InVec0 and InVec1.
5717 if (InVec0.getOpcode() == ISD::UNDEF) {
5718 InVec0 = Op0.getOperand(0);
5719 if (InVec0.getValueType() != VT)
5722 if (InVec1.getOpcode() == ISD::UNDEF) {
5723 InVec1 = Op1.getOperand(0);
5724 if (InVec1.getValueType() != VT)
5728 // Make sure that operands in input to each add/sub node always
5729 // come from a same pair of vectors.
5730 if (InVec0 != Op0.getOperand(0)) {
5731 if (ExpectedOpcode == ISD::FSUB)
5734 // FADD is commutable. Try to commute the operands
5735 // and then test again.
5736 std::swap(Op0, Op1);
5737 if (InVec0 != Op0.getOperand(0))
5741 if (InVec1 != Op1.getOperand(0))
5744 // Update the pair of expected opcodes.
5745 std::swap(ExpectedOpcode, NextExpectedOpcode);
5748 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5749 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5750 InVec1.getOpcode() != ISD::UNDEF)
5751 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5756 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5757 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5758 const X86Subtarget *Subtarget,
5759 SelectionDAG &DAG) {
5760 EVT VT = BV->getValueType(0);
5761 unsigned NumElts = VT.getVectorNumElements();
5762 unsigned NumUndefsLO = 0;
5763 unsigned NumUndefsHI = 0;
5764 unsigned Half = NumElts/2;
5766 // Count the number of UNDEF operands in the build_vector in input.
5767 for (unsigned i = 0, e = Half; i != e; ++i)
5768 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5771 for (unsigned i = Half, e = NumElts; i != e; ++i)
5772 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5775 // Early exit if this is either a build_vector of all UNDEFs or all the
5776 // operands but one are UNDEF.
5777 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5781 SDValue InVec0, InVec1;
5782 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5783 // Try to match an SSE3 float HADD/HSUB.
5784 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5785 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5787 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5788 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5789 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5790 // Try to match an SSSE3 integer HADD/HSUB.
5791 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5792 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5794 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5795 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5798 if (!Subtarget->hasAVX())
5801 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5802 // Try to match an AVX horizontal add/sub of packed single/double
5803 // precision floating point values from 256-bit vectors.
5804 SDValue InVec2, InVec3;
5805 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5806 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5807 ((InVec0.getOpcode() == ISD::UNDEF ||
5808 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5809 ((InVec1.getOpcode() == ISD::UNDEF ||
5810 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5811 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5813 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5814 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5815 ((InVec0.getOpcode() == ISD::UNDEF ||
5816 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5817 ((InVec1.getOpcode() == ISD::UNDEF ||
5818 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5819 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5820 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5821 // Try to match an AVX2 horizontal add/sub of signed integers.
5822 SDValue InVec2, InVec3;
5824 bool CanFold = true;
5826 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5827 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5828 ((InVec0.getOpcode() == ISD::UNDEF ||
5829 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5830 ((InVec1.getOpcode() == ISD::UNDEF ||
5831 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5832 X86Opcode = X86ISD::HADD;
5833 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5834 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5835 ((InVec0.getOpcode() == ISD::UNDEF ||
5836 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5837 ((InVec1.getOpcode() == ISD::UNDEF ||
5838 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5839 X86Opcode = X86ISD::HSUB;
5844 // Fold this build_vector into a single horizontal add/sub.
5845 // Do this only if the target has AVX2.
5846 if (Subtarget->hasAVX2())
5847 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5849 // Do not try to expand this build_vector into a pair of horizontal
5850 // add/sub if we can emit a pair of scalar add/sub.
5851 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5854 // Convert this build_vector into a pair of horizontal binop followed by
5856 bool isUndefLO = NumUndefsLO == Half;
5857 bool isUndefHI = NumUndefsHI == Half;
5858 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5859 isUndefLO, isUndefHI);
5863 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5864 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5866 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5867 X86Opcode = X86ISD::HADD;
5868 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5869 X86Opcode = X86ISD::HSUB;
5870 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5871 X86Opcode = X86ISD::FHADD;
5872 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5873 X86Opcode = X86ISD::FHSUB;
5877 // Don't try to expand this build_vector into a pair of horizontal add/sub
5878 // if we can simply emit a pair of scalar add/sub.
5879 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5882 // Convert this build_vector into two horizontal add/sub followed by
5884 bool isUndefLO = NumUndefsLO == Half;
5885 bool isUndefHI = NumUndefsHI == Half;
5886 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5887 isUndefLO, isUndefHI);
5894 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5897 MVT VT = Op.getSimpleValueType();
5898 MVT ExtVT = VT.getVectorElementType();
5899 unsigned NumElems = Op.getNumOperands();
5901 // Generate vectors for predicate vectors.
5902 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5903 return LowerBUILD_VECTORvXi1(Op, DAG);
5905 // Vectors containing all zeros can be matched by pxor and xorps later
5906 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5907 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5908 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5909 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5912 return getZeroVector(VT, Subtarget, DAG, dl);
5915 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5916 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5917 // vpcmpeqd on 256-bit vectors.
5918 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5919 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5922 if (!VT.is512BitVector())
5923 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5926 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5927 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5929 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5930 return HorizontalOp;
5931 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5934 unsigned EVTBits = ExtVT.getSizeInBits();
5936 unsigned NumZero = 0;
5937 unsigned NumNonZero = 0;
5938 unsigned NonZeros = 0;
5939 bool IsAllConstants = true;
5940 SmallSet<SDValue, 8> Values;
5941 for (unsigned i = 0; i < NumElems; ++i) {
5942 SDValue Elt = Op.getOperand(i);
5943 if (Elt.getOpcode() == ISD::UNDEF)
5946 if (Elt.getOpcode() != ISD::Constant &&
5947 Elt.getOpcode() != ISD::ConstantFP)
5948 IsAllConstants = false;
5949 if (X86::isZeroNode(Elt))
5952 NonZeros |= (1 << i);
5957 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5958 if (NumNonZero == 0)
5959 return DAG.getUNDEF(VT);
5961 // Special case for single non-zero, non-undef, element.
5962 if (NumNonZero == 1) {
5963 unsigned Idx = countTrailingZeros(NonZeros);
5964 SDValue Item = Op.getOperand(Idx);
5966 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5967 // the value are obviously zero, truncate the value to i32 and do the
5968 // insertion that way. Only do this if the value is non-constant or if the
5969 // value is a constant being inserted into element 0. It is cheaper to do
5970 // a constant pool load than it is to do a movd + shuffle.
5971 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5972 (!IsAllConstants || Idx == 0)) {
5973 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5975 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5976 EVT VecVT = MVT::v4i32;
5978 // Truncate the value (which may itself be a constant) to i32, and
5979 // convert it to a vector with movd (S2V+shuffle to zero extend).
5980 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5981 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5982 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5983 Item, Idx * 2, true, Subtarget, DAG));
5987 // If we have a constant or non-constant insertion into the low element of
5988 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5989 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5990 // depending on what the source datatype is.
5993 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5995 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5996 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5997 if (VT.is512BitVector()) {
5998 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5999 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6000 Item, DAG.getIntPtrConstant(0, dl));
6002 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6003 "Expected an SSE value type!");
6004 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6005 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6006 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6009 // We can't directly insert an i8 or i16 into a vector, so zero extend
6011 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6012 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6013 if (VT.is256BitVector()) {
6014 if (Subtarget->hasAVX()) {
6015 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6016 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6018 // Without AVX, we need to extend to a 128-bit vector and then
6019 // insert into the 256-bit vector.
6020 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6021 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6022 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6025 assert(VT.is128BitVector() && "Expected an SSE value type!");
6026 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6027 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6029 return DAG.getBitcast(VT, Item);
6033 // Is it a vector logical left shift?
6034 if (NumElems == 2 && Idx == 1 &&
6035 X86::isZeroNode(Op.getOperand(0)) &&
6036 !X86::isZeroNode(Op.getOperand(1))) {
6037 unsigned NumBits = VT.getSizeInBits();
6038 return getVShift(true, VT,
6039 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6040 VT, Op.getOperand(1)),
6041 NumBits/2, DAG, *this, dl);
6044 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6047 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6048 // is a non-constant being inserted into an element other than the low one,
6049 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6050 // movd/movss) to move this into the low element, then shuffle it into
6052 if (EVTBits == 32) {
6053 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6054 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6058 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6059 if (Values.size() == 1) {
6060 if (EVTBits == 32) {
6061 // Instead of a shuffle like this:
6062 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6063 // Check if it's possible to issue this instead.
6064 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6065 unsigned Idx = countTrailingZeros(NonZeros);
6066 SDValue Item = Op.getOperand(Idx);
6067 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6068 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6073 // A vector full of immediates; various special cases are already
6074 // handled, so this is best done with a single constant-pool load.
6078 // For AVX-length vectors, see if we can use a vector load to get all of the
6079 // elements, otherwise build the individual 128-bit pieces and use
6080 // shuffles to put them in place.
6081 if (VT.is256BitVector() || VT.is512BitVector()) {
6082 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6084 // Check for a build vector of consecutive loads.
6085 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6088 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6090 // Build both the lower and upper subvector.
6091 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6092 makeArrayRef(&V[0], NumElems/2));
6093 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6094 makeArrayRef(&V[NumElems / 2], NumElems/2));
6096 // Recreate the wider vector with the lower and upper part.
6097 if (VT.is256BitVector())
6098 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6099 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6102 // Let legalizer expand 2-wide build_vectors.
6103 if (EVTBits == 64) {
6104 if (NumNonZero == 1) {
6105 // One half is zero or undef.
6106 unsigned Idx = countTrailingZeros(NonZeros);
6107 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6108 Op.getOperand(Idx));
6109 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6114 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6115 if (EVTBits == 8 && NumElems == 16)
6116 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6120 if (EVTBits == 16 && NumElems == 8)
6121 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6125 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6126 if (EVTBits == 32 && NumElems == 4)
6127 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6130 // If element VT is == 32 bits, turn it into a number of shuffles.
6131 SmallVector<SDValue, 8> V(NumElems);
6132 if (NumElems == 4 && NumZero > 0) {
6133 for (unsigned i = 0; i < 4; ++i) {
6134 bool isZero = !(NonZeros & (1 << i));
6136 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6138 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6141 for (unsigned i = 0; i < 2; ++i) {
6142 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6145 V[i] = V[i*2]; // Must be a zero vector.
6148 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6151 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6154 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6159 bool Reverse1 = (NonZeros & 0x3) == 2;
6160 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6164 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6165 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6167 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6170 if (Values.size() > 1 && VT.is128BitVector()) {
6171 // Check for a build vector of consecutive loads.
6172 for (unsigned i = 0; i < NumElems; ++i)
6173 V[i] = Op.getOperand(i);
6175 // Check for elements which are consecutive loads.
6176 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6179 // Check for a build vector from mostly shuffle plus few inserting.
6180 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6183 // For SSE 4.1, use insertps to put the high elements into the low element.
6184 if (Subtarget->hasSSE41()) {
6186 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6187 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6189 Result = DAG.getUNDEF(VT);
6191 for (unsigned i = 1; i < NumElems; ++i) {
6192 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6193 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6194 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6199 // Otherwise, expand into a number of unpckl*, start by extending each of
6200 // our (non-undef) elements to the full vector width with the element in the
6201 // bottom slot of the vector (which generates no code for SSE).
6202 for (unsigned i = 0; i < NumElems; ++i) {
6203 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6204 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6206 V[i] = DAG.getUNDEF(VT);
6209 // Next, we iteratively mix elements, e.g. for v4f32:
6210 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6211 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6212 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6213 unsigned EltStride = NumElems >> 1;
6214 while (EltStride != 0) {
6215 for (unsigned i = 0; i < EltStride; ++i) {
6216 // If V[i+EltStride] is undef and this is the first round of mixing,
6217 // then it is safe to just drop this shuffle: V[i] is already in the
6218 // right place, the one element (since it's the first round) being
6219 // inserted as undef can be dropped. This isn't safe for successive
6220 // rounds because they will permute elements within both vectors.
6221 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6222 EltStride == NumElems/2)
6225 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6234 // 256-bit AVX can use the vinsertf128 instruction
6235 // to create 256-bit vectors from two other 128-bit ones.
6236 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6238 MVT ResVT = Op.getSimpleValueType();
6240 assert((ResVT.is256BitVector() ||
6241 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6243 SDValue V1 = Op.getOperand(0);
6244 SDValue V2 = Op.getOperand(1);
6245 unsigned NumElems = ResVT.getVectorNumElements();
6246 if (ResVT.is256BitVector())
6247 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6249 if (Op.getNumOperands() == 4) {
6250 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6251 ResVT.getVectorNumElements()/2);
6252 SDValue V3 = Op.getOperand(2);
6253 SDValue V4 = Op.getOperand(3);
6254 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6255 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6257 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6260 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6261 const X86Subtarget *Subtarget,
6262 SelectionDAG & DAG) {
6264 MVT ResVT = Op.getSimpleValueType();
6265 unsigned NumOfOperands = Op.getNumOperands();
6267 assert(isPowerOf2_32(NumOfOperands) &&
6268 "Unexpected number of operands in CONCAT_VECTORS");
6270 if (NumOfOperands > 2) {
6271 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6272 ResVT.getVectorNumElements()/2);
6273 SmallVector<SDValue, 2> Ops;
6274 for (unsigned i = 0; i < NumOfOperands/2; i++)
6275 Ops.push_back(Op.getOperand(i));
6276 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6278 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6279 Ops.push_back(Op.getOperand(i));
6280 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6281 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6284 SDValue V1 = Op.getOperand(0);
6285 SDValue V2 = Op.getOperand(1);
6286 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6287 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6289 if (IsZeroV1 && IsZeroV2)
6290 return getZeroVector(ResVT, Subtarget, DAG, dl);
6292 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6293 SDValue Undef = DAG.getUNDEF(ResVT);
6294 unsigned NumElems = ResVT.getVectorNumElements();
6295 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6297 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6298 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6302 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6303 // Zero the upper bits of V1
6304 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6305 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6308 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6311 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6312 const X86Subtarget *Subtarget,
6313 SelectionDAG &DAG) {
6314 MVT VT = Op.getSimpleValueType();
6315 if (VT.getVectorElementType() == MVT::i1)
6316 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6318 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6319 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6320 Op.getNumOperands() == 4)));
6322 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6323 // from two other 128-bit ones.
6325 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6326 return LowerAVXCONCAT_VECTORS(Op, DAG);
6330 //===----------------------------------------------------------------------===//
6331 // Vector shuffle lowering
6333 // This is an experimental code path for lowering vector shuffles on x86. It is
6334 // designed to handle arbitrary vector shuffles and blends, gracefully
6335 // degrading performance as necessary. It works hard to recognize idiomatic
6336 // shuffles and lower them to optimal instruction patterns without leaving
6337 // a framework that allows reasonably efficient handling of all vector shuffle
6339 //===----------------------------------------------------------------------===//
6341 /// \brief Tiny helper function to identify a no-op mask.
6343 /// This is a somewhat boring predicate function. It checks whether the mask
6344 /// array input, which is assumed to be a single-input shuffle mask of the kind
6345 /// used by the X86 shuffle instructions (not a fully general
6346 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6347 /// in-place shuffle are 'no-op's.
6348 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6349 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6350 if (Mask[i] != -1 && Mask[i] != i)
6355 /// \brief Helper function to classify a mask as a single-input mask.
6357 /// This isn't a generic single-input test because in the vector shuffle
6358 /// lowering we canonicalize single inputs to be the first input operand. This
6359 /// means we can more quickly test for a single input by only checking whether
6360 /// an input from the second operand exists. We also assume that the size of
6361 /// mask corresponds to the size of the input vectors which isn't true in the
6362 /// fully general case.
6363 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6365 if (M >= (int)Mask.size())
6370 /// \brief Test whether there are elements crossing 128-bit lanes in this
6373 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6374 /// and we routinely test for these.
6375 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6376 int LaneSize = 128 / VT.getScalarSizeInBits();
6377 int Size = Mask.size();
6378 for (int i = 0; i < Size; ++i)
6379 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6384 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6386 /// This checks a shuffle mask to see if it is performing the same
6387 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6388 /// that it is also not lane-crossing. It may however involve a blend from the
6389 /// same lane of a second vector.
6391 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6392 /// non-trivial to compute in the face of undef lanes. The representation is
6393 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6394 /// entries from both V1 and V2 inputs to the wider mask.
6396 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6397 SmallVectorImpl<int> &RepeatedMask) {
6398 int LaneSize = 128 / VT.getScalarSizeInBits();
6399 RepeatedMask.resize(LaneSize, -1);
6400 int Size = Mask.size();
6401 for (int i = 0; i < Size; ++i) {
6404 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6405 // This entry crosses lanes, so there is no way to model this shuffle.
6408 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6409 if (RepeatedMask[i % LaneSize] == -1)
6410 // This is the first non-undef entry in this slot of a 128-bit lane.
6411 RepeatedMask[i % LaneSize] =
6412 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6413 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6414 // Found a mismatch with the repeated mask.
6420 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6423 /// This is a fast way to test a shuffle mask against a fixed pattern:
6425 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6427 /// It returns true if the mask is exactly as wide as the argument list, and
6428 /// each element of the mask is either -1 (signifying undef) or the value given
6429 /// in the argument.
6430 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6431 ArrayRef<int> ExpectedMask) {
6432 if (Mask.size() != ExpectedMask.size())
6435 int Size = Mask.size();
6437 // If the values are build vectors, we can look through them to find
6438 // equivalent inputs that make the shuffles equivalent.
6439 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6440 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6442 for (int i = 0; i < Size; ++i)
6443 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6444 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6445 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6446 if (!MaskBV || !ExpectedBV ||
6447 MaskBV->getOperand(Mask[i] % Size) !=
6448 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6455 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6457 /// This helper function produces an 8-bit shuffle immediate corresponding to
6458 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6459 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6462 /// NB: We rely heavily on "undef" masks preserving the input lane.
6463 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6464 SelectionDAG &DAG) {
6465 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6466 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6467 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6468 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6469 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6472 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6473 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6474 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6475 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6476 return DAG.getConstant(Imm, DL, MVT::i8);
6479 /// \brief Compute whether each element of a shuffle is zeroable.
6481 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6482 /// Either it is an undef element in the shuffle mask, the element of the input
6483 /// referenced is undef, or the element of the input referenced is known to be
6484 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6485 /// as many lanes with this technique as possible to simplify the remaining
6487 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6488 SDValue V1, SDValue V2) {
6489 SmallBitVector Zeroable(Mask.size(), false);
6491 while (V1.getOpcode() == ISD::BITCAST)
6492 V1 = V1->getOperand(0);
6493 while (V2.getOpcode() == ISD::BITCAST)
6494 V2 = V2->getOperand(0);
6496 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6497 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6499 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6501 // Handle the easy cases.
6502 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6507 // If this is an index into a build_vector node (which has the same number
6508 // of elements), dig out the input value and use it.
6509 SDValue V = M < Size ? V1 : V2;
6510 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6513 SDValue Input = V.getOperand(M % Size);
6514 // The UNDEF opcode check really should be dead code here, but not quite
6515 // worth asserting on (it isn't invalid, just unexpected).
6516 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6523 /// \brief Try to emit a bitmask instruction for a shuffle.
6525 /// This handles cases where we can model a blend exactly as a bitmask due to
6526 /// one of the inputs being zeroable.
6527 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6528 SDValue V2, ArrayRef<int> Mask,
6529 SelectionDAG &DAG) {
6530 MVT EltVT = VT.getScalarType();
6531 int NumEltBits = EltVT.getSizeInBits();
6532 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6533 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6534 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6536 if (EltVT.isFloatingPoint()) {
6537 Zero = DAG.getBitcast(EltVT, Zero);
6538 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6540 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6541 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6543 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6546 if (Mask[i] % Size != i)
6547 return SDValue(); // Not a blend.
6549 V = Mask[i] < Size ? V1 : V2;
6550 else if (V != (Mask[i] < Size ? V1 : V2))
6551 return SDValue(); // Can only let one input through the mask.
6553 VMaskOps[i] = AllOnes;
6556 return SDValue(); // No non-zeroable elements!
6558 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6559 V = DAG.getNode(VT.isFloatingPoint()
6560 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6565 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6567 /// This is used as a fallback approach when first class blend instructions are
6568 /// unavailable. Currently it is only suitable for integer vectors, but could
6569 /// be generalized for floating point vectors if desirable.
6570 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6571 SDValue V2, ArrayRef<int> Mask,
6572 SelectionDAG &DAG) {
6573 assert(VT.isInteger() && "Only supports integer vector types!");
6574 MVT EltVT = VT.getScalarType();
6575 int NumEltBits = EltVT.getSizeInBits();
6576 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6577 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6579 SmallVector<SDValue, 16> MaskOps;
6580 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6581 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6582 return SDValue(); // Shuffled input!
6583 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6586 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6587 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6588 // We have to cast V2 around.
6589 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6590 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6591 DAG.getBitcast(MaskVT, V1Mask),
6592 DAG.getBitcast(MaskVT, V2)));
6593 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6596 /// \brief Try to emit a blend instruction for a shuffle.
6598 /// This doesn't do any checks for the availability of instructions for blending
6599 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6600 /// be matched in the backend with the type given. What it does check for is
6601 /// that the shuffle mask is in fact a blend.
6602 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6603 SDValue V2, ArrayRef<int> Mask,
6604 const X86Subtarget *Subtarget,
6605 SelectionDAG &DAG) {
6606 unsigned BlendMask = 0;
6607 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6608 if (Mask[i] >= Size) {
6609 if (Mask[i] != i + Size)
6610 return SDValue(); // Shuffled V2 input!
6611 BlendMask |= 1u << i;
6614 if (Mask[i] >= 0 && Mask[i] != i)
6615 return SDValue(); // Shuffled V1 input!
6617 switch (VT.SimpleTy) {
6622 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6623 DAG.getConstant(BlendMask, DL, MVT::i8));
6627 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6631 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6632 // that instruction.
6633 if (Subtarget->hasAVX2()) {
6634 // Scale the blend by the number of 32-bit dwords per element.
6635 int Scale = VT.getScalarSizeInBits() / 32;
6637 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6638 if (Mask[i] >= Size)
6639 for (int j = 0; j < Scale; ++j)
6640 BlendMask |= 1u << (i * Scale + j);
6642 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6643 V1 = DAG.getBitcast(BlendVT, V1);
6644 V2 = DAG.getBitcast(BlendVT, V2);
6645 return DAG.getBitcast(
6646 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6647 DAG.getConstant(BlendMask, DL, MVT::i8)));
6651 // For integer shuffles we need to expand the mask and cast the inputs to
6652 // v8i16s prior to blending.
6653 int Scale = 8 / VT.getVectorNumElements();
6655 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6656 if (Mask[i] >= Size)
6657 for (int j = 0; j < Scale; ++j)
6658 BlendMask |= 1u << (i * Scale + j);
6660 V1 = DAG.getBitcast(MVT::v8i16, V1);
6661 V2 = DAG.getBitcast(MVT::v8i16, V2);
6662 return DAG.getBitcast(VT,
6663 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6664 DAG.getConstant(BlendMask, DL, MVT::i8)));
6668 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6669 SmallVector<int, 8> RepeatedMask;
6670 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6671 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6672 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6674 for (int i = 0; i < 8; ++i)
6675 if (RepeatedMask[i] >= 16)
6676 BlendMask |= 1u << i;
6677 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6678 DAG.getConstant(BlendMask, DL, MVT::i8));
6684 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6685 "256-bit byte-blends require AVX2 support!");
6687 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6688 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6691 // Scale the blend by the number of bytes per element.
6692 int Scale = VT.getScalarSizeInBits() / 8;
6694 // This form of blend is always done on bytes. Compute the byte vector
6696 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6698 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6699 // mix of LLVM's code generator and the x86 backend. We tell the code
6700 // generator that boolean values in the elements of an x86 vector register
6701 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6702 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6703 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6704 // of the element (the remaining are ignored) and 0 in that high bit would
6705 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6706 // the LLVM model for boolean values in vector elements gets the relevant
6707 // bit set, it is set backwards and over constrained relative to x86's
6709 SmallVector<SDValue, 32> VSELECTMask;
6710 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6711 for (int j = 0; j < Scale; ++j)
6712 VSELECTMask.push_back(
6713 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6714 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6717 V1 = DAG.getBitcast(BlendVT, V1);
6718 V2 = DAG.getBitcast(BlendVT, V2);
6719 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6720 DAG.getNode(ISD::BUILD_VECTOR, DL,
6721 BlendVT, VSELECTMask),
6726 llvm_unreachable("Not a supported integer vector type!");
6730 /// \brief Try to lower as a blend of elements from two inputs followed by
6731 /// a single-input permutation.
6733 /// This matches the pattern where we can blend elements from two inputs and
6734 /// then reduce the shuffle to a single-input permutation.
6735 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6738 SelectionDAG &DAG) {
6739 // We build up the blend mask while checking whether a blend is a viable way
6740 // to reduce the shuffle.
6741 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6742 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6744 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6748 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6750 if (BlendMask[Mask[i] % Size] == -1)
6751 BlendMask[Mask[i] % Size] = Mask[i];
6752 else if (BlendMask[Mask[i] % Size] != Mask[i])
6753 return SDValue(); // Can't blend in the needed input!
6755 PermuteMask[i] = Mask[i] % Size;
6758 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6759 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6762 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6763 /// blends and permutes.
6765 /// This matches the extremely common pattern for handling combined
6766 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6767 /// operations. It will try to pick the best arrangement of shuffles and
6769 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6773 SelectionDAG &DAG) {
6774 // Shuffle the input elements into the desired positions in V1 and V2 and
6775 // blend them together.
6776 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6777 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6778 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6779 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6780 if (Mask[i] >= 0 && Mask[i] < Size) {
6781 V1Mask[i] = Mask[i];
6783 } else if (Mask[i] >= Size) {
6784 V2Mask[i] = Mask[i] - Size;
6785 BlendMask[i] = i + Size;
6788 // Try to lower with the simpler initial blend strategy unless one of the
6789 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6790 // shuffle may be able to fold with a load or other benefit. However, when
6791 // we'll have to do 2x as many shuffles in order to achieve this, blending
6792 // first is a better strategy.
6793 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6794 if (SDValue BlendPerm =
6795 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6798 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6799 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6800 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6803 /// \brief Try to lower a vector shuffle as a byte rotation.
6805 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6806 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6807 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6808 /// try to generically lower a vector shuffle through such an pattern. It
6809 /// does not check for the profitability of lowering either as PALIGNR or
6810 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6811 /// This matches shuffle vectors that look like:
6813 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6815 /// Essentially it concatenates V1 and V2, shifts right by some number of
6816 /// elements, and takes the low elements as the result. Note that while this is
6817 /// specified as a *right shift* because x86 is little-endian, it is a *left
6818 /// rotate* of the vector lanes.
6819 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6822 const X86Subtarget *Subtarget,
6823 SelectionDAG &DAG) {
6824 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6826 int NumElts = Mask.size();
6827 int NumLanes = VT.getSizeInBits() / 128;
6828 int NumLaneElts = NumElts / NumLanes;
6830 // We need to detect various ways of spelling a rotation:
6831 // [11, 12, 13, 14, 15, 0, 1, 2]
6832 // [-1, 12, 13, 14, -1, -1, 1, -1]
6833 // [-1, -1, -1, -1, -1, -1, 1, 2]
6834 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6835 // [-1, 4, 5, 6, -1, -1, 9, -1]
6836 // [-1, 4, 5, 6, -1, -1, -1, -1]
6839 for (int l = 0; l < NumElts; l += NumLaneElts) {
6840 for (int i = 0; i < NumLaneElts; ++i) {
6841 if (Mask[l + i] == -1)
6843 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6845 // Get the mod-Size index and lane correct it.
6846 int LaneIdx = (Mask[l + i] % NumElts) - l;
6847 // Make sure it was in this lane.
6848 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6851 // Determine where a rotated vector would have started.
6852 int StartIdx = i - LaneIdx;
6854 // The identity rotation isn't interesting, stop.
6857 // If we found the tail of a vector the rotation must be the missing
6858 // front. If we found the head of a vector, it must be how much of the
6860 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6863 Rotation = CandidateRotation;
6864 else if (Rotation != CandidateRotation)
6865 // The rotations don't match, so we can't match this mask.
6868 // Compute which value this mask is pointing at.
6869 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6871 // Compute which of the two target values this index should be assigned
6872 // to. This reflects whether the high elements are remaining or the low
6873 // elements are remaining.
6874 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6876 // Either set up this value if we've not encountered it before, or check
6877 // that it remains consistent.
6880 else if (TargetV != MaskV)
6881 // This may be a rotation, but it pulls from the inputs in some
6882 // unsupported interleaving.
6887 // Check that we successfully analyzed the mask, and normalize the results.
6888 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6889 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6895 // The actual rotate instruction rotates bytes, so we need to scale the
6896 // rotation based on how many bytes are in the vector lane.
6897 int Scale = 16 / NumLaneElts;
6899 // SSSE3 targets can use the palignr instruction.
6900 if (Subtarget->hasSSSE3()) {
6901 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6902 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6903 Lo = DAG.getBitcast(AlignVT, Lo);
6904 Hi = DAG.getBitcast(AlignVT, Hi);
6906 return DAG.getBitcast(
6907 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6908 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6911 assert(VT.getSizeInBits() == 128 &&
6912 "Rotate-based lowering only supports 128-bit lowering!");
6913 assert(Mask.size() <= 16 &&
6914 "Can shuffle at most 16 bytes in a 128-bit vector!");
6916 // Default SSE2 implementation
6917 int LoByteShift = 16 - Rotation * Scale;
6918 int HiByteShift = Rotation * Scale;
6920 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6921 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6922 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6924 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6925 DAG.getConstant(LoByteShift, DL, MVT::i8));
6926 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6927 DAG.getConstant(HiByteShift, DL, MVT::i8));
6928 return DAG.getBitcast(VT,
6929 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6932 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6934 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6935 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6936 /// matches elements from one of the input vectors shuffled to the left or
6937 /// right with zeroable elements 'shifted in'. It handles both the strictly
6938 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6941 /// PSHL : (little-endian) left bit shift.
6942 /// [ zz, 0, zz, 2 ]
6943 /// [ -1, 4, zz, -1 ]
6944 /// PSRL : (little-endian) right bit shift.
6946 /// [ -1, -1, 7, zz]
6947 /// PSLLDQ : (little-endian) left byte shift
6948 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6949 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6950 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6951 /// PSRLDQ : (little-endian) right byte shift
6952 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6953 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6954 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6955 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6956 SDValue V2, ArrayRef<int> Mask,
6957 SelectionDAG &DAG) {
6958 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6960 int Size = Mask.size();
6961 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6963 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6964 for (int i = 0; i < Size; i += Scale)
6965 for (int j = 0; j < Shift; ++j)
6966 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6972 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6973 for (int i = 0; i != Size; i += Scale) {
6974 unsigned Pos = Left ? i + Shift : i;
6975 unsigned Low = Left ? i : i + Shift;
6976 unsigned Len = Scale - Shift;
6977 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6978 Low + (V == V1 ? 0 : Size)))
6982 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6983 bool ByteShift = ShiftEltBits > 64;
6984 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6985 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6986 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6988 // Normalize the scale for byte shifts to still produce an i64 element
6990 Scale = ByteShift ? Scale / 2 : Scale;
6992 // We need to round trip through the appropriate type for the shift.
6993 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6994 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6995 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6996 "Illegal integer vector type");
6997 V = DAG.getBitcast(ShiftVT, V);
6999 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7000 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7001 return DAG.getBitcast(VT, V);
7004 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7005 // keep doubling the size of the integer elements up to that. We can
7006 // then shift the elements of the integer vector by whole multiples of
7007 // their width within the elements of the larger integer vector. Test each
7008 // multiple to see if we can find a match with the moved element indices
7009 // and that the shifted in elements are all zeroable.
7010 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7011 for (int Shift = 1; Shift != Scale; ++Shift)
7012 for (bool Left : {true, false})
7013 if (CheckZeros(Shift, Scale, Left))
7014 for (SDValue V : {V1, V2})
7015 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7022 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7023 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7024 SDValue V2, ArrayRef<int> Mask,
7025 SelectionDAG &DAG) {
7026 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7027 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7029 int Size = Mask.size();
7030 int HalfSize = Size / 2;
7031 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7033 // Upper half must be undefined.
7034 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7037 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7038 // Remainder of lower half result is zero and upper half is all undef.
7039 auto LowerAsEXTRQ = [&]() {
7040 // Determine the extraction length from the part of the
7041 // lower half that isn't zeroable.
7043 for (; Len >= 0; --Len)
7044 if (!Zeroable[Len - 1])
7046 assert(Len > 0 && "Zeroable shuffle mask");
7048 // Attempt to match first Len sequential elements from the lower half.
7051 for (int i = 0; i != Len; ++i) {
7055 SDValue &V = (M < Size ? V1 : V2);
7058 // All mask elements must be in the lower half.
7062 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7073 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7074 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7075 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7076 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7077 DAG.getConstant(BitLen, DL, MVT::i8),
7078 DAG.getConstant(BitIdx, DL, MVT::i8));
7081 if (SDValue ExtrQ = LowerAsEXTRQ())
7084 // INSERTQ: Extract lowest Len elements from lower half of second source and
7085 // insert over first source, starting at Idx.
7086 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7087 auto LowerAsInsertQ = [&]() {
7088 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7091 // Attempt to match first source from mask before insertion point.
7092 if (isUndefInRange(Mask, 0, Idx)) {
7094 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7096 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7102 // Extend the extraction length looking to match both the insertion of
7103 // the second source and the remaining elements of the first.
7104 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7109 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7111 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7117 // Match the remaining elements of the lower half.
7118 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7120 } else if ((!Base || (Base == V1)) &&
7121 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7123 } else if ((!Base || (Base == V2)) &&
7124 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7131 // We may not have a base (first source) - this can safely be undefined.
7133 Base = DAG.getUNDEF(VT);
7135 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7136 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7137 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7138 DAG.getConstant(BitLen, DL, MVT::i8),
7139 DAG.getConstant(BitIdx, DL, MVT::i8));
7146 if (SDValue InsertQ = LowerAsInsertQ())
7152 /// \brief Lower a vector shuffle as a zero or any extension.
7154 /// Given a specific number of elements, element bit width, and extension
7155 /// stride, produce either a zero or any extension based on the available
7156 /// features of the subtarget.
7157 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7158 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7159 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7160 assert(Scale > 1 && "Need a scale to extend.");
7161 int NumElements = VT.getVectorNumElements();
7162 int EltBits = VT.getScalarSizeInBits();
7163 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7164 "Only 8, 16, and 32 bit elements can be extended.");
7165 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7167 // Found a valid zext mask! Try various lowering strategies based on the
7168 // input type and available ISA extensions.
7169 if (Subtarget->hasSSE41()) {
7170 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7171 NumElements / Scale);
7172 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7175 // For any extends we can cheat for larger element sizes and use shuffle
7176 // instructions that can fold with a load and/or copy.
7177 if (AnyExt && EltBits == 32) {
7178 int PSHUFDMask[4] = {0, -1, 1, -1};
7179 return DAG.getBitcast(
7180 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7181 DAG.getBitcast(MVT::v4i32, InputV),
7182 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7184 if (AnyExt && EltBits == 16 && Scale > 2) {
7185 int PSHUFDMask[4] = {0, -1, 0, -1};
7186 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7187 DAG.getBitcast(MVT::v4i32, InputV),
7188 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7189 int PSHUFHWMask[4] = {1, -1, -1, -1};
7190 return DAG.getBitcast(
7191 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7192 DAG.getBitcast(MVT::v8i16, InputV),
7193 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7196 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7198 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7199 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7200 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7202 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7203 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7204 DAG.getConstant(EltBits, DL, MVT::i8),
7205 DAG.getConstant(0, DL, MVT::i8)));
7206 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7207 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7210 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7211 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7212 DAG.getConstant(EltBits, DL, MVT::i8),
7213 DAG.getConstant(EltBits, DL, MVT::i8)));
7214 return DAG.getNode(ISD::BITCAST, DL, VT,
7215 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7218 // If this would require more than 2 unpack instructions to expand, use
7219 // pshufb when available. We can only use more than 2 unpack instructions
7220 // when zero extending i8 elements which also makes it easier to use pshufb.
7221 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7222 assert(NumElements == 16 && "Unexpected byte vector width!");
7223 SDValue PSHUFBMask[16];
7224 for (int i = 0; i < 16; ++i)
7226 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7227 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7228 return DAG.getBitcast(VT,
7229 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7230 DAG.getNode(ISD::BUILD_VECTOR, DL,
7231 MVT::v16i8, PSHUFBMask)));
7234 // Otherwise emit a sequence of unpacks.
7236 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7237 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7238 : getZeroVector(InputVT, Subtarget, DAG, DL);
7239 InputV = DAG.getBitcast(InputVT, InputV);
7240 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7244 } while (Scale > 1);
7245 return DAG.getBitcast(VT, InputV);
7248 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7250 /// This routine will try to do everything in its power to cleverly lower
7251 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7252 /// check for the profitability of this lowering, it tries to aggressively
7253 /// match this pattern. It will use all of the micro-architectural details it
7254 /// can to emit an efficient lowering. It handles both blends with all-zero
7255 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7256 /// masking out later).
7258 /// The reason we have dedicated lowering for zext-style shuffles is that they
7259 /// are both incredibly common and often quite performance sensitive.
7260 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7261 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7262 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7263 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7265 int Bits = VT.getSizeInBits();
7266 int NumElements = VT.getVectorNumElements();
7267 assert(VT.getScalarSizeInBits() <= 32 &&
7268 "Exceeds 32-bit integer zero extension limit");
7269 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7271 // Define a helper function to check a particular ext-scale and lower to it if
7273 auto Lower = [&](int Scale) -> SDValue {
7276 for (int i = 0; i < NumElements; ++i) {
7278 continue; // Valid anywhere but doesn't tell us anything.
7279 if (i % Scale != 0) {
7280 // Each of the extended elements need to be zeroable.
7284 // We no longer are in the anyext case.
7289 // Each of the base elements needs to be consecutive indices into the
7290 // same input vector.
7291 SDValue V = Mask[i] < NumElements ? V1 : V2;
7294 else if (InputV != V)
7295 return SDValue(); // Flip-flopping inputs.
7297 if (Mask[i] % NumElements != i / Scale)
7298 return SDValue(); // Non-consecutive strided elements.
7301 // If we fail to find an input, we have a zero-shuffle which should always
7302 // have already been handled.
7303 // FIXME: Maybe handle this here in case during blending we end up with one?
7307 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7308 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7311 // The widest scale possible for extending is to a 64-bit integer.
7312 assert(Bits % 64 == 0 &&
7313 "The number of bits in a vector must be divisible by 64 on x86!");
7314 int NumExtElements = Bits / 64;
7316 // Each iteration, try extending the elements half as much, but into twice as
7318 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7319 assert(NumElements % NumExtElements == 0 &&
7320 "The input vector size must be divisible by the extended size.");
7321 if (SDValue V = Lower(NumElements / NumExtElements))
7325 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7329 // Returns one of the source operands if the shuffle can be reduced to a
7330 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7331 auto CanZExtLowHalf = [&]() {
7332 for (int i = NumElements / 2; i != NumElements; ++i)
7335 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7337 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7342 if (SDValue V = CanZExtLowHalf()) {
7343 V = DAG.getBitcast(MVT::v2i64, V);
7344 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7345 return DAG.getBitcast(VT, V);
7348 // No viable ext lowering found.
7352 /// \brief Try to get a scalar value for a specific element of a vector.
7354 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7355 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7356 SelectionDAG &DAG) {
7357 MVT VT = V.getSimpleValueType();
7358 MVT EltVT = VT.getVectorElementType();
7359 while (V.getOpcode() == ISD::BITCAST)
7360 V = V.getOperand(0);
7361 // If the bitcasts shift the element size, we can't extract an equivalent
7363 MVT NewVT = V.getSimpleValueType();
7364 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7367 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7368 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7369 // Ensure the scalar operand is the same size as the destination.
7370 // FIXME: Add support for scalar truncation where possible.
7371 SDValue S = V.getOperand(Idx);
7372 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7373 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7379 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7381 /// This is particularly important because the set of instructions varies
7382 /// significantly based on whether the operand is a load or not.
7383 static bool isShuffleFoldableLoad(SDValue V) {
7384 while (V.getOpcode() == ISD::BITCAST)
7385 V = V.getOperand(0);
7387 return ISD::isNON_EXTLoad(V.getNode());
7390 /// \brief Try to lower insertion of a single element into a zero vector.
7392 /// This is a common pattern that we have especially efficient patterns to lower
7393 /// across all subtarget feature sets.
7394 static SDValue lowerVectorShuffleAsElementInsertion(
7395 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7396 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7397 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7399 MVT EltVT = VT.getVectorElementType();
7401 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7402 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7404 bool IsV1Zeroable = true;
7405 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7406 if (i != V2Index && !Zeroable[i]) {
7407 IsV1Zeroable = false;
7411 // Check for a single input from a SCALAR_TO_VECTOR node.
7412 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7413 // all the smarts here sunk into that routine. However, the current
7414 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7415 // vector shuffle lowering is dead.
7416 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7418 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7419 // We need to zext the scalar if it is smaller than an i32.
7420 V2S = DAG.getBitcast(EltVT, V2S);
7421 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7422 // Using zext to expand a narrow element won't work for non-zero
7427 // Zero-extend directly to i32.
7429 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7431 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7432 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7433 EltVT == MVT::i16) {
7434 // Either not inserting from the low element of the input or the input
7435 // element size is too small to use VZEXT_MOVL to clear the high bits.
7439 if (!IsV1Zeroable) {
7440 // If V1 can't be treated as a zero vector we have fewer options to lower
7441 // this. We can't support integer vectors or non-zero targets cheaply, and
7442 // the V1 elements can't be permuted in any way.
7443 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7444 if (!VT.isFloatingPoint() || V2Index != 0)
7446 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7447 V1Mask[V2Index] = -1;
7448 if (!isNoopShuffleMask(V1Mask))
7450 // This is essentially a special case blend operation, but if we have
7451 // general purpose blend operations, they are always faster. Bail and let
7452 // the rest of the lowering handle these as blends.
7453 if (Subtarget->hasSSE41())
7456 // Otherwise, use MOVSD or MOVSS.
7457 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7458 "Only two types of floating point element types to handle!");
7459 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7463 // This lowering only works for the low element with floating point vectors.
7464 if (VT.isFloatingPoint() && V2Index != 0)
7467 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7469 V2 = DAG.getBitcast(VT, V2);
7472 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7473 // the desired position. Otherwise it is more efficient to do a vector
7474 // shift left. We know that we can do a vector shift left because all
7475 // the inputs are zero.
7476 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7477 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7478 V2Shuffle[V2Index] = 0;
7479 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7481 V2 = DAG.getBitcast(MVT::v2i64, V2);
7483 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7484 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7485 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7486 DAG.getDataLayout(), VT)));
7487 V2 = DAG.getBitcast(VT, V2);
7493 /// \brief Try to lower broadcast of a single element.
7495 /// For convenience, this code also bundles all of the subtarget feature set
7496 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7497 /// a convenient way to factor it out.
7498 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7500 const X86Subtarget *Subtarget,
7501 SelectionDAG &DAG) {
7502 if (!Subtarget->hasAVX())
7504 if (VT.isInteger() && !Subtarget->hasAVX2())
7507 // Check that the mask is a broadcast.
7508 int BroadcastIdx = -1;
7510 if (M >= 0 && BroadcastIdx == -1)
7512 else if (M >= 0 && M != BroadcastIdx)
7515 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7516 "a sorted mask where the broadcast "
7519 // Go up the chain of (vector) values to find a scalar load that we can
7520 // combine with the broadcast.
7522 switch (V.getOpcode()) {
7523 case ISD::CONCAT_VECTORS: {
7524 int OperandSize = Mask.size() / V.getNumOperands();
7525 V = V.getOperand(BroadcastIdx / OperandSize);
7526 BroadcastIdx %= OperandSize;
7530 case ISD::INSERT_SUBVECTOR: {
7531 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7532 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7536 int BeginIdx = (int)ConstantIdx->getZExtValue();
7538 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7539 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7540 BroadcastIdx -= BeginIdx;
7551 // Check if this is a broadcast of a scalar. We special case lowering
7552 // for scalars so that we can more effectively fold with loads.
7553 // First, look through bitcast: if the original value has a larger element
7554 // type than the shuffle, the broadcast element is in essence truncated.
7555 // Make that explicit to ease folding.
7556 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7557 EVT EltVT = VT.getVectorElementType();
7558 SDValue V0 = V.getOperand(0);
7559 EVT V0VT = V0.getValueType();
7561 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7562 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7563 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7564 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7569 // Also check the simpler case, where we can directly reuse the scalar.
7570 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7571 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7572 V = V.getOperand(BroadcastIdx);
7574 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7575 // Only AVX2 has register broadcasts.
7576 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7578 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7579 // We can't broadcast from a vector register without AVX2, and we can only
7580 // broadcast from the zero-element of a vector register.
7584 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7587 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7588 // INSERTPS when the V1 elements are already in the correct locations
7589 // because otherwise we can just always use two SHUFPS instructions which
7590 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7591 // perform INSERTPS if a single V1 element is out of place and all V2
7592 // elements are zeroable.
7593 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7595 SelectionDAG &DAG) {
7596 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7597 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7598 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7599 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7601 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7604 int V1DstIndex = -1;
7605 int V2DstIndex = -1;
7606 bool V1UsedInPlace = false;
7608 for (int i = 0; i < 4; ++i) {
7609 // Synthesize a zero mask from the zeroable elements (includes undefs).
7615 // Flag if we use any V1 inputs in place.
7617 V1UsedInPlace = true;
7621 // We can only insert a single non-zeroable element.
7622 if (V1DstIndex != -1 || V2DstIndex != -1)
7626 // V1 input out of place for insertion.
7629 // V2 input for insertion.
7634 // Don't bother if we have no (non-zeroable) element for insertion.
7635 if (V1DstIndex == -1 && V2DstIndex == -1)
7638 // Determine element insertion src/dst indices. The src index is from the
7639 // start of the inserted vector, not the start of the concatenated vector.
7640 unsigned V2SrcIndex = 0;
7641 if (V1DstIndex != -1) {
7642 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7643 // and don't use the original V2 at all.
7644 V2SrcIndex = Mask[V1DstIndex];
7645 V2DstIndex = V1DstIndex;
7648 V2SrcIndex = Mask[V2DstIndex] - 4;
7651 // If no V1 inputs are used in place, then the result is created only from
7652 // the zero mask and the V2 insertion - so remove V1 dependency.
7654 V1 = DAG.getUNDEF(MVT::v4f32);
7656 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7657 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7659 // Insert the V2 element into the desired position.
7661 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7662 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7665 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7666 /// UNPCK instruction.
7668 /// This specifically targets cases where we end up with alternating between
7669 /// the two inputs, and so can permute them into something that feeds a single
7670 /// UNPCK instruction. Note that this routine only targets integer vectors
7671 /// because for floating point vectors we have a generalized SHUFPS lowering
7672 /// strategy that handles everything that doesn't *exactly* match an unpack,
7673 /// making this clever lowering unnecessary.
7674 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7675 SDValue V2, ArrayRef<int> Mask,
7676 SelectionDAG &DAG) {
7677 assert(!VT.isFloatingPoint() &&
7678 "This routine only supports integer vectors.");
7679 assert(!isSingleInputShuffleMask(Mask) &&
7680 "This routine should only be used when blending two inputs.");
7681 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7683 int Size = Mask.size();
7685 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7686 return M >= 0 && M % Size < Size / 2;
7688 int NumHiInputs = std::count_if(
7689 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7691 bool UnpackLo = NumLoInputs >= NumHiInputs;
7693 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7694 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7695 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7697 for (int i = 0; i < Size; ++i) {
7701 // Each element of the unpack contains Scale elements from this mask.
7702 int UnpackIdx = i / Scale;
7704 // We only handle the case where V1 feeds the first slots of the unpack.
7705 // We rely on canonicalization to ensure this is the case.
7706 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7709 // Setup the mask for this input. The indexing is tricky as we have to
7710 // handle the unpack stride.
7711 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7712 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7716 // If we will have to shuffle both inputs to use the unpack, check whether
7717 // we can just unpack first and shuffle the result. If so, skip this unpack.
7718 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7719 !isNoopShuffleMask(V2Mask))
7722 // Shuffle the inputs into place.
7723 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7724 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7726 // Cast the inputs to the type we will use to unpack them.
7727 V1 = DAG.getBitcast(UnpackVT, V1);
7728 V2 = DAG.getBitcast(UnpackVT, V2);
7730 // Unpack the inputs and cast the result back to the desired type.
7731 return DAG.getBitcast(
7732 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7736 // We try each unpack from the largest to the smallest to try and find one
7737 // that fits this mask.
7738 int OrigNumElements = VT.getVectorNumElements();
7739 int OrigScalarSize = VT.getScalarSizeInBits();
7740 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7741 int Scale = ScalarSize / OrigScalarSize;
7742 int NumElements = OrigNumElements / Scale;
7743 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7744 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7748 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7750 if (NumLoInputs == 0 || NumHiInputs == 0) {
7751 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7752 "We have to have *some* inputs!");
7753 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7755 // FIXME: We could consider the total complexity of the permute of each
7756 // possible unpacking. Or at the least we should consider how many
7757 // half-crossings are created.
7758 // FIXME: We could consider commuting the unpacks.
7760 SmallVector<int, 32> PermMask;
7761 PermMask.assign(Size, -1);
7762 for (int i = 0; i < Size; ++i) {
7766 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7769 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7771 return DAG.getVectorShuffle(
7772 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7774 DAG.getUNDEF(VT), PermMask);
7780 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7782 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7783 /// support for floating point shuffles but not integer shuffles. These
7784 /// instructions will incur a domain crossing penalty on some chips though so
7785 /// it is better to avoid lowering through this for integer vectors where
7787 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7788 const X86Subtarget *Subtarget,
7789 SelectionDAG &DAG) {
7791 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7792 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7793 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7794 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7795 ArrayRef<int> Mask = SVOp->getMask();
7796 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7798 if (isSingleInputShuffleMask(Mask)) {
7799 // Use low duplicate instructions for masks that match their pattern.
7800 if (Subtarget->hasSSE3())
7801 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7802 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7804 // Straight shuffle of a single input vector. Simulate this by using the
7805 // single input as both of the "inputs" to this instruction..
7806 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7808 if (Subtarget->hasAVX()) {
7809 // If we have AVX, we can use VPERMILPS which will allow folding a load
7810 // into the shuffle.
7811 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7812 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7815 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7816 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7818 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7819 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7821 // If we have a single input, insert that into V1 if we can do so cheaply.
7822 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7823 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7824 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7826 // Try inverting the insertion since for v2 masks it is easy to do and we
7827 // can't reliably sort the mask one way or the other.
7828 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7829 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7830 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7831 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7835 // Try to use one of the special instruction patterns to handle two common
7836 // blend patterns if a zero-blend above didn't work.
7837 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7838 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7839 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7840 // We can either use a special instruction to load over the low double or
7841 // to move just the low double.
7843 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7845 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7847 if (Subtarget->hasSSE41())
7848 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7852 // Use dedicated unpack instructions for masks that match their pattern.
7853 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7854 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7855 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7856 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7858 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7859 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7860 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7863 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7865 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7866 /// the integer unit to minimize domain crossing penalties. However, for blends
7867 /// it falls back to the floating point shuffle operation with appropriate bit
7869 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7870 const X86Subtarget *Subtarget,
7871 SelectionDAG &DAG) {
7873 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7874 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7875 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7876 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7877 ArrayRef<int> Mask = SVOp->getMask();
7878 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7880 if (isSingleInputShuffleMask(Mask)) {
7881 // Check for being able to broadcast a single element.
7882 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7883 Mask, Subtarget, DAG))
7886 // Straight shuffle of a single input vector. For everything from SSE2
7887 // onward this has a single fast instruction with no scary immediates.
7888 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7889 V1 = DAG.getBitcast(MVT::v4i32, V1);
7890 int WidenedMask[4] = {
7891 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7892 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7893 return DAG.getBitcast(
7895 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7896 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7898 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7899 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7900 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7901 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7903 // If we have a blend of two PACKUS operations an the blend aligns with the
7904 // low and half halves, we can just merge the PACKUS operations. This is
7905 // particularly important as it lets us merge shuffles that this routine itself
7907 auto GetPackNode = [](SDValue V) {
7908 while (V.getOpcode() == ISD::BITCAST)
7909 V = V.getOperand(0);
7911 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7913 if (SDValue V1Pack = GetPackNode(V1))
7914 if (SDValue V2Pack = GetPackNode(V2))
7915 return DAG.getBitcast(MVT::v2i64,
7916 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7917 Mask[0] == 0 ? V1Pack.getOperand(0)
7918 : V1Pack.getOperand(1),
7919 Mask[1] == 2 ? V2Pack.getOperand(0)
7920 : V2Pack.getOperand(1)));
7922 // Try to use shift instructions.
7924 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7927 // When loading a scalar and then shuffling it into a vector we can often do
7928 // the insertion cheaply.
7929 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7930 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7932 // Try inverting the insertion since for v2 masks it is easy to do and we
7933 // can't reliably sort the mask one way or the other.
7934 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7935 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7936 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7939 // We have different paths for blend lowering, but they all must use the
7940 // *exact* same predicate.
7941 bool IsBlendSupported = Subtarget->hasSSE41();
7942 if (IsBlendSupported)
7943 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7947 // Use dedicated unpack instructions for masks that match their pattern.
7948 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7949 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7950 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7951 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7953 // Try to use byte rotation instructions.
7954 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7955 if (Subtarget->hasSSSE3())
7956 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7957 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7960 // If we have direct support for blends, we should lower by decomposing into
7961 // a permute. That will be faster than the domain cross.
7962 if (IsBlendSupported)
7963 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7966 // We implement this with SHUFPD which is pretty lame because it will likely
7967 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7968 // However, all the alternatives are still more cycles and newer chips don't
7969 // have this problem. It would be really nice if x86 had better shuffles here.
7970 V1 = DAG.getBitcast(MVT::v2f64, V1);
7971 V2 = DAG.getBitcast(MVT::v2f64, V2);
7972 return DAG.getBitcast(MVT::v2i64,
7973 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7976 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7978 /// This is used to disable more specialized lowerings when the shufps lowering
7979 /// will happen to be efficient.
7980 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7981 // This routine only handles 128-bit shufps.
7982 assert(Mask.size() == 4 && "Unsupported mask size!");
7984 // To lower with a single SHUFPS we need to have the low half and high half
7985 // each requiring a single input.
7986 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7988 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7994 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7996 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7997 /// It makes no assumptions about whether this is the *best* lowering, it simply
7999 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8000 ArrayRef<int> Mask, SDValue V1,
8001 SDValue V2, SelectionDAG &DAG) {
8002 SDValue LowV = V1, HighV = V2;
8003 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8006 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8008 if (NumV2Elements == 1) {
8010 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8013 // Compute the index adjacent to V2Index and in the same half by toggling
8015 int V2AdjIndex = V2Index ^ 1;
8017 if (Mask[V2AdjIndex] == -1) {
8018 // Handles all the cases where we have a single V2 element and an undef.
8019 // This will only ever happen in the high lanes because we commute the
8020 // vector otherwise.
8022 std::swap(LowV, HighV);
8023 NewMask[V2Index] -= 4;
8025 // Handle the case where the V2 element ends up adjacent to a V1 element.
8026 // To make this work, blend them together as the first step.
8027 int V1Index = V2AdjIndex;
8028 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8029 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8030 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8032 // Now proceed to reconstruct the final blend as we have the necessary
8033 // high or low half formed.
8040 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8041 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8043 } else if (NumV2Elements == 2) {
8044 if (Mask[0] < 4 && Mask[1] < 4) {
8045 // Handle the easy case where we have V1 in the low lanes and V2 in the
8049 } else if (Mask[2] < 4 && Mask[3] < 4) {
8050 // We also handle the reversed case because this utility may get called
8051 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8052 // arrange things in the right direction.
8058 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8059 // trying to place elements directly, just blend them and set up the final
8060 // shuffle to place them.
8062 // The first two blend mask elements are for V1, the second two are for
8064 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8065 Mask[2] < 4 ? Mask[2] : Mask[3],
8066 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8067 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8068 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8069 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8071 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8074 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8075 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8076 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8077 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8080 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8081 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8084 /// \brief Lower 4-lane 32-bit floating point shuffles.
8086 /// Uses instructions exclusively from the floating point unit to minimize
8087 /// domain crossing penalties, as these are sufficient to implement all v4f32
8089 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8090 const X86Subtarget *Subtarget,
8091 SelectionDAG &DAG) {
8093 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8094 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8095 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8096 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8097 ArrayRef<int> Mask = SVOp->getMask();
8098 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8101 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8103 if (NumV2Elements == 0) {
8104 // Check for being able to broadcast a single element.
8105 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8106 Mask, Subtarget, DAG))
8109 // Use even/odd duplicate instructions for masks that match their pattern.
8110 if (Subtarget->hasSSE3()) {
8111 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8112 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8113 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8114 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8117 if (Subtarget->hasAVX()) {
8118 // If we have AVX, we can use VPERMILPS which will allow folding a load
8119 // into the shuffle.
8120 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8121 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8124 // Otherwise, use a straight shuffle of a single input vector. We pass the
8125 // input vector to both operands to simulate this with a SHUFPS.
8126 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8127 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8130 // There are special ways we can lower some single-element blends. However, we
8131 // have custom ways we can lower more complex single-element blends below that
8132 // we defer to if both this and BLENDPS fail to match, so restrict this to
8133 // when the V2 input is targeting element 0 of the mask -- that is the fast
8135 if (NumV2Elements == 1 && Mask[0] >= 4)
8136 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8137 Mask, Subtarget, DAG))
8140 if (Subtarget->hasSSE41()) {
8141 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8145 // Use INSERTPS if we can complete the shuffle efficiently.
8146 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8149 if (!isSingleSHUFPSMask(Mask))
8150 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8151 DL, MVT::v4f32, V1, V2, Mask, DAG))
8155 // Use dedicated unpack instructions for masks that match their pattern.
8156 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8157 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8158 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8159 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8160 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8161 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8162 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8163 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8165 // Otherwise fall back to a SHUFPS lowering strategy.
8166 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8169 /// \brief Lower 4-lane i32 vector shuffles.
8171 /// We try to handle these with integer-domain shuffles where we can, but for
8172 /// blends we use the floating point domain blend instructions.
8173 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8174 const X86Subtarget *Subtarget,
8175 SelectionDAG &DAG) {
8177 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8178 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8179 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8180 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8181 ArrayRef<int> Mask = SVOp->getMask();
8182 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8184 // Whenever we can lower this as a zext, that instruction is strictly faster
8185 // than any alternative. It also allows us to fold memory operands into the
8186 // shuffle in many cases.
8187 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8188 Mask, Subtarget, DAG))
8192 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8194 if (NumV2Elements == 0) {
8195 // Check for being able to broadcast a single element.
8196 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8197 Mask, Subtarget, DAG))
8200 // Straight shuffle of a single input vector. For everything from SSE2
8201 // onward this has a single fast instruction with no scary immediates.
8202 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8203 // but we aren't actually going to use the UNPCK instruction because doing
8204 // so prevents folding a load into this instruction or making a copy.
8205 const int UnpackLoMask[] = {0, 0, 1, 1};
8206 const int UnpackHiMask[] = {2, 2, 3, 3};
8207 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8208 Mask = UnpackLoMask;
8209 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8210 Mask = UnpackHiMask;
8212 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8213 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8216 // Try to use shift instructions.
8218 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8221 // There are special ways we can lower some single-element blends.
8222 if (NumV2Elements == 1)
8223 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8224 Mask, Subtarget, DAG))
8227 // We have different paths for blend lowering, but they all must use the
8228 // *exact* same predicate.
8229 bool IsBlendSupported = Subtarget->hasSSE41();
8230 if (IsBlendSupported)
8231 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8235 if (SDValue Masked =
8236 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8239 // Use dedicated unpack instructions for masks that match their pattern.
8240 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8241 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8242 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8243 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8244 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8245 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8246 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8247 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8249 // Try to use byte rotation instructions.
8250 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8251 if (Subtarget->hasSSSE3())
8252 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8253 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8256 // If we have direct support for blends, we should lower by decomposing into
8257 // a permute. That will be faster than the domain cross.
8258 if (IsBlendSupported)
8259 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8262 // Try to lower by permuting the inputs into an unpack instruction.
8263 if (SDValue Unpack =
8264 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8267 // We implement this with SHUFPS because it can blend from two vectors.
8268 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8269 // up the inputs, bypassing domain shift penalties that we would encur if we
8270 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8272 return DAG.getBitcast(
8274 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8275 DAG.getBitcast(MVT::v4f32, V2), Mask));
8278 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8279 /// shuffle lowering, and the most complex part.
8281 /// The lowering strategy is to try to form pairs of input lanes which are
8282 /// targeted at the same half of the final vector, and then use a dword shuffle
8283 /// to place them onto the right half, and finally unpack the paired lanes into
8284 /// their final position.
8286 /// The exact breakdown of how to form these dword pairs and align them on the
8287 /// correct sides is really tricky. See the comments within the function for
8288 /// more of the details.
8290 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8291 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8292 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8293 /// vector, form the analogous 128-bit 8-element Mask.
8294 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8295 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8296 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8297 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8298 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8300 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8301 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8302 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8304 SmallVector<int, 4> LoInputs;
8305 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8306 [](int M) { return M >= 0; });
8307 std::sort(LoInputs.begin(), LoInputs.end());
8308 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8309 SmallVector<int, 4> HiInputs;
8310 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8311 [](int M) { return M >= 0; });
8312 std::sort(HiInputs.begin(), HiInputs.end());
8313 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8315 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8316 int NumHToL = LoInputs.size() - NumLToL;
8318 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8319 int NumHToH = HiInputs.size() - NumLToH;
8320 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8321 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8322 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8323 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8325 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8326 // such inputs we can swap two of the dwords across the half mark and end up
8327 // with <=2 inputs to each half in each half. Once there, we can fall through
8328 // to the generic code below. For example:
8330 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8331 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8333 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8334 // and an existing 2-into-2 on the other half. In this case we may have to
8335 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8336 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8337 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8338 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8339 // half than the one we target for fixing) will be fixed when we re-enter this
8340 // path. We will also combine away any sequence of PSHUFD instructions that
8341 // result into a single instruction. Here is an example of the tricky case:
8343 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8344 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8346 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8348 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8349 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8351 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8352 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8354 // The result is fine to be handled by the generic logic.
8355 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8356 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8357 int AOffset, int BOffset) {
8358 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8359 "Must call this with A having 3 or 1 inputs from the A half.");
8360 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8361 "Must call this with B having 1 or 3 inputs from the B half.");
8362 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8363 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8365 bool ThreeAInputs = AToAInputs.size() == 3;
8367 // Compute the index of dword with only one word among the three inputs in
8368 // a half by taking the sum of the half with three inputs and subtracting
8369 // the sum of the actual three inputs. The difference is the remaining
8372 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8373 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8374 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8375 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8376 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8377 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8378 int TripleNonInputIdx =
8379 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8380 TripleDWord = TripleNonInputIdx / 2;
8382 // We use xor with one to compute the adjacent DWord to whichever one the
8384 OneInputDWord = (OneInput / 2) ^ 1;
8386 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8387 // and BToA inputs. If there is also such a problem with the BToB and AToB
8388 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8389 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8390 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8391 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8392 // Compute how many inputs will be flipped by swapping these DWords. We
8394 // to balance this to ensure we don't form a 3-1 shuffle in the other
8396 int NumFlippedAToBInputs =
8397 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8398 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8399 int NumFlippedBToBInputs =
8400 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8401 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8402 if ((NumFlippedAToBInputs == 1 &&
8403 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8404 (NumFlippedBToBInputs == 1 &&
8405 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8406 // We choose whether to fix the A half or B half based on whether that
8407 // half has zero flipped inputs. At zero, we may not be able to fix it
8408 // with that half. We also bias towards fixing the B half because that
8409 // will more commonly be the high half, and we have to bias one way.
8410 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8411 ArrayRef<int> Inputs) {
8412 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8413 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8414 PinnedIdx ^ 1) != Inputs.end();
8415 // Determine whether the free index is in the flipped dword or the
8416 // unflipped dword based on where the pinned index is. We use this bit
8417 // in an xor to conditionally select the adjacent dword.
8418 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8419 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8420 FixFreeIdx) != Inputs.end();
8421 if (IsFixIdxInput == IsFixFreeIdxInput)
8423 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8424 FixFreeIdx) != Inputs.end();
8425 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8426 "We need to be changing the number of flipped inputs!");
8427 int PSHUFHalfMask[] = {0, 1, 2, 3};
8428 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8429 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8431 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8434 if (M != -1 && M == FixIdx)
8436 else if (M != -1 && M == FixFreeIdx)
8439 if (NumFlippedBToBInputs != 0) {
8441 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8442 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8444 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8445 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8446 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8451 int PSHUFDMask[] = {0, 1, 2, 3};
8452 PSHUFDMask[ADWord] = BDWord;
8453 PSHUFDMask[BDWord] = ADWord;
8456 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8457 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8459 // Adjust the mask to match the new locations of A and B.
8461 if (M != -1 && M/2 == ADWord)
8462 M = 2 * BDWord + M % 2;
8463 else if (M != -1 && M/2 == BDWord)
8464 M = 2 * ADWord + M % 2;
8466 // Recurse back into this routine to re-compute state now that this isn't
8467 // a 3 and 1 problem.
8468 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8471 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8472 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8473 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8474 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8476 // At this point there are at most two inputs to the low and high halves from
8477 // each half. That means the inputs can always be grouped into dwords and
8478 // those dwords can then be moved to the correct half with a dword shuffle.
8479 // We use at most one low and one high word shuffle to collect these paired
8480 // inputs into dwords, and finally a dword shuffle to place them.
8481 int PSHUFLMask[4] = {-1, -1, -1, -1};
8482 int PSHUFHMask[4] = {-1, -1, -1, -1};
8483 int PSHUFDMask[4] = {-1, -1, -1, -1};
8485 // First fix the masks for all the inputs that are staying in their
8486 // original halves. This will then dictate the targets of the cross-half
8488 auto fixInPlaceInputs =
8489 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8490 MutableArrayRef<int> SourceHalfMask,
8491 MutableArrayRef<int> HalfMask, int HalfOffset) {
8492 if (InPlaceInputs.empty())
8494 if (InPlaceInputs.size() == 1) {
8495 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8496 InPlaceInputs[0] - HalfOffset;
8497 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8500 if (IncomingInputs.empty()) {
8501 // Just fix all of the in place inputs.
8502 for (int Input : InPlaceInputs) {
8503 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8504 PSHUFDMask[Input / 2] = Input / 2;
8509 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8510 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8511 InPlaceInputs[0] - HalfOffset;
8512 // Put the second input next to the first so that they are packed into
8513 // a dword. We find the adjacent index by toggling the low bit.
8514 int AdjIndex = InPlaceInputs[0] ^ 1;
8515 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8516 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8517 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8519 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8520 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8522 // Now gather the cross-half inputs and place them into a free dword of
8523 // their target half.
8524 // FIXME: This operation could almost certainly be simplified dramatically to
8525 // look more like the 3-1 fixing operation.
8526 auto moveInputsToRightHalf = [&PSHUFDMask](
8527 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8528 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8529 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8531 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8532 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8534 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8536 int LowWord = Word & ~1;
8537 int HighWord = Word | 1;
8538 return isWordClobbered(SourceHalfMask, LowWord) ||
8539 isWordClobbered(SourceHalfMask, HighWord);
8542 if (IncomingInputs.empty())
8545 if (ExistingInputs.empty()) {
8546 // Map any dwords with inputs from them into the right half.
8547 for (int Input : IncomingInputs) {
8548 // If the source half mask maps over the inputs, turn those into
8549 // swaps and use the swapped lane.
8550 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8551 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8552 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8553 Input - SourceOffset;
8554 // We have to swap the uses in our half mask in one sweep.
8555 for (int &M : HalfMask)
8556 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8558 else if (M == Input)
8559 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8561 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8562 Input - SourceOffset &&
8563 "Previous placement doesn't match!");
8565 // Note that this correctly re-maps both when we do a swap and when
8566 // we observe the other side of the swap above. We rely on that to
8567 // avoid swapping the members of the input list directly.
8568 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8571 // Map the input's dword into the correct half.
8572 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8573 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8575 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8577 "Previous placement doesn't match!");
8580 // And just directly shift any other-half mask elements to be same-half
8581 // as we will have mirrored the dword containing the element into the
8582 // same position within that half.
8583 for (int &M : HalfMask)
8584 if (M >= SourceOffset && M < SourceOffset + 4) {
8585 M = M - SourceOffset + DestOffset;
8586 assert(M >= 0 && "This should never wrap below zero!");
8591 // Ensure we have the input in a viable dword of its current half. This
8592 // is particularly tricky because the original position may be clobbered
8593 // by inputs being moved and *staying* in that half.
8594 if (IncomingInputs.size() == 1) {
8595 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8596 int InputFixed = std::find(std::begin(SourceHalfMask),
8597 std::end(SourceHalfMask), -1) -
8598 std::begin(SourceHalfMask) + SourceOffset;
8599 SourceHalfMask[InputFixed - SourceOffset] =
8600 IncomingInputs[0] - SourceOffset;
8601 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8603 IncomingInputs[0] = InputFixed;
8605 } else if (IncomingInputs.size() == 2) {
8606 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8607 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8608 // We have two non-adjacent or clobbered inputs we need to extract from
8609 // the source half. To do this, we need to map them into some adjacent
8610 // dword slot in the source mask.
8611 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8612 IncomingInputs[1] - SourceOffset};
8614 // If there is a free slot in the source half mask adjacent to one of
8615 // the inputs, place the other input in it. We use (Index XOR 1) to
8616 // compute an adjacent index.
8617 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8618 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8619 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8620 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8621 InputsFixed[1] = InputsFixed[0] ^ 1;
8622 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8623 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8624 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8625 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8626 InputsFixed[0] = InputsFixed[1] ^ 1;
8627 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8628 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8629 // The two inputs are in the same DWord but it is clobbered and the
8630 // adjacent DWord isn't used at all. Move both inputs to the free
8632 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8633 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8634 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8635 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8637 // The only way we hit this point is if there is no clobbering
8638 // (because there are no off-half inputs to this half) and there is no
8639 // free slot adjacent to one of the inputs. In this case, we have to
8640 // swap an input with a non-input.
8641 for (int i = 0; i < 4; ++i)
8642 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8643 "We can't handle any clobbers here!");
8644 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8645 "Cannot have adjacent inputs here!");
8647 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8648 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8650 // We also have to update the final source mask in this case because
8651 // it may need to undo the above swap.
8652 for (int &M : FinalSourceHalfMask)
8653 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8654 M = InputsFixed[1] + SourceOffset;
8655 else if (M == InputsFixed[1] + SourceOffset)
8656 M = (InputsFixed[0] ^ 1) + SourceOffset;
8658 InputsFixed[1] = InputsFixed[0] ^ 1;
8661 // Point everything at the fixed inputs.
8662 for (int &M : HalfMask)
8663 if (M == IncomingInputs[0])
8664 M = InputsFixed[0] + SourceOffset;
8665 else if (M == IncomingInputs[1])
8666 M = InputsFixed[1] + SourceOffset;
8668 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8669 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8672 llvm_unreachable("Unhandled input size!");
8675 // Now hoist the DWord down to the right half.
8676 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8677 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8678 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8679 for (int &M : HalfMask)
8680 for (int Input : IncomingInputs)
8682 M = FreeDWord * 2 + Input % 2;
8684 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8685 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8686 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8687 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8689 // Now enact all the shuffles we've computed to move the inputs into their
8691 if (!isNoopShuffleMask(PSHUFLMask))
8692 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8693 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8694 if (!isNoopShuffleMask(PSHUFHMask))
8695 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8696 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8697 if (!isNoopShuffleMask(PSHUFDMask))
8700 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8701 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8703 // At this point, each half should contain all its inputs, and we can then
8704 // just shuffle them into their final position.
8705 assert(std::count_if(LoMask.begin(), LoMask.end(),
8706 [](int M) { return M >= 4; }) == 0 &&
8707 "Failed to lift all the high half inputs to the low mask!");
8708 assert(std::count_if(HiMask.begin(), HiMask.end(),
8709 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8710 "Failed to lift all the low half inputs to the high mask!");
8712 // Do a half shuffle for the low mask.
8713 if (!isNoopShuffleMask(LoMask))
8714 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8715 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8717 // Do a half shuffle with the high mask after shifting its values down.
8718 for (int &M : HiMask)
8721 if (!isNoopShuffleMask(HiMask))
8722 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8723 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8728 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8729 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8730 SDValue V2, ArrayRef<int> Mask,
8731 SelectionDAG &DAG, bool &V1InUse,
8733 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8739 int Size = Mask.size();
8740 int Scale = 16 / Size;
8741 for (int i = 0; i < 16; ++i) {
8742 if (Mask[i / Scale] == -1) {
8743 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8745 const int ZeroMask = 0x80;
8746 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8748 int V2Idx = Mask[i / Scale] < Size
8750 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8751 if (Zeroable[i / Scale])
8752 V1Idx = V2Idx = ZeroMask;
8753 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8754 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8755 V1InUse |= (ZeroMask != V1Idx);
8756 V2InUse |= (ZeroMask != V2Idx);
8761 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8762 DAG.getBitcast(MVT::v16i8, V1),
8763 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8765 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8766 DAG.getBitcast(MVT::v16i8, V2),
8767 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8769 // If we need shuffled inputs from both, blend the two.
8771 if (V1InUse && V2InUse)
8772 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8774 V = V1InUse ? V1 : V2;
8776 // Cast the result back to the correct type.
8777 return DAG.getBitcast(VT, V);
8780 /// \brief Generic lowering of 8-lane i16 shuffles.
8782 /// This handles both single-input shuffles and combined shuffle/blends with
8783 /// two inputs. The single input shuffles are immediately delegated to
8784 /// a dedicated lowering routine.
8786 /// The blends are lowered in one of three fundamental ways. If there are few
8787 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8788 /// of the input is significantly cheaper when lowered as an interleaving of
8789 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8790 /// halves of the inputs separately (making them have relatively few inputs)
8791 /// and then concatenate them.
8792 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8793 const X86Subtarget *Subtarget,
8794 SelectionDAG &DAG) {
8796 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8797 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8798 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8800 ArrayRef<int> OrigMask = SVOp->getMask();
8801 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8802 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8803 MutableArrayRef<int> Mask(MaskStorage);
8805 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8807 // Whenever we can lower this as a zext, that instruction is strictly faster
8808 // than any alternative.
8809 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8810 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8813 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8815 auto isV2 = [](int M) { return M >= 8; };
8817 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8819 if (NumV2Inputs == 0) {
8820 // Check for being able to broadcast a single element.
8821 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8822 Mask, Subtarget, DAG))
8825 // Try to use shift instructions.
8827 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8830 // Use dedicated unpack instructions for masks that match their pattern.
8831 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8832 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8833 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8834 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8836 // Try to use byte rotation instructions.
8837 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8838 Mask, Subtarget, DAG))
8841 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8845 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8846 "All single-input shuffles should be canonicalized to be V1-input "
8849 // Try to use shift instructions.
8851 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8854 // See if we can use SSE4A Extraction / Insertion.
8855 if (Subtarget->hasSSE4A())
8856 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8859 // There are special ways we can lower some single-element blends.
8860 if (NumV2Inputs == 1)
8861 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8862 Mask, Subtarget, DAG))
8865 // We have different paths for blend lowering, but they all must use the
8866 // *exact* same predicate.
8867 bool IsBlendSupported = Subtarget->hasSSE41();
8868 if (IsBlendSupported)
8869 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8873 if (SDValue Masked =
8874 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8877 // Use dedicated unpack instructions for masks that match their pattern.
8878 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8879 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8880 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8881 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8883 // Try to use byte rotation instructions.
8884 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8885 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8888 if (SDValue BitBlend =
8889 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8892 if (SDValue Unpack =
8893 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8896 // If we can't directly blend but can use PSHUFB, that will be better as it
8897 // can both shuffle and set up the inefficient blend.
8898 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8899 bool V1InUse, V2InUse;
8900 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8904 // We can always bit-blend if we have to so the fallback strategy is to
8905 // decompose into single-input permutes and blends.
8906 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8910 /// \brief Check whether a compaction lowering can be done by dropping even
8911 /// elements and compute how many times even elements must be dropped.
8913 /// This handles shuffles which take every Nth element where N is a power of
8914 /// two. Example shuffle masks:
8916 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8917 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8918 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8919 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8920 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8921 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8923 /// Any of these lanes can of course be undef.
8925 /// This routine only supports N <= 3.
8926 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8929 /// \returns N above, or the number of times even elements must be dropped if
8930 /// there is such a number. Otherwise returns zero.
8931 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8932 // Figure out whether we're looping over two inputs or just one.
8933 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8935 // The modulus for the shuffle vector entries is based on whether this is
8936 // a single input or not.
8937 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8938 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8939 "We should only be called with masks with a power-of-2 size!");
8941 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8943 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8944 // and 2^3 simultaneously. This is because we may have ambiguity with
8945 // partially undef inputs.
8946 bool ViableForN[3] = {true, true, true};
8948 for (int i = 0, e = Mask.size(); i < e; ++i) {
8949 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8954 bool IsAnyViable = false;
8955 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8956 if (ViableForN[j]) {
8959 // The shuffle mask must be equal to (i * 2^N) % M.
8960 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8963 ViableForN[j] = false;
8965 // Early exit if we exhaust the possible powers of two.
8970 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8974 // Return 0 as there is no viable power of two.
8978 /// \brief Generic lowering of v16i8 shuffles.
8980 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8981 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8982 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8983 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8985 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8986 const X86Subtarget *Subtarget,
8987 SelectionDAG &DAG) {
8989 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8990 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8991 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8992 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8993 ArrayRef<int> Mask = SVOp->getMask();
8994 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8996 // Try to use shift instructions.
8998 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9001 // Try to use byte rotation instructions.
9002 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9003 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9006 // Try to use a zext lowering.
9007 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9008 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9011 // See if we can use SSE4A Extraction / Insertion.
9012 if (Subtarget->hasSSE4A())
9013 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9017 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9019 // For single-input shuffles, there are some nicer lowering tricks we can use.
9020 if (NumV2Elements == 0) {
9021 // Check for being able to broadcast a single element.
9022 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9023 Mask, Subtarget, DAG))
9026 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9027 // Notably, this handles splat and partial-splat shuffles more efficiently.
9028 // However, it only makes sense if the pre-duplication shuffle simplifies
9029 // things significantly. Currently, this means we need to be able to
9030 // express the pre-duplication shuffle as an i16 shuffle.
9032 // FIXME: We should check for other patterns which can be widened into an
9033 // i16 shuffle as well.
9034 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9035 for (int i = 0; i < 16; i += 2)
9036 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9041 auto tryToWidenViaDuplication = [&]() -> SDValue {
9042 if (!canWidenViaDuplication(Mask))
9044 SmallVector<int, 4> LoInputs;
9045 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9046 [](int M) { return M >= 0 && M < 8; });
9047 std::sort(LoInputs.begin(), LoInputs.end());
9048 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9050 SmallVector<int, 4> HiInputs;
9051 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9052 [](int M) { return M >= 8; });
9053 std::sort(HiInputs.begin(), HiInputs.end());
9054 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9057 bool TargetLo = LoInputs.size() >= HiInputs.size();
9058 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9059 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9061 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9062 SmallDenseMap<int, int, 8> LaneMap;
9063 for (int I : InPlaceInputs) {
9064 PreDupI16Shuffle[I/2] = I/2;
9067 int j = TargetLo ? 0 : 4, je = j + 4;
9068 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9069 // Check if j is already a shuffle of this input. This happens when
9070 // there are two adjacent bytes after we move the low one.
9071 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9072 // If we haven't yet mapped the input, search for a slot into which
9074 while (j < je && PreDupI16Shuffle[j] != -1)
9078 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9081 // Map this input with the i16 shuffle.
9082 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9085 // Update the lane map based on the mapping we ended up with.
9086 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9088 V1 = DAG.getBitcast(
9090 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9091 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9093 // Unpack the bytes to form the i16s that will be shuffled into place.
9094 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9095 MVT::v16i8, V1, V1);
9097 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9098 for (int i = 0; i < 16; ++i)
9099 if (Mask[i] != -1) {
9100 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9101 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9102 if (PostDupI16Shuffle[i / 2] == -1)
9103 PostDupI16Shuffle[i / 2] = MappedMask;
9105 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9106 "Conflicting entrties in the original shuffle!");
9108 return DAG.getBitcast(
9110 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9111 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9113 if (SDValue V = tryToWidenViaDuplication())
9117 if (SDValue Masked =
9118 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9121 // Use dedicated unpack instructions for masks that match their pattern.
9122 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9123 0, 16, 1, 17, 2, 18, 3, 19,
9125 4, 20, 5, 21, 6, 22, 7, 23}))
9126 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9127 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9128 8, 24, 9, 25, 10, 26, 11, 27,
9130 12, 28, 13, 29, 14, 30, 15, 31}))
9131 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9133 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9134 // with PSHUFB. It is important to do this before we attempt to generate any
9135 // blends but after all of the single-input lowerings. If the single input
9136 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9137 // want to preserve that and we can DAG combine any longer sequences into
9138 // a PSHUFB in the end. But once we start blending from multiple inputs,
9139 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9140 // and there are *very* few patterns that would actually be faster than the
9141 // PSHUFB approach because of its ability to zero lanes.
9143 // FIXME: The only exceptions to the above are blends which are exact
9144 // interleavings with direct instructions supporting them. We currently don't
9145 // handle those well here.
9146 if (Subtarget->hasSSSE3()) {
9147 bool V1InUse = false;
9148 bool V2InUse = false;
9150 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9151 DAG, V1InUse, V2InUse);
9153 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9154 // do so. This avoids using them to handle blends-with-zero which is
9155 // important as a single pshufb is significantly faster for that.
9156 if (V1InUse && V2InUse) {
9157 if (Subtarget->hasSSE41())
9158 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9159 Mask, Subtarget, DAG))
9162 // We can use an unpack to do the blending rather than an or in some
9163 // cases. Even though the or may be (very minorly) more efficient, we
9164 // preference this lowering because there are common cases where part of
9165 // the complexity of the shuffles goes away when we do the final blend as
9167 // FIXME: It might be worth trying to detect if the unpack-feeding
9168 // shuffles will both be pshufb, in which case we shouldn't bother with
9170 if (SDValue Unpack =
9171 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9178 // There are special ways we can lower some single-element blends.
9179 if (NumV2Elements == 1)
9180 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9181 Mask, Subtarget, DAG))
9184 if (SDValue BitBlend =
9185 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9188 // Check whether a compaction lowering can be done. This handles shuffles
9189 // which take every Nth element for some even N. See the helper function for
9192 // We special case these as they can be particularly efficiently handled with
9193 // the PACKUSB instruction on x86 and they show up in common patterns of
9194 // rearranging bytes to truncate wide elements.
9195 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9196 // NumEvenDrops is the power of two stride of the elements. Another way of
9197 // thinking about it is that we need to drop the even elements this many
9198 // times to get the original input.
9199 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9201 // First we need to zero all the dropped bytes.
9202 assert(NumEvenDrops <= 3 &&
9203 "No support for dropping even elements more than 3 times.");
9204 // We use the mask type to pick which bytes are preserved based on how many
9205 // elements are dropped.
9206 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9207 SDValue ByteClearMask = DAG.getBitcast(
9208 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9209 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9211 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9213 // Now pack things back together.
9214 V1 = DAG.getBitcast(MVT::v8i16, V1);
9215 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9216 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9217 for (int i = 1; i < NumEvenDrops; ++i) {
9218 Result = DAG.getBitcast(MVT::v8i16, Result);
9219 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9225 // Handle multi-input cases by blending single-input shuffles.
9226 if (NumV2Elements > 0)
9227 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9230 // The fallback path for single-input shuffles widens this into two v8i16
9231 // vectors with unpacks, shuffles those, and then pulls them back together
9235 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9236 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9237 for (int i = 0; i < 16; ++i)
9239 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9241 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9243 SDValue VLoHalf, VHiHalf;
9244 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9245 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9247 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9248 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9249 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9250 [](int M) { return M >= 0 && M % 2 == 1; })) {
9251 // Use a mask to drop the high bytes.
9252 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9253 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9254 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9256 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9257 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9259 // Squash the masks to point directly into VLoHalf.
9260 for (int &M : LoBlendMask)
9263 for (int &M : HiBlendMask)
9267 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9268 // VHiHalf so that we can blend them as i16s.
9269 VLoHalf = DAG.getBitcast(
9270 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9271 VHiHalf = DAG.getBitcast(
9272 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9275 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9276 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9278 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9281 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9283 /// This routine breaks down the specific type of 128-bit shuffle and
9284 /// dispatches to the lowering routines accordingly.
9285 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9286 MVT VT, const X86Subtarget *Subtarget,
9287 SelectionDAG &DAG) {
9288 switch (VT.SimpleTy) {
9290 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9292 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9294 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9296 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9298 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9300 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9303 llvm_unreachable("Unimplemented!");
9307 /// \brief Helper function to test whether a shuffle mask could be
9308 /// simplified by widening the elements being shuffled.
9310 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9311 /// leaves it in an unspecified state.
9313 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9314 /// shuffle masks. The latter have the special property of a '-2' representing
9315 /// a zero-ed lane of a vector.
9316 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9317 SmallVectorImpl<int> &WidenedMask) {
9318 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9319 // If both elements are undef, its trivial.
9320 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9321 WidenedMask.push_back(SM_SentinelUndef);
9325 // Check for an undef mask and a mask value properly aligned to fit with
9326 // a pair of values. If we find such a case, use the non-undef mask's value.
9327 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9328 WidenedMask.push_back(Mask[i + 1] / 2);
9331 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9332 WidenedMask.push_back(Mask[i] / 2);
9336 // When zeroing, we need to spread the zeroing across both lanes to widen.
9337 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9338 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9339 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9340 WidenedMask.push_back(SM_SentinelZero);
9346 // Finally check if the two mask values are adjacent and aligned with
9348 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9349 WidenedMask.push_back(Mask[i] / 2);
9353 // Otherwise we can't safely widen the elements used in this shuffle.
9356 assert(WidenedMask.size() == Mask.size() / 2 &&
9357 "Incorrect size of mask after widening the elements!");
9362 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9364 /// This routine just extracts two subvectors, shuffles them independently, and
9365 /// then concatenates them back together. This should work effectively with all
9366 /// AVX vector shuffle types.
9367 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9368 SDValue V2, ArrayRef<int> Mask,
9369 SelectionDAG &DAG) {
9370 assert(VT.getSizeInBits() >= 256 &&
9371 "Only for 256-bit or wider vector shuffles!");
9372 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9373 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9375 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9376 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9378 int NumElements = VT.getVectorNumElements();
9379 int SplitNumElements = NumElements / 2;
9380 MVT ScalarVT = VT.getScalarType();
9381 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9383 // Rather than splitting build-vectors, just build two narrower build
9384 // vectors. This helps shuffling with splats and zeros.
9385 auto SplitVector = [&](SDValue V) {
9386 while (V.getOpcode() == ISD::BITCAST)
9387 V = V->getOperand(0);
9389 MVT OrigVT = V.getSimpleValueType();
9390 int OrigNumElements = OrigVT.getVectorNumElements();
9391 int OrigSplitNumElements = OrigNumElements / 2;
9392 MVT OrigScalarVT = OrigVT.getScalarType();
9393 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9397 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9399 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9400 DAG.getIntPtrConstant(0, DL));
9401 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9402 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9405 SmallVector<SDValue, 16> LoOps, HiOps;
9406 for (int i = 0; i < OrigSplitNumElements; ++i) {
9407 LoOps.push_back(BV->getOperand(i));
9408 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9410 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9411 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9413 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9414 DAG.getBitcast(SplitVT, HiV));
9417 SDValue LoV1, HiV1, LoV2, HiV2;
9418 std::tie(LoV1, HiV1) = SplitVector(V1);
9419 std::tie(LoV2, HiV2) = SplitVector(V2);
9421 // Now create two 4-way blends of these half-width vectors.
9422 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9423 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9424 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9425 for (int i = 0; i < SplitNumElements; ++i) {
9426 int M = HalfMask[i];
9427 if (M >= NumElements) {
9428 if (M >= NumElements + SplitNumElements)
9432 V2BlendMask.push_back(M - NumElements);
9433 V1BlendMask.push_back(-1);
9434 BlendMask.push_back(SplitNumElements + i);
9435 } else if (M >= 0) {
9436 if (M >= SplitNumElements)
9440 V2BlendMask.push_back(-1);
9441 V1BlendMask.push_back(M);
9442 BlendMask.push_back(i);
9444 V2BlendMask.push_back(-1);
9445 V1BlendMask.push_back(-1);
9446 BlendMask.push_back(-1);
9450 // Because the lowering happens after all combining takes place, we need to
9451 // manually combine these blend masks as much as possible so that we create
9452 // a minimal number of high-level vector shuffle nodes.
9454 // First try just blending the halves of V1 or V2.
9455 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9456 return DAG.getUNDEF(SplitVT);
9457 if (!UseLoV2 && !UseHiV2)
9458 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9459 if (!UseLoV1 && !UseHiV1)
9460 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9462 SDValue V1Blend, V2Blend;
9463 if (UseLoV1 && UseHiV1) {
9465 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9467 // We only use half of V1 so map the usage down into the final blend mask.
9468 V1Blend = UseLoV1 ? LoV1 : HiV1;
9469 for (int i = 0; i < SplitNumElements; ++i)
9470 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9471 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9473 if (UseLoV2 && UseHiV2) {
9475 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9477 // We only use half of V2 so map the usage down into the final blend mask.
9478 V2Blend = UseLoV2 ? LoV2 : HiV2;
9479 for (int i = 0; i < SplitNumElements; ++i)
9480 if (BlendMask[i] >= SplitNumElements)
9481 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9483 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9485 SDValue Lo = HalfBlend(LoMask);
9486 SDValue Hi = HalfBlend(HiMask);
9487 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9490 /// \brief Either split a vector in halves or decompose the shuffles and the
9493 /// This is provided as a good fallback for many lowerings of non-single-input
9494 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9495 /// between splitting the shuffle into 128-bit components and stitching those
9496 /// back together vs. extracting the single-input shuffles and blending those
9498 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9499 SDValue V2, ArrayRef<int> Mask,
9500 SelectionDAG &DAG) {
9501 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9502 "lower single-input shuffles as it "
9503 "could then recurse on itself.");
9504 int Size = Mask.size();
9506 // If this can be modeled as a broadcast of two elements followed by a blend,
9507 // prefer that lowering. This is especially important because broadcasts can
9508 // often fold with memory operands.
9509 auto DoBothBroadcast = [&] {
9510 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9513 if (V2BroadcastIdx == -1)
9514 V2BroadcastIdx = M - Size;
9515 else if (M - Size != V2BroadcastIdx)
9517 } else if (M >= 0) {
9518 if (V1BroadcastIdx == -1)
9520 else if (M != V1BroadcastIdx)
9525 if (DoBothBroadcast())
9526 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9529 // If the inputs all stem from a single 128-bit lane of each input, then we
9530 // split them rather than blending because the split will decompose to
9531 // unusually few instructions.
9532 int LaneCount = VT.getSizeInBits() / 128;
9533 int LaneSize = Size / LaneCount;
9534 SmallBitVector LaneInputs[2];
9535 LaneInputs[0].resize(LaneCount, false);
9536 LaneInputs[1].resize(LaneCount, false);
9537 for (int i = 0; i < Size; ++i)
9539 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9540 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9541 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9543 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9544 // that the decomposed single-input shuffles don't end up here.
9545 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9548 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9549 /// a permutation and blend of those lanes.
9551 /// This essentially blends the out-of-lane inputs to each lane into the lane
9552 /// from a permuted copy of the vector. This lowering strategy results in four
9553 /// instructions in the worst case for a single-input cross lane shuffle which
9554 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9555 /// of. Special cases for each particular shuffle pattern should be handled
9556 /// prior to trying this lowering.
9557 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9558 SDValue V1, SDValue V2,
9560 SelectionDAG &DAG) {
9561 // FIXME: This should probably be generalized for 512-bit vectors as well.
9562 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9563 int LaneSize = Mask.size() / 2;
9565 // If there are only inputs from one 128-bit lane, splitting will in fact be
9566 // less expensive. The flags track whether the given lane contains an element
9567 // that crosses to another lane.
9568 bool LaneCrossing[2] = {false, false};
9569 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9570 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9571 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9572 if (!LaneCrossing[0] || !LaneCrossing[1])
9573 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9575 if (isSingleInputShuffleMask(Mask)) {
9576 SmallVector<int, 32> FlippedBlendMask;
9577 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9578 FlippedBlendMask.push_back(
9579 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9581 : Mask[i] % LaneSize +
9582 (i / LaneSize) * LaneSize + Size));
9584 // Flip the vector, and blend the results which should now be in-lane. The
9585 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9586 // 5 for the high source. The value 3 selects the high half of source 2 and
9587 // the value 2 selects the low half of source 2. We only use source 2 to
9588 // allow folding it into a memory operand.
9589 unsigned PERMMask = 3 | 2 << 4;
9590 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9591 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9592 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9595 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9596 // will be handled by the above logic and a blend of the results, much like
9597 // other patterns in AVX.
9598 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9601 /// \brief Handle lowering 2-lane 128-bit shuffles.
9602 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9603 SDValue V2, ArrayRef<int> Mask,
9604 const X86Subtarget *Subtarget,
9605 SelectionDAG &DAG) {
9606 // TODO: If minimizing size and one of the inputs is a zero vector and the
9607 // the zero vector has only one use, we could use a VPERM2X128 to save the
9608 // instruction bytes needed to explicitly generate the zero vector.
9610 // Blends are faster and handle all the non-lane-crossing cases.
9611 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9615 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9616 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9618 // If either input operand is a zero vector, use VPERM2X128 because its mask
9619 // allows us to replace the zero input with an implicit zero.
9620 if (!IsV1Zero && !IsV2Zero) {
9621 // Check for patterns which can be matched with a single insert of a 128-bit
9623 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9624 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9625 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9626 VT.getVectorNumElements() / 2);
9627 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9628 DAG.getIntPtrConstant(0, DL));
9629 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9630 OnlyUsesV1 ? V1 : V2,
9631 DAG.getIntPtrConstant(0, DL));
9632 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9636 // Otherwise form a 128-bit permutation. After accounting for undefs,
9637 // convert the 64-bit shuffle mask selection values into 128-bit
9638 // selection bits by dividing the indexes by 2 and shifting into positions
9639 // defined by a vperm2*128 instruction's immediate control byte.
9641 // The immediate permute control byte looks like this:
9642 // [1:0] - select 128 bits from sources for low half of destination
9644 // [3] - zero low half of destination
9645 // [5:4] - select 128 bits from sources for high half of destination
9647 // [7] - zero high half of destination
9649 int MaskLO = Mask[0];
9650 if (MaskLO == SM_SentinelUndef)
9651 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9653 int MaskHI = Mask[2];
9654 if (MaskHI == SM_SentinelUndef)
9655 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9657 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9659 // If either input is a zero vector, replace it with an undef input.
9660 // Shuffle mask values < 4 are selecting elements of V1.
9661 // Shuffle mask values >= 4 are selecting elements of V2.
9662 // Adjust each half of the permute mask by clearing the half that was
9663 // selecting the zero vector and setting the zero mask bit.
9665 V1 = DAG.getUNDEF(VT);
9667 PermMask = (PermMask & 0xf0) | 0x08;
9669 PermMask = (PermMask & 0x0f) | 0x80;
9672 V2 = DAG.getUNDEF(VT);
9674 PermMask = (PermMask & 0xf0) | 0x08;
9676 PermMask = (PermMask & 0x0f) | 0x80;
9679 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9680 DAG.getConstant(PermMask, DL, MVT::i8));
9683 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9684 /// shuffling each lane.
9686 /// This will only succeed when the result of fixing the 128-bit lanes results
9687 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9688 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9689 /// the lane crosses early and then use simpler shuffles within each lane.
9691 /// FIXME: It might be worthwhile at some point to support this without
9692 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9693 /// in x86 only floating point has interesting non-repeating shuffles, and even
9694 /// those are still *marginally* more expensive.
9695 static SDValue lowerVectorShuffleByMerging128BitLanes(
9696 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9697 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9698 assert(!isSingleInputShuffleMask(Mask) &&
9699 "This is only useful with multiple inputs.");
9701 int Size = Mask.size();
9702 int LaneSize = 128 / VT.getScalarSizeInBits();
9703 int NumLanes = Size / LaneSize;
9704 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9706 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9707 // check whether the in-128-bit lane shuffles share a repeating pattern.
9708 SmallVector<int, 4> Lanes;
9709 Lanes.resize(NumLanes, -1);
9710 SmallVector<int, 4> InLaneMask;
9711 InLaneMask.resize(LaneSize, -1);
9712 for (int i = 0; i < Size; ++i) {
9716 int j = i / LaneSize;
9719 // First entry we've seen for this lane.
9720 Lanes[j] = Mask[i] / LaneSize;
9721 } else if (Lanes[j] != Mask[i] / LaneSize) {
9722 // This doesn't match the lane selected previously!
9726 // Check that within each lane we have a consistent shuffle mask.
9727 int k = i % LaneSize;
9728 if (InLaneMask[k] < 0) {
9729 InLaneMask[k] = Mask[i] % LaneSize;
9730 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9731 // This doesn't fit a repeating in-lane mask.
9736 // First shuffle the lanes into place.
9737 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9738 VT.getSizeInBits() / 64);
9739 SmallVector<int, 8> LaneMask;
9740 LaneMask.resize(NumLanes * 2, -1);
9741 for (int i = 0; i < NumLanes; ++i)
9742 if (Lanes[i] >= 0) {
9743 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9744 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9747 V1 = DAG.getBitcast(LaneVT, V1);
9748 V2 = DAG.getBitcast(LaneVT, V2);
9749 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9751 // Cast it back to the type we actually want.
9752 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9754 // Now do a simple shuffle that isn't lane crossing.
9755 SmallVector<int, 8> NewMask;
9756 NewMask.resize(Size, -1);
9757 for (int i = 0; i < Size; ++i)
9759 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9760 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9761 "Must not introduce lane crosses at this point!");
9763 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9766 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9769 /// This returns true if the elements from a particular input are already in the
9770 /// slot required by the given mask and require no permutation.
9771 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9772 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9773 int Size = Mask.size();
9774 for (int i = 0; i < Size; ++i)
9775 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9781 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9782 ArrayRef<int> Mask, SDValue V1,
9783 SDValue V2, SelectionDAG &DAG) {
9785 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9786 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9787 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9788 int NumElts = VT.getVectorNumElements();
9789 bool ShufpdMask = true;
9790 bool CommutableMask = true;
9791 unsigned Immediate = 0;
9792 for (int i = 0; i < NumElts; ++i) {
9795 int Val = (i & 6) + NumElts * (i & 1);
9796 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9797 if (Mask[i] < Val || Mask[i] > Val + 1)
9799 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9800 CommutableMask = false;
9801 Immediate |= (Mask[i] % 2) << i;
9804 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9805 DAG.getConstant(Immediate, DL, MVT::i8));
9807 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9808 DAG.getConstant(Immediate, DL, MVT::i8));
9812 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9814 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9815 /// isn't available.
9816 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9817 const X86Subtarget *Subtarget,
9818 SelectionDAG &DAG) {
9820 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9821 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9822 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9823 ArrayRef<int> Mask = SVOp->getMask();
9824 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9826 SmallVector<int, 4> WidenedMask;
9827 if (canWidenShuffleElements(Mask, WidenedMask))
9828 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9831 if (isSingleInputShuffleMask(Mask)) {
9832 // Check for being able to broadcast a single element.
9833 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9834 Mask, Subtarget, DAG))
9837 // Use low duplicate instructions for masks that match their pattern.
9838 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9839 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9841 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9842 // Non-half-crossing single input shuffles can be lowerid with an
9843 // interleaved permutation.
9844 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9845 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9846 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9847 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9850 // With AVX2 we have direct support for this permutation.
9851 if (Subtarget->hasAVX2())
9852 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9853 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9855 // Otherwise, fall back.
9856 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9860 // X86 has dedicated unpack instructions that can handle specific blend
9861 // operations: UNPCKH and UNPCKL.
9862 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9863 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9864 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9865 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9866 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9867 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9868 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9869 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9871 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9875 // Check if the blend happens to exactly fit that of SHUFPD.
9877 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9880 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9881 // shuffle. However, if we have AVX2 and either inputs are already in place,
9882 // we will be able to shuffle even across lanes the other input in a single
9883 // instruction so skip this pattern.
9884 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9885 isShuffleMaskInputInPlace(1, Mask))))
9886 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9887 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9890 // If we have AVX2 then we always want to lower with a blend because an v4 we
9891 // can fully permute the elements.
9892 if (Subtarget->hasAVX2())
9893 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9896 // Otherwise fall back on generic lowering.
9897 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9900 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9902 /// This routine is only called when we have AVX2 and thus a reasonable
9903 /// instruction set for v4i64 shuffling..
9904 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9905 const X86Subtarget *Subtarget,
9906 SelectionDAG &DAG) {
9908 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9909 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9910 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9911 ArrayRef<int> Mask = SVOp->getMask();
9912 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9913 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9915 SmallVector<int, 4> WidenedMask;
9916 if (canWidenShuffleElements(Mask, WidenedMask))
9917 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9920 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9924 // Check for being able to broadcast a single element.
9925 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9926 Mask, Subtarget, DAG))
9929 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9930 // use lower latency instructions that will operate on both 128-bit lanes.
9931 SmallVector<int, 2> RepeatedMask;
9932 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9933 if (isSingleInputShuffleMask(Mask)) {
9934 int PSHUFDMask[] = {-1, -1, -1, -1};
9935 for (int i = 0; i < 2; ++i)
9936 if (RepeatedMask[i] >= 0) {
9937 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9938 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9940 return DAG.getBitcast(
9942 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9943 DAG.getBitcast(MVT::v8i32, V1),
9944 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9948 // AVX2 provides a direct instruction for permuting a single input across
9950 if (isSingleInputShuffleMask(Mask))
9951 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9952 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9954 // Try to use shift instructions.
9956 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9959 // Use dedicated unpack instructions for masks that match their pattern.
9960 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9961 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9962 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9963 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9964 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9965 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9966 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9967 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9969 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9970 // shuffle. However, if we have AVX2 and either inputs are already in place,
9971 // we will be able to shuffle even across lanes the other input in a single
9972 // instruction so skip this pattern.
9973 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9974 isShuffleMaskInputInPlace(1, Mask))))
9975 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9976 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9979 // Otherwise fall back on generic blend lowering.
9980 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9984 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9986 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9987 /// isn't available.
9988 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9989 const X86Subtarget *Subtarget,
9990 SelectionDAG &DAG) {
9992 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9993 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9994 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9995 ArrayRef<int> Mask = SVOp->getMask();
9996 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9998 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10002 // Check for being able to broadcast a single element.
10003 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10004 Mask, Subtarget, DAG))
10007 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10008 // options to efficiently lower the shuffle.
10009 SmallVector<int, 4> RepeatedMask;
10010 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10011 assert(RepeatedMask.size() == 4 &&
10012 "Repeated masks must be half the mask width!");
10014 // Use even/odd duplicate instructions for masks that match their pattern.
10015 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10016 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10017 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10018 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10020 if (isSingleInputShuffleMask(Mask))
10021 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10022 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10024 // Use dedicated unpack instructions for masks that match their pattern.
10025 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10026 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10027 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10028 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10029 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10030 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10031 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10032 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10034 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10035 // have already handled any direct blends. We also need to squash the
10036 // repeated mask into a simulated v4f32 mask.
10037 for (int i = 0; i < 4; ++i)
10038 if (RepeatedMask[i] >= 8)
10039 RepeatedMask[i] -= 4;
10040 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10043 // If we have a single input shuffle with different shuffle patterns in the
10044 // two 128-bit lanes use the variable mask to VPERMILPS.
10045 if (isSingleInputShuffleMask(Mask)) {
10046 SDValue VPermMask[8];
10047 for (int i = 0; i < 8; ++i)
10048 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10049 : DAG.getConstant(Mask[i], DL, MVT::i32);
10050 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10051 return DAG.getNode(
10052 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10053 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10055 if (Subtarget->hasAVX2())
10056 return DAG.getNode(
10057 X86ISD::VPERMV, DL, MVT::v8f32,
10058 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10059 MVT::v8i32, VPermMask)),
10062 // Otherwise, fall back.
10063 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10067 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10069 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10070 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10073 // If we have AVX2 then we always want to lower with a blend because at v8 we
10074 // can fully permute the elements.
10075 if (Subtarget->hasAVX2())
10076 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10079 // Otherwise fall back on generic lowering.
10080 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10083 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10085 /// This routine is only called when we have AVX2 and thus a reasonable
10086 /// instruction set for v8i32 shuffling..
10087 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10088 const X86Subtarget *Subtarget,
10089 SelectionDAG &DAG) {
10091 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10092 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10093 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10094 ArrayRef<int> Mask = SVOp->getMask();
10095 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10096 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10098 // Whenever we can lower this as a zext, that instruction is strictly faster
10099 // than any alternative. It also allows us to fold memory operands into the
10100 // shuffle in many cases.
10101 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10102 Mask, Subtarget, DAG))
10105 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10109 // Check for being able to broadcast a single element.
10110 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10111 Mask, Subtarget, DAG))
10114 // If the shuffle mask is repeated in each 128-bit lane we can use more
10115 // efficient instructions that mirror the shuffles across the two 128-bit
10117 SmallVector<int, 4> RepeatedMask;
10118 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10119 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10120 if (isSingleInputShuffleMask(Mask))
10121 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10122 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10124 // Use dedicated unpack instructions for masks that match their pattern.
10125 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10126 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10127 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10128 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10129 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10130 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10131 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10132 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10135 // Try to use shift instructions.
10136 if (SDValue Shift =
10137 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10140 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10141 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10144 // If the shuffle patterns aren't repeated but it is a single input, directly
10145 // generate a cross-lane VPERMD instruction.
10146 if (isSingleInputShuffleMask(Mask)) {
10147 SDValue VPermMask[8];
10148 for (int i = 0; i < 8; ++i)
10149 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10150 : DAG.getConstant(Mask[i], DL, MVT::i32);
10151 return DAG.getNode(
10152 X86ISD::VPERMV, DL, MVT::v8i32,
10153 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10156 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10158 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10159 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10162 // Otherwise fall back on generic blend lowering.
10163 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10167 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10169 /// This routine is only called when we have AVX2 and thus a reasonable
10170 /// instruction set for v16i16 shuffling..
10171 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10172 const X86Subtarget *Subtarget,
10173 SelectionDAG &DAG) {
10175 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10176 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10177 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10178 ArrayRef<int> Mask = SVOp->getMask();
10179 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10180 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10182 // Whenever we can lower this as a zext, that instruction is strictly faster
10183 // than any alternative. It also allows us to fold memory operands into the
10184 // shuffle in many cases.
10185 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10186 Mask, Subtarget, DAG))
10189 // Check for being able to broadcast a single element.
10190 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10191 Mask, Subtarget, DAG))
10194 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10198 // Use dedicated unpack instructions for masks that match their pattern.
10199 if (isShuffleEquivalent(V1, V2, Mask,
10200 {// First 128-bit lane:
10201 0, 16, 1, 17, 2, 18, 3, 19,
10202 // Second 128-bit lane:
10203 8, 24, 9, 25, 10, 26, 11, 27}))
10204 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10205 if (isShuffleEquivalent(V1, V2, Mask,
10206 {// First 128-bit lane:
10207 4, 20, 5, 21, 6, 22, 7, 23,
10208 // Second 128-bit lane:
10209 12, 28, 13, 29, 14, 30, 15, 31}))
10210 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10212 // Try to use shift instructions.
10213 if (SDValue Shift =
10214 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10217 // Try to use byte rotation instructions.
10218 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10219 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10222 if (isSingleInputShuffleMask(Mask)) {
10223 // There are no generalized cross-lane shuffle operations available on i16
10225 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10226 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10229 SmallVector<int, 8> RepeatedMask;
10230 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10231 // As this is a single-input shuffle, the repeated mask should be
10232 // a strictly valid v8i16 mask that we can pass through to the v8i16
10233 // lowering to handle even the v16 case.
10234 return lowerV8I16GeneralSingleInputVectorShuffle(
10235 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10238 SDValue PSHUFBMask[32];
10239 for (int i = 0; i < 16; ++i) {
10240 if (Mask[i] == -1) {
10241 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10245 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10246 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10247 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10248 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10250 return DAG.getBitcast(MVT::v16i16,
10251 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10252 DAG.getBitcast(MVT::v32i8, V1),
10253 DAG.getNode(ISD::BUILD_VECTOR, DL,
10254 MVT::v32i8, PSHUFBMask)));
10257 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10259 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10260 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10263 // Otherwise fall back on generic lowering.
10264 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10267 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10269 /// This routine is only called when we have AVX2 and thus a reasonable
10270 /// instruction set for v32i8 shuffling..
10271 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10272 const X86Subtarget *Subtarget,
10273 SelectionDAG &DAG) {
10275 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10276 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10277 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10278 ArrayRef<int> Mask = SVOp->getMask();
10279 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10280 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10282 // Whenever we can lower this as a zext, that instruction is strictly faster
10283 // than any alternative. It also allows us to fold memory operands into the
10284 // shuffle in many cases.
10285 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10286 Mask, Subtarget, DAG))
10289 // Check for being able to broadcast a single element.
10290 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10291 Mask, Subtarget, DAG))
10294 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10298 // Use dedicated unpack instructions for masks that match their pattern.
10299 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10301 if (isShuffleEquivalent(
10303 {// First 128-bit lane:
10304 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10305 // Second 128-bit lane:
10306 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10307 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10308 if (isShuffleEquivalent(
10310 {// First 128-bit lane:
10311 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10312 // Second 128-bit lane:
10313 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10314 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10316 // Try to use shift instructions.
10317 if (SDValue Shift =
10318 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10321 // Try to use byte rotation instructions.
10322 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10323 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10326 if (isSingleInputShuffleMask(Mask)) {
10327 // There are no generalized cross-lane shuffle operations available on i8
10329 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10330 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10333 SDValue PSHUFBMask[32];
10334 for (int i = 0; i < 32; ++i)
10337 ? DAG.getUNDEF(MVT::i8)
10338 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10341 return DAG.getNode(
10342 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10343 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10346 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10348 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10349 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10352 // Otherwise fall back on generic lowering.
10353 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10356 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10358 /// This routine either breaks down the specific type of a 256-bit x86 vector
10359 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10360 /// together based on the available instructions.
10361 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10362 MVT VT, const X86Subtarget *Subtarget,
10363 SelectionDAG &DAG) {
10365 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10366 ArrayRef<int> Mask = SVOp->getMask();
10368 // If we have a single input to the zero element, insert that into V1 if we
10369 // can do so cheaply.
10370 int NumElts = VT.getVectorNumElements();
10371 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10372 return M >= NumElts;
10375 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10376 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10377 DL, VT, V1, V2, Mask, Subtarget, DAG))
10380 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10381 // check for those subtargets here and avoid much of the subtarget querying in
10382 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10383 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10384 // floating point types there eventually, just immediately cast everything to
10385 // a float and operate entirely in that domain.
10386 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10387 int ElementBits = VT.getScalarSizeInBits();
10388 if (ElementBits < 32)
10389 // No floating point type available, decompose into 128-bit vectors.
10390 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10392 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10393 VT.getVectorNumElements());
10394 V1 = DAG.getBitcast(FpVT, V1);
10395 V2 = DAG.getBitcast(FpVT, V2);
10396 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10399 switch (VT.SimpleTy) {
10401 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10403 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10405 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10407 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10409 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10411 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10414 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10418 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10419 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10420 const X86Subtarget *Subtarget,
10421 SelectionDAG &DAG) {
10423 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10424 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10425 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10426 ArrayRef<int> Mask = SVOp->getMask();
10427 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10429 // X86 has dedicated unpack instructions that can handle specific blend
10430 // operations: UNPCKH and UNPCKL.
10431 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10432 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10433 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10434 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10436 // FIXME: Implement direct support for this type!
10437 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10440 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10441 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10442 const X86Subtarget *Subtarget,
10443 SelectionDAG &DAG) {
10445 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10446 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10447 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10448 ArrayRef<int> Mask = SVOp->getMask();
10449 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10451 // Use dedicated unpack instructions for masks that match their pattern.
10452 if (isShuffleEquivalent(V1, V2, Mask,
10453 {// First 128-bit lane.
10454 0, 16, 1, 17, 4, 20, 5, 21,
10455 // Second 128-bit lane.
10456 8, 24, 9, 25, 12, 28, 13, 29}))
10457 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10458 if (isShuffleEquivalent(V1, V2, Mask,
10459 {// First 128-bit lane.
10460 2, 18, 3, 19, 6, 22, 7, 23,
10461 // Second 128-bit lane.
10462 10, 26, 11, 27, 14, 30, 15, 31}))
10463 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10465 // FIXME: Implement direct support for this type!
10466 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10469 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10470 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10471 const X86Subtarget *Subtarget,
10472 SelectionDAG &DAG) {
10474 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10475 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10476 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10477 ArrayRef<int> Mask = SVOp->getMask();
10478 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10480 // X86 has dedicated unpack instructions that can handle specific blend
10481 // operations: UNPCKH and UNPCKL.
10482 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10483 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10484 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10485 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10487 // FIXME: Implement direct support for this type!
10488 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10491 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10492 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10493 const X86Subtarget *Subtarget,
10494 SelectionDAG &DAG) {
10496 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10497 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10498 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10499 ArrayRef<int> Mask = SVOp->getMask();
10500 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10502 // Use dedicated unpack instructions for masks that match their pattern.
10503 if (isShuffleEquivalent(V1, V2, Mask,
10504 {// First 128-bit lane.
10505 0, 16, 1, 17, 4, 20, 5, 21,
10506 // Second 128-bit lane.
10507 8, 24, 9, 25, 12, 28, 13, 29}))
10508 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10509 if (isShuffleEquivalent(V1, V2, Mask,
10510 {// First 128-bit lane.
10511 2, 18, 3, 19, 6, 22, 7, 23,
10512 // Second 128-bit lane.
10513 10, 26, 11, 27, 14, 30, 15, 31}))
10514 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10516 // FIXME: Implement direct support for this type!
10517 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10520 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10521 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10522 const X86Subtarget *Subtarget,
10523 SelectionDAG &DAG) {
10525 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10526 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10527 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10528 ArrayRef<int> Mask = SVOp->getMask();
10529 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10530 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10532 // FIXME: Implement direct support for this type!
10533 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10536 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10537 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10538 const X86Subtarget *Subtarget,
10539 SelectionDAG &DAG) {
10541 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10542 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10544 ArrayRef<int> Mask = SVOp->getMask();
10545 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10546 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10548 // FIXME: Implement direct support for this type!
10549 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10552 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10554 /// This routine either breaks down the specific type of a 512-bit x86 vector
10555 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10556 /// together based on the available instructions.
10557 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10558 MVT VT, const X86Subtarget *Subtarget,
10559 SelectionDAG &DAG) {
10561 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10562 ArrayRef<int> Mask = SVOp->getMask();
10563 assert(Subtarget->hasAVX512() &&
10564 "Cannot lower 512-bit vectors w/ basic ISA!");
10566 // Check for being able to broadcast a single element.
10567 if (SDValue Broadcast =
10568 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10571 // Dispatch to each element type for lowering. If we don't have supprot for
10572 // specific element type shuffles at 512 bits, immediately split them and
10573 // lower them. Each lowering routine of a given type is allowed to assume that
10574 // the requisite ISA extensions for that element type are available.
10575 switch (VT.SimpleTy) {
10577 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10579 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10581 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10583 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10585 if (Subtarget->hasBWI())
10586 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10589 if (Subtarget->hasBWI())
10590 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10594 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10597 // Otherwise fall back on splitting.
10598 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10601 /// \brief Top-level lowering for x86 vector shuffles.
10603 /// This handles decomposition, canonicalization, and lowering of all x86
10604 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10605 /// above in helper routines. The canonicalization attempts to widen shuffles
10606 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10607 /// s.t. only one of the two inputs needs to be tested, etc.
10608 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10609 SelectionDAG &DAG) {
10610 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10611 ArrayRef<int> Mask = SVOp->getMask();
10612 SDValue V1 = Op.getOperand(0);
10613 SDValue V2 = Op.getOperand(1);
10614 MVT VT = Op.getSimpleValueType();
10615 int NumElements = VT.getVectorNumElements();
10618 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10620 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10621 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10622 if (V1IsUndef && V2IsUndef)
10623 return DAG.getUNDEF(VT);
10625 // When we create a shuffle node we put the UNDEF node to second operand,
10626 // but in some cases the first operand may be transformed to UNDEF.
10627 // In this case we should just commute the node.
10629 return DAG.getCommutedVectorShuffle(*SVOp);
10631 // Check for non-undef masks pointing at an undef vector and make the masks
10632 // undef as well. This makes it easier to match the shuffle based solely on
10636 if (M >= NumElements) {
10637 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10638 for (int &M : NewMask)
10639 if (M >= NumElements)
10641 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10644 // We actually see shuffles that are entirely re-arrangements of a set of
10645 // zero inputs. This mostly happens while decomposing complex shuffles into
10646 // simple ones. Directly lower these as a buildvector of zeros.
10647 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10648 if (Zeroable.all())
10649 return getZeroVector(VT, Subtarget, DAG, dl);
10651 // Try to collapse shuffles into using a vector type with fewer elements but
10652 // wider element types. We cap this to not form integers or floating point
10653 // elements wider than 64 bits, but it might be interesting to form i128
10654 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10655 SmallVector<int, 16> WidenedMask;
10656 if (VT.getScalarSizeInBits() < 64 &&
10657 canWidenShuffleElements(Mask, WidenedMask)) {
10658 MVT NewEltVT = VT.isFloatingPoint()
10659 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10660 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10661 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10662 // Make sure that the new vector type is legal. For example, v2f64 isn't
10664 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10665 V1 = DAG.getBitcast(NewVT, V1);
10666 V2 = DAG.getBitcast(NewVT, V2);
10667 return DAG.getBitcast(
10668 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10672 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10673 for (int M : SVOp->getMask())
10675 ++NumUndefElements;
10676 else if (M < NumElements)
10681 // Commute the shuffle as needed such that more elements come from V1 than
10682 // V2. This allows us to match the shuffle pattern strictly on how many
10683 // elements come from V1 without handling the symmetric cases.
10684 if (NumV2Elements > NumV1Elements)
10685 return DAG.getCommutedVectorShuffle(*SVOp);
10687 // When the number of V1 and V2 elements are the same, try to minimize the
10688 // number of uses of V2 in the low half of the vector. When that is tied,
10689 // ensure that the sum of indices for V1 is equal to or lower than the sum
10690 // indices for V2. When those are equal, try to ensure that the number of odd
10691 // indices for V1 is lower than the number of odd indices for V2.
10692 if (NumV1Elements == NumV2Elements) {
10693 int LowV1Elements = 0, LowV2Elements = 0;
10694 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10695 if (M >= NumElements)
10699 if (LowV2Elements > LowV1Elements) {
10700 return DAG.getCommutedVectorShuffle(*SVOp);
10701 } else if (LowV2Elements == LowV1Elements) {
10702 int SumV1Indices = 0, SumV2Indices = 0;
10703 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10704 if (SVOp->getMask()[i] >= NumElements)
10706 else if (SVOp->getMask()[i] >= 0)
10708 if (SumV2Indices < SumV1Indices) {
10709 return DAG.getCommutedVectorShuffle(*SVOp);
10710 } else if (SumV2Indices == SumV1Indices) {
10711 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10712 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10713 if (SVOp->getMask()[i] >= NumElements)
10714 NumV2OddIndices += i % 2;
10715 else if (SVOp->getMask()[i] >= 0)
10716 NumV1OddIndices += i % 2;
10717 if (NumV2OddIndices < NumV1OddIndices)
10718 return DAG.getCommutedVectorShuffle(*SVOp);
10723 // For each vector width, delegate to a specialized lowering routine.
10724 if (VT.getSizeInBits() == 128)
10725 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10727 if (VT.getSizeInBits() == 256)
10728 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10730 // Force AVX-512 vectors to be scalarized for now.
10731 // FIXME: Implement AVX-512 support!
10732 if (VT.getSizeInBits() == 512)
10733 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10735 llvm_unreachable("Unimplemented!");
10738 // This function assumes its argument is a BUILD_VECTOR of constants or
10739 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10741 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10742 unsigned &MaskValue) {
10744 unsigned NumElems = BuildVector->getNumOperands();
10745 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10746 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10747 unsigned NumElemsInLane = NumElems / NumLanes;
10749 // Blend for v16i16 should be symmetric for the both lanes.
10750 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10751 SDValue EltCond = BuildVector->getOperand(i);
10752 SDValue SndLaneEltCond =
10753 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10755 int Lane1Cond = -1, Lane2Cond = -1;
10756 if (isa<ConstantSDNode>(EltCond))
10757 Lane1Cond = !isZero(EltCond);
10758 if (isa<ConstantSDNode>(SndLaneEltCond))
10759 Lane2Cond = !isZero(SndLaneEltCond);
10761 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10762 // Lane1Cond != 0, means we want the first argument.
10763 // Lane1Cond == 0, means we want the second argument.
10764 // The encoding of this argument is 0 for the first argument, 1
10765 // for the second. Therefore, invert the condition.
10766 MaskValue |= !Lane1Cond << i;
10767 else if (Lane1Cond < 0)
10768 MaskValue |= !Lane2Cond << i;
10775 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10776 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10777 const X86Subtarget *Subtarget,
10778 SelectionDAG &DAG) {
10779 SDValue Cond = Op.getOperand(0);
10780 SDValue LHS = Op.getOperand(1);
10781 SDValue RHS = Op.getOperand(2);
10783 MVT VT = Op.getSimpleValueType();
10785 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10787 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10789 // Only non-legal VSELECTs reach this lowering, convert those into generic
10790 // shuffles and re-use the shuffle lowering path for blends.
10791 SmallVector<int, 32> Mask;
10792 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10793 SDValue CondElt = CondBV->getOperand(i);
10795 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10797 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10800 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10801 // A vselect where all conditions and data are constants can be optimized into
10802 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10803 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10804 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10805 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10808 // Try to lower this to a blend-style vector shuffle. This can handle all
10809 // constant condition cases.
10810 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10813 // Variable blends are only legal from SSE4.1 onward.
10814 if (!Subtarget->hasSSE41())
10817 // Only some types will be legal on some subtargets. If we can emit a legal
10818 // VSELECT-matching blend, return Op, and but if we need to expand, return
10820 switch (Op.getSimpleValueType().SimpleTy) {
10822 // Most of the vector types have blends past SSE4.1.
10826 // The byte blends for AVX vectors were introduced only in AVX2.
10827 if (Subtarget->hasAVX2())
10834 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10835 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10838 // FIXME: We should custom lower this by fixing the condition and using i8
10844 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10845 MVT VT = Op.getSimpleValueType();
10848 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10851 if (VT.getSizeInBits() == 8) {
10852 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10853 Op.getOperand(0), Op.getOperand(1));
10854 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10855 DAG.getValueType(VT));
10856 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10859 if (VT.getSizeInBits() == 16) {
10860 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10861 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10863 return DAG.getNode(
10864 ISD::TRUNCATE, dl, MVT::i16,
10865 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10866 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10867 Op.getOperand(1)));
10868 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10869 Op.getOperand(0), Op.getOperand(1));
10870 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10871 DAG.getValueType(VT));
10872 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10875 if (VT == MVT::f32) {
10876 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10877 // the result back to FR32 register. It's only worth matching if the
10878 // result has a single use which is a store or a bitcast to i32. And in
10879 // the case of a store, it's not worth it if the index is a constant 0,
10880 // because a MOVSSmr can be used instead, which is smaller and faster.
10881 if (!Op.hasOneUse())
10883 SDNode *User = *Op.getNode()->use_begin();
10884 if ((User->getOpcode() != ISD::STORE ||
10885 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10886 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10887 (User->getOpcode() != ISD::BITCAST ||
10888 User->getValueType(0) != MVT::i32))
10890 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10891 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10893 return DAG.getBitcast(MVT::f32, Extract);
10896 if (VT == MVT::i32 || VT == MVT::i64) {
10897 // ExtractPS/pextrq works with constant index.
10898 if (isa<ConstantSDNode>(Op.getOperand(1)))
10904 /// Extract one bit from mask vector, like v16i1 or v8i1.
10905 /// AVX-512 feature.
10907 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10908 SDValue Vec = Op.getOperand(0);
10910 MVT VecVT = Vec.getSimpleValueType();
10911 SDValue Idx = Op.getOperand(1);
10912 MVT EltVT = Op.getSimpleValueType();
10914 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10915 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10916 "Unexpected vector type in ExtractBitFromMaskVector");
10918 // variable index can't be handled in mask registers,
10919 // extend vector to VR512
10920 if (!isa<ConstantSDNode>(Idx)) {
10921 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10922 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10923 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10924 ExtVT.getVectorElementType(), Ext, Idx);
10925 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10928 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10929 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10930 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10931 rc = getRegClassFor(MVT::v16i1);
10932 unsigned MaxSift = rc->getSize()*8 - 1;
10933 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10934 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10935 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10936 DAG.getConstant(MaxSift, dl, MVT::i8));
10937 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10938 DAG.getIntPtrConstant(0, dl));
10942 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10943 SelectionDAG &DAG) const {
10945 SDValue Vec = Op.getOperand(0);
10946 MVT VecVT = Vec.getSimpleValueType();
10947 SDValue Idx = Op.getOperand(1);
10949 if (Op.getSimpleValueType() == MVT::i1)
10950 return ExtractBitFromMaskVector(Op, DAG);
10952 if (!isa<ConstantSDNode>(Idx)) {
10953 if (VecVT.is512BitVector() ||
10954 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10955 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10958 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10959 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10960 MaskEltVT.getSizeInBits());
10962 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10963 auto PtrVT = getPointerTy(DAG.getDataLayout());
10964 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10965 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10966 DAG.getConstant(0, dl, PtrVT));
10967 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10968 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10969 DAG.getConstant(0, dl, PtrVT));
10974 // If this is a 256-bit vector result, first extract the 128-bit vector and
10975 // then extract the element from the 128-bit vector.
10976 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10978 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10979 // Get the 128-bit vector.
10980 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10981 MVT EltVT = VecVT.getVectorElementType();
10983 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10985 //if (IdxVal >= NumElems/2)
10986 // IdxVal -= NumElems/2;
10987 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10988 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10989 DAG.getConstant(IdxVal, dl, MVT::i32));
10992 assert(VecVT.is128BitVector() && "Unexpected vector length");
10994 if (Subtarget->hasSSE41())
10995 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10998 MVT VT = Op.getSimpleValueType();
10999 // TODO: handle v16i8.
11000 if (VT.getSizeInBits() == 16) {
11001 SDValue Vec = Op.getOperand(0);
11002 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11004 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11005 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11006 DAG.getBitcast(MVT::v4i32, Vec),
11007 Op.getOperand(1)));
11008 // Transform it so it match pextrw which produces a 32-bit result.
11009 MVT EltVT = MVT::i32;
11010 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11011 Op.getOperand(0), Op.getOperand(1));
11012 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11013 DAG.getValueType(VT));
11014 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11017 if (VT.getSizeInBits() == 32) {
11018 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11022 // SHUFPS the element to the lowest double word, then movss.
11023 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11024 MVT VVT = Op.getOperand(0).getSimpleValueType();
11025 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11026 DAG.getUNDEF(VVT), Mask);
11027 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11028 DAG.getIntPtrConstant(0, dl));
11031 if (VT.getSizeInBits() == 64) {
11032 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11033 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11034 // to match extract_elt for f64.
11035 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11039 // UNPCKHPD the element to the lowest double word, then movsd.
11040 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11041 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11042 int Mask[2] = { 1, -1 };
11043 MVT VVT = Op.getOperand(0).getSimpleValueType();
11044 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11045 DAG.getUNDEF(VVT), Mask);
11046 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11047 DAG.getIntPtrConstant(0, dl));
11053 /// Insert one bit to mask vector, like v16i1 or v8i1.
11054 /// AVX-512 feature.
11056 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11058 SDValue Vec = Op.getOperand(0);
11059 SDValue Elt = Op.getOperand(1);
11060 SDValue Idx = Op.getOperand(2);
11061 MVT VecVT = Vec.getSimpleValueType();
11063 if (!isa<ConstantSDNode>(Idx)) {
11064 // Non constant index. Extend source and destination,
11065 // insert element and then truncate the result.
11066 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11067 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11068 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11069 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11070 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11071 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11074 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11075 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11077 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11078 DAG.getConstant(IdxVal, dl, MVT::i8));
11079 if (Vec.getOpcode() == ISD::UNDEF)
11081 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11084 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11085 SelectionDAG &DAG) const {
11086 MVT VT = Op.getSimpleValueType();
11087 MVT EltVT = VT.getVectorElementType();
11089 if (EltVT == MVT::i1)
11090 return InsertBitToMaskVector(Op, DAG);
11093 SDValue N0 = Op.getOperand(0);
11094 SDValue N1 = Op.getOperand(1);
11095 SDValue N2 = Op.getOperand(2);
11096 if (!isa<ConstantSDNode>(N2))
11098 auto *N2C = cast<ConstantSDNode>(N2);
11099 unsigned IdxVal = N2C->getZExtValue();
11101 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11102 // into that, and then insert the subvector back into the result.
11103 if (VT.is256BitVector() || VT.is512BitVector()) {
11104 // With a 256-bit vector, we can insert into the zero element efficiently
11105 // using a blend if we have AVX or AVX2 and the right data type.
11106 if (VT.is256BitVector() && IdxVal == 0) {
11107 // TODO: It is worthwhile to cast integer to floating point and back
11108 // and incur a domain crossing penalty if that's what we'll end up
11109 // doing anyway after extracting to a 128-bit vector.
11110 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11111 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11112 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11113 N2 = DAG.getIntPtrConstant(1, dl);
11114 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11118 // Get the desired 128-bit vector chunk.
11119 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11121 // Insert the element into the desired chunk.
11122 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11123 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11125 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11126 DAG.getConstant(IdxIn128, dl, MVT::i32));
11128 // Insert the changed part back into the bigger vector
11129 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11131 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11133 if (Subtarget->hasSSE41()) {
11134 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11136 if (VT == MVT::v8i16) {
11137 Opc = X86ISD::PINSRW;
11139 assert(VT == MVT::v16i8);
11140 Opc = X86ISD::PINSRB;
11143 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11145 if (N1.getValueType() != MVT::i32)
11146 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11147 if (N2.getValueType() != MVT::i32)
11148 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11149 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11152 if (EltVT == MVT::f32) {
11153 // Bits [7:6] of the constant are the source select. This will always be
11154 // zero here. The DAG Combiner may combine an extract_elt index into
11155 // these bits. For example (insert (extract, 3), 2) could be matched by
11156 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11157 // Bits [5:4] of the constant are the destination select. This is the
11158 // value of the incoming immediate.
11159 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11160 // combine either bitwise AND or insert of float 0.0 to set these bits.
11162 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11163 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11164 // If this is an insertion of 32-bits into the low 32-bits of
11165 // a vector, we prefer to generate a blend with immediate rather
11166 // than an insertps. Blends are simpler operations in hardware and so
11167 // will always have equal or better performance than insertps.
11168 // But if optimizing for size and there's a load folding opportunity,
11169 // generate insertps because blendps does not have a 32-bit memory
11171 N2 = DAG.getIntPtrConstant(1, dl);
11172 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11173 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11175 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11176 // Create this as a scalar to vector..
11177 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11178 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11181 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11182 // PINSR* works with constant index.
11187 if (EltVT == MVT::i8)
11190 if (EltVT.getSizeInBits() == 16) {
11191 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11192 // as its second argument.
11193 if (N1.getValueType() != MVT::i32)
11194 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11195 if (N2.getValueType() != MVT::i32)
11196 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11197 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11202 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11204 MVT OpVT = Op.getSimpleValueType();
11206 // If this is a 256-bit vector result, first insert into a 128-bit
11207 // vector and then insert into the 256-bit vector.
11208 if (!OpVT.is128BitVector()) {
11209 // Insert into a 128-bit vector.
11210 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11211 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11212 OpVT.getVectorNumElements() / SizeFactor);
11214 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11216 // Insert the 128-bit vector.
11217 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11220 if (OpVT == MVT::v1i64 &&
11221 Op.getOperand(0).getValueType() == MVT::i64)
11222 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11224 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11225 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11226 return DAG.getBitcast(
11227 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11230 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11231 // a simple subregister reference or explicit instructions to grab
11232 // upper bits of a vector.
11233 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11234 SelectionDAG &DAG) {
11236 SDValue In = Op.getOperand(0);
11237 SDValue Idx = Op.getOperand(1);
11238 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11239 MVT ResVT = Op.getSimpleValueType();
11240 MVT InVT = In.getSimpleValueType();
11242 if (Subtarget->hasFp256()) {
11243 if (ResVT.is128BitVector() &&
11244 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11245 isa<ConstantSDNode>(Idx)) {
11246 return Extract128BitVector(In, IdxVal, DAG, dl);
11248 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11249 isa<ConstantSDNode>(Idx)) {
11250 return Extract256BitVector(In, IdxVal, DAG, dl);
11256 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11257 // simple superregister reference or explicit instructions to insert
11258 // the upper bits of a vector.
11259 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11260 SelectionDAG &DAG) {
11261 if (!Subtarget->hasAVX())
11265 SDValue Vec = Op.getOperand(0);
11266 SDValue SubVec = Op.getOperand(1);
11267 SDValue Idx = Op.getOperand(2);
11269 if (!isa<ConstantSDNode>(Idx))
11272 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11273 MVT OpVT = Op.getSimpleValueType();
11274 MVT SubVecVT = SubVec.getSimpleValueType();
11276 // Fold two 16-byte subvector loads into one 32-byte load:
11277 // (insert_subvector (insert_subvector undef, (load addr), 0),
11278 // (load addr + 16), Elts/2)
11280 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11281 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11282 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11283 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11284 if (Idx2 && Idx2->getZExtValue() == 0) {
11285 SDValue SubVec2 = Vec.getOperand(1);
11286 // If needed, look through a bitcast to get to the load.
11287 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11288 SubVec2 = SubVec2.getOperand(0);
11290 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11292 unsigned Alignment = FirstLd->getAlignment();
11293 unsigned AS = FirstLd->getAddressSpace();
11294 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11295 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11296 OpVT, AS, Alignment, &Fast) && Fast) {
11297 SDValue Ops[] = { SubVec2, SubVec };
11298 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11305 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11306 SubVecVT.is128BitVector())
11307 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11309 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11310 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11312 if (OpVT.getVectorElementType() == MVT::i1) {
11313 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11315 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11316 SDValue Undef = DAG.getUNDEF(OpVT);
11317 unsigned NumElems = OpVT.getVectorNumElements();
11318 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11320 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11321 // Zero upper bits of the Vec
11322 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11323 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11325 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11327 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11328 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11331 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11333 // Zero upper bits of the Vec2
11334 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11335 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11336 // Zero lower bits of the Vec
11337 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11338 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11339 // Merge them together
11340 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11346 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11347 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11348 // one of the above mentioned nodes. It has to be wrapped because otherwise
11349 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11350 // be used to form addressing mode. These wrapped nodes will be selected
11353 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11354 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11356 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11357 // global base reg.
11358 unsigned char OpFlag = 0;
11359 unsigned WrapperKind = X86ISD::Wrapper;
11360 CodeModel::Model M = DAG.getTarget().getCodeModel();
11362 if (Subtarget->isPICStyleRIPRel() &&
11363 (M == CodeModel::Small || M == CodeModel::Kernel))
11364 WrapperKind = X86ISD::WrapperRIP;
11365 else if (Subtarget->isPICStyleGOT())
11366 OpFlag = X86II::MO_GOTOFF;
11367 else if (Subtarget->isPICStyleStubPIC())
11368 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11370 auto PtrVT = getPointerTy(DAG.getDataLayout());
11371 SDValue Result = DAG.getTargetConstantPool(
11372 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11374 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11375 // With PIC, the address is actually $g + Offset.
11378 DAG.getNode(ISD::ADD, DL, PtrVT,
11379 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11385 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11386 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11388 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11389 // global base reg.
11390 unsigned char OpFlag = 0;
11391 unsigned WrapperKind = X86ISD::Wrapper;
11392 CodeModel::Model M = DAG.getTarget().getCodeModel();
11394 if (Subtarget->isPICStyleRIPRel() &&
11395 (M == CodeModel::Small || M == CodeModel::Kernel))
11396 WrapperKind = X86ISD::WrapperRIP;
11397 else if (Subtarget->isPICStyleGOT())
11398 OpFlag = X86II::MO_GOTOFF;
11399 else if (Subtarget->isPICStyleStubPIC())
11400 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11402 auto PtrVT = getPointerTy(DAG.getDataLayout());
11403 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11405 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11407 // With PIC, the address is actually $g + Offset.
11410 DAG.getNode(ISD::ADD, DL, PtrVT,
11411 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11417 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11418 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11420 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11421 // global base reg.
11422 unsigned char OpFlag = 0;
11423 unsigned WrapperKind = X86ISD::Wrapper;
11424 CodeModel::Model M = DAG.getTarget().getCodeModel();
11426 if (Subtarget->isPICStyleRIPRel() &&
11427 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11428 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11429 OpFlag = X86II::MO_GOTPCREL;
11430 WrapperKind = X86ISD::WrapperRIP;
11431 } else if (Subtarget->isPICStyleGOT()) {
11432 OpFlag = X86II::MO_GOT;
11433 } else if (Subtarget->isPICStyleStubPIC()) {
11434 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11435 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11436 OpFlag = X86II::MO_DARWIN_NONLAZY;
11439 auto PtrVT = getPointerTy(DAG.getDataLayout());
11440 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11443 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11445 // With PIC, the address is actually $g + Offset.
11446 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11447 !Subtarget->is64Bit()) {
11449 DAG.getNode(ISD::ADD, DL, PtrVT,
11450 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11453 // For symbols that require a load from a stub to get the address, emit the
11455 if (isGlobalStubReference(OpFlag))
11456 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11457 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11458 false, false, false, 0);
11464 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11465 // Create the TargetBlockAddressAddress node.
11466 unsigned char OpFlags =
11467 Subtarget->ClassifyBlockAddressReference();
11468 CodeModel::Model M = DAG.getTarget().getCodeModel();
11469 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11470 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11472 auto PtrVT = getPointerTy(DAG.getDataLayout());
11473 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11475 if (Subtarget->isPICStyleRIPRel() &&
11476 (M == CodeModel::Small || M == CodeModel::Kernel))
11477 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11479 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11481 // With PIC, the address is actually $g + Offset.
11482 if (isGlobalRelativeToPICBase(OpFlags)) {
11483 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11484 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11491 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11492 int64_t Offset, SelectionDAG &DAG) const {
11493 // Create the TargetGlobalAddress node, folding in the constant
11494 // offset if it is legal.
11495 unsigned char OpFlags =
11496 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11497 CodeModel::Model M = DAG.getTarget().getCodeModel();
11498 auto PtrVT = getPointerTy(DAG.getDataLayout());
11500 if (OpFlags == X86II::MO_NO_FLAG &&
11501 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11502 // A direct static reference to a global.
11503 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11506 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11509 if (Subtarget->isPICStyleRIPRel() &&
11510 (M == CodeModel::Small || M == CodeModel::Kernel))
11511 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11513 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11515 // With PIC, the address is actually $g + Offset.
11516 if (isGlobalRelativeToPICBase(OpFlags)) {
11517 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11518 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11521 // For globals that require a load from a stub to get the address, emit the
11523 if (isGlobalStubReference(OpFlags))
11524 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11525 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11526 false, false, false, 0);
11528 // If there was a non-zero offset that we didn't fold, create an explicit
11529 // addition for it.
11531 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11532 DAG.getConstant(Offset, dl, PtrVT));
11538 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11539 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11540 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11541 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11545 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11546 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11547 unsigned char OperandFlags, bool LocalDynamic = false) {
11548 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11549 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11551 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11552 GA->getValueType(0),
11556 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11560 SDValue Ops[] = { Chain, TGA, *InFlag };
11561 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11563 SDValue Ops[] = { Chain, TGA };
11564 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11567 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11568 MFI->setAdjustsStack(true);
11569 MFI->setHasCalls(true);
11571 SDValue Flag = Chain.getValue(1);
11572 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11575 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11577 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11580 SDLoc dl(GA); // ? function entry point might be better
11581 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11582 DAG.getNode(X86ISD::GlobalBaseReg,
11583 SDLoc(), PtrVT), InFlag);
11584 InFlag = Chain.getValue(1);
11586 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11589 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11591 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11593 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11594 X86::RAX, X86II::MO_TLSGD);
11597 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11603 // Get the start address of the TLS block for this module.
11604 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11605 .getInfo<X86MachineFunctionInfo>();
11606 MFI->incNumLocalDynamicTLSAccesses();
11610 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11611 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11614 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11615 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11616 InFlag = Chain.getValue(1);
11617 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11618 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11621 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11625 unsigned char OperandFlags = X86II::MO_DTPOFF;
11626 unsigned WrapperKind = X86ISD::Wrapper;
11627 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11628 GA->getValueType(0),
11629 GA->getOffset(), OperandFlags);
11630 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11632 // Add x@dtpoff with the base.
11633 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11636 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11637 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11638 const EVT PtrVT, TLSModel::Model model,
11639 bool is64Bit, bool isPIC) {
11642 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11643 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11644 is64Bit ? 257 : 256));
11646 SDValue ThreadPointer =
11647 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11648 MachinePointerInfo(Ptr), false, false, false, 0);
11650 unsigned char OperandFlags = 0;
11651 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11653 unsigned WrapperKind = X86ISD::Wrapper;
11654 if (model == TLSModel::LocalExec) {
11655 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11656 } else if (model == TLSModel::InitialExec) {
11658 OperandFlags = X86II::MO_GOTTPOFF;
11659 WrapperKind = X86ISD::WrapperRIP;
11661 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11664 llvm_unreachable("Unexpected model");
11667 // emit "addl x@ntpoff,%eax" (local exec)
11668 // or "addl x@indntpoff,%eax" (initial exec)
11669 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11671 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11672 GA->getOffset(), OperandFlags);
11673 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11675 if (model == TLSModel::InitialExec) {
11676 if (isPIC && !is64Bit) {
11677 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11678 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11682 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11683 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11684 false, false, false, 0);
11687 // The address of the thread local variable is the add of the thread
11688 // pointer with the offset of the variable.
11689 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11693 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11695 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11696 const GlobalValue *GV = GA->getGlobal();
11697 auto PtrVT = getPointerTy(DAG.getDataLayout());
11699 if (Subtarget->isTargetELF()) {
11700 if (DAG.getTarget().Options.EmulatedTLS)
11701 return LowerToTLSEmulatedModel(GA, DAG);
11702 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11704 case TLSModel::GeneralDynamic:
11705 if (Subtarget->is64Bit())
11706 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11707 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11708 case TLSModel::LocalDynamic:
11709 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11710 Subtarget->is64Bit());
11711 case TLSModel::InitialExec:
11712 case TLSModel::LocalExec:
11713 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11714 DAG.getTarget().getRelocationModel() ==
11717 llvm_unreachable("Unknown TLS model.");
11720 if (Subtarget->isTargetDarwin()) {
11721 // Darwin only has one model of TLS. Lower to that.
11722 unsigned char OpFlag = 0;
11723 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11724 X86ISD::WrapperRIP : X86ISD::Wrapper;
11726 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11727 // global base reg.
11728 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11729 !Subtarget->is64Bit();
11731 OpFlag = X86II::MO_TLVP_PIC_BASE;
11733 OpFlag = X86II::MO_TLVP;
11735 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11736 GA->getValueType(0),
11737 GA->getOffset(), OpFlag);
11738 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11740 // With PIC32, the address is actually $g + Offset.
11742 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11743 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11746 // Lowering the machine isd will make sure everything is in the right
11748 SDValue Chain = DAG.getEntryNode();
11749 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11750 SDValue Args[] = { Chain, Offset };
11751 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11753 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11754 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11755 MFI->setAdjustsStack(true);
11757 // And our return value (tls address) is in the standard call return value
11759 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11760 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11763 if (Subtarget->isTargetKnownWindowsMSVC() ||
11764 Subtarget->isTargetWindowsGNU()) {
11765 // Just use the implicit TLS architecture
11766 // Need to generate someting similar to:
11767 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11769 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11770 // mov rcx, qword [rdx+rcx*8]
11771 // mov eax, .tls$:tlsvar
11772 // [rax+rcx] contains the address
11773 // Windows 64bit: gs:0x58
11774 // Windows 32bit: fs:__tls_array
11777 SDValue Chain = DAG.getEntryNode();
11779 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11780 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11781 // use its literal value of 0x2C.
11782 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11783 ? Type::getInt8PtrTy(*DAG.getContext(),
11785 : Type::getInt32PtrTy(*DAG.getContext(),
11788 SDValue TlsArray = Subtarget->is64Bit()
11789 ? DAG.getIntPtrConstant(0x58, dl)
11790 : (Subtarget->isTargetWindowsGNU()
11791 ? DAG.getIntPtrConstant(0x2C, dl)
11792 : DAG.getExternalSymbol("_tls_array", PtrVT));
11794 SDValue ThreadPointer =
11795 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11799 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11800 res = ThreadPointer;
11802 // Load the _tls_index variable
11803 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11804 if (Subtarget->is64Bit())
11805 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11806 MachinePointerInfo(), MVT::i32, false, false,
11809 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11812 auto &DL = DAG.getDataLayout();
11814 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11815 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11817 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11820 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11823 // Get the offset of start of .tls section
11824 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11825 GA->getValueType(0),
11826 GA->getOffset(), X86II::MO_SECREL);
11827 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11829 // The address of the thread local variable is the add of the thread
11830 // pointer with the offset of the variable.
11831 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11834 llvm_unreachable("TLS not implemented for this target.");
11837 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11838 /// and take a 2 x i32 value to shift plus a shift amount.
11839 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11840 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11841 MVT VT = Op.getSimpleValueType();
11842 unsigned VTBits = VT.getSizeInBits();
11844 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11845 SDValue ShOpLo = Op.getOperand(0);
11846 SDValue ShOpHi = Op.getOperand(1);
11847 SDValue ShAmt = Op.getOperand(2);
11848 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11849 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11851 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11852 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11853 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11854 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11855 : DAG.getConstant(0, dl, VT);
11857 SDValue Tmp2, Tmp3;
11858 if (Op.getOpcode() == ISD::SHL_PARTS) {
11859 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11860 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11862 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11863 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11866 // If the shift amount is larger or equal than the width of a part we can't
11867 // rely on the results of shld/shrd. Insert a test and select the appropriate
11868 // values for large shift amounts.
11869 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11870 DAG.getConstant(VTBits, dl, MVT::i8));
11871 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11872 AndNode, DAG.getConstant(0, dl, MVT::i8));
11875 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11876 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11877 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11879 if (Op.getOpcode() == ISD::SHL_PARTS) {
11880 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11881 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11883 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11884 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11887 SDValue Ops[2] = { Lo, Hi };
11888 return DAG.getMergeValues(Ops, dl);
11891 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11892 SelectionDAG &DAG) const {
11893 SDValue Src = Op.getOperand(0);
11894 MVT SrcVT = Src.getSimpleValueType();
11895 MVT VT = Op.getSimpleValueType();
11898 if (SrcVT.isVector()) {
11899 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11900 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11901 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11902 DAG.getUNDEF(SrcVT)));
11904 if (SrcVT.getVectorElementType() == MVT::i1) {
11905 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11906 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11907 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11912 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11913 "Unknown SINT_TO_FP to lower!");
11915 // These are really Legal; return the operand so the caller accepts it as
11917 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11919 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11920 Subtarget->is64Bit()) {
11924 unsigned Size = SrcVT.getSizeInBits()/8;
11925 MachineFunction &MF = DAG.getMachineFunction();
11926 auto PtrVT = getPointerTy(MF.getDataLayout());
11927 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11928 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11929 SDValue Chain = DAG.getStore(
11930 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11931 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11933 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11936 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11938 SelectionDAG &DAG) const {
11942 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11944 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11946 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11948 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11950 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11951 MachineMemOperand *MMO;
11953 int SSFI = FI->getIndex();
11954 MMO = DAG.getMachineFunction().getMachineMemOperand(
11955 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11956 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11958 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11959 StackSlot = StackSlot.getOperand(1);
11961 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11962 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11964 Tys, Ops, SrcVT, MMO);
11967 Chain = Result.getValue(1);
11968 SDValue InFlag = Result.getValue(2);
11970 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11971 // shouldn't be necessary except that RFP cannot be live across
11972 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11973 MachineFunction &MF = DAG.getMachineFunction();
11974 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11975 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11976 auto PtrVT = getPointerTy(MF.getDataLayout());
11977 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11978 Tys = DAG.getVTList(MVT::Other);
11980 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11982 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11983 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11984 MachineMemOperand::MOStore, SSFISize, SSFISize);
11986 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11987 Ops, Op.getValueType(), MMO);
11988 Result = DAG.getLoad(
11989 Op.getValueType(), DL, Chain, StackSlot,
11990 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11991 false, false, false, 0);
11997 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11998 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11999 SelectionDAG &DAG) const {
12000 // This algorithm is not obvious. Here it is what we're trying to output:
12003 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12004 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12006 haddpd %xmm0, %xmm0
12008 pshufd $0x4e, %xmm0, %xmm1
12014 LLVMContext *Context = DAG.getContext();
12016 // Build some magic constants.
12017 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12018 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12019 auto PtrVT = getPointerTy(DAG.getDataLayout());
12020 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12022 SmallVector<Constant*,2> CV1;
12024 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12025 APInt(64, 0x4330000000000000ULL))));
12027 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12028 APInt(64, 0x4530000000000000ULL))));
12029 Constant *C1 = ConstantVector::get(CV1);
12030 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12032 // Load the 64-bit value into an XMM register.
12033 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12036 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12037 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12038 false, false, false, 16);
12040 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12043 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12044 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12045 false, false, false, 16);
12046 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12047 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12050 if (Subtarget->hasSSE3()) {
12051 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12052 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12054 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12055 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12057 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12058 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12061 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12062 DAG.getIntPtrConstant(0, dl));
12065 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12066 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12067 SelectionDAG &DAG) const {
12069 // FP constant to bias correct the final result.
12070 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12073 // Load the 32-bit value into an XMM register.
12074 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12077 // Zero out the upper parts of the register.
12078 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12080 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12081 DAG.getBitcast(MVT::v2f64, Load),
12082 DAG.getIntPtrConstant(0, dl));
12084 // Or the load with the bias.
12085 SDValue Or = DAG.getNode(
12086 ISD::OR, dl, MVT::v2i64,
12087 DAG.getBitcast(MVT::v2i64,
12088 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12089 DAG.getBitcast(MVT::v2i64,
12090 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12092 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12093 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12095 // Subtract the bias.
12096 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12098 // Handle final rounding.
12099 EVT DestVT = Op.getValueType();
12101 if (DestVT.bitsLT(MVT::f64))
12102 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12103 DAG.getIntPtrConstant(0, dl));
12104 if (DestVT.bitsGT(MVT::f64))
12105 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12107 // Handle final rounding.
12111 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12112 const X86Subtarget &Subtarget) {
12113 // The algorithm is the following:
12114 // #ifdef __SSE4_1__
12115 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12116 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12117 // (uint4) 0x53000000, 0xaa);
12119 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12120 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12122 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12123 // return (float4) lo + fhi;
12126 SDValue V = Op->getOperand(0);
12127 EVT VecIntVT = V.getValueType();
12128 bool Is128 = VecIntVT == MVT::v4i32;
12129 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12130 // If we convert to something else than the supported type, e.g., to v4f64,
12132 if (VecFloatVT != Op->getValueType(0))
12135 unsigned NumElts = VecIntVT.getVectorNumElements();
12136 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12137 "Unsupported custom type");
12138 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12140 // In the #idef/#else code, we have in common:
12141 // - The vector of constants:
12147 // Create the splat vector for 0x4b000000.
12148 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12149 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12150 CstLow, CstLow, CstLow, CstLow};
12151 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12152 makeArrayRef(&CstLowArray[0], NumElts));
12153 // Create the splat vector for 0x53000000.
12154 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12155 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12156 CstHigh, CstHigh, CstHigh, CstHigh};
12157 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12158 makeArrayRef(&CstHighArray[0], NumElts));
12160 // Create the right shift.
12161 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12162 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12163 CstShift, CstShift, CstShift, CstShift};
12164 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12165 makeArrayRef(&CstShiftArray[0], NumElts));
12166 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12169 if (Subtarget.hasSSE41()) {
12170 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12171 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12172 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12173 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12174 // Low will be bitcasted right away, so do not bother bitcasting back to its
12176 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12177 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12178 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12179 // (uint4) 0x53000000, 0xaa);
12180 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12181 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12182 // High will be bitcasted right away, so do not bother bitcasting back to
12183 // its original type.
12184 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12185 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12187 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12188 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12189 CstMask, CstMask, CstMask);
12190 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12191 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12192 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12194 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12195 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12198 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12199 SDValue CstFAdd = DAG.getConstantFP(
12200 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12201 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12202 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12203 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12204 makeArrayRef(&CstFAddArray[0], NumElts));
12206 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12207 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12209 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12210 // return (float4) lo + fhi;
12211 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12212 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12215 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12216 SelectionDAG &DAG) const {
12217 SDValue N0 = Op.getOperand(0);
12218 MVT SVT = N0.getSimpleValueType();
12221 switch (SVT.SimpleTy) {
12223 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12228 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12229 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12230 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12234 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12237 if (Subtarget->hasAVX512())
12238 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12239 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12241 llvm_unreachable(nullptr);
12244 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12245 SelectionDAG &DAG) const {
12246 SDValue N0 = Op.getOperand(0);
12248 auto PtrVT = getPointerTy(DAG.getDataLayout());
12250 if (Op.getValueType().isVector())
12251 return lowerUINT_TO_FP_vec(Op, DAG);
12253 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12254 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12255 // the optimization here.
12256 if (DAG.SignBitIsZero(N0))
12257 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12259 MVT SrcVT = N0.getSimpleValueType();
12260 MVT DstVT = Op.getSimpleValueType();
12261 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12262 return LowerUINT_TO_FP_i64(Op, DAG);
12263 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12264 return LowerUINT_TO_FP_i32(Op, DAG);
12265 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12268 // Make a 64-bit buffer, and use it to build an FILD.
12269 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12270 if (SrcVT == MVT::i32) {
12271 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12272 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12273 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12274 StackSlot, MachinePointerInfo(),
12276 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12277 OffsetSlot, MachinePointerInfo(),
12279 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12283 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12284 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12285 StackSlot, MachinePointerInfo(),
12287 // For i64 source, we need to add the appropriate power of 2 if the input
12288 // was negative. This is the same as the optimization in
12289 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12290 // we must be careful to do the computation in x87 extended precision, not
12291 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12292 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12293 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12294 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12295 MachineMemOperand::MOLoad, 8, 8);
12297 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12298 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12299 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12302 APInt FF(32, 0x5F800000ULL);
12304 // Check whether the sign bit is set.
12305 SDValue SignSet = DAG.getSetCC(
12306 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12307 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12309 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12310 SDValue FudgePtr = DAG.getConstantPool(
12311 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12313 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12314 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12315 SDValue Four = DAG.getIntPtrConstant(4, dl);
12316 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12318 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12320 // Load the value out, extending it from f32 to f80.
12321 // FIXME: Avoid the extend by constructing the right constant pool?
12322 SDValue Fudge = DAG.getExtLoad(
12323 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12324 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12325 false, false, false, 4);
12326 // Extend everything to 80 bits to force it to be done on x87.
12327 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12328 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12329 DAG.getIntPtrConstant(0, dl));
12332 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12333 // is legal, or has an f16 source (which needs to be promoted to f32),
12334 // just return an <SDValue(), SDValue()> pair.
12335 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12336 // to i16, i32 or i64, and we lower it to a legal sequence.
12337 // If lowered to the final integer result we return a <result, SDValue()> pair.
12338 // Otherwise we lower it to a sequence ending with a FIST, return a
12339 // <FIST, StackSlot> pair, and the caller is responsible for loading
12340 // the final integer result from StackSlot.
12341 std::pair<SDValue,SDValue>
12342 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12343 bool IsSigned, bool IsReplace) const {
12346 EVT DstTy = Op.getValueType();
12347 EVT TheVT = Op.getOperand(0).getValueType();
12348 auto PtrVT = getPointerTy(DAG.getDataLayout());
12350 if (TheVT == MVT::f16)
12351 // We need to promote the f16 to f32 before using the lowering
12352 // in this routine.
12353 return std::make_pair(SDValue(), SDValue());
12355 assert((TheVT == MVT::f32 ||
12356 TheVT == MVT::f64 ||
12357 TheVT == MVT::f80) &&
12358 "Unexpected FP operand type in FP_TO_INTHelper");
12360 // If using FIST to compute an unsigned i64, we'll need some fixup
12361 // to handle values above the maximum signed i64. A FIST is always
12362 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12363 bool UnsignedFixup = !IsSigned &&
12364 DstTy == MVT::i64 &&
12365 (!Subtarget->is64Bit() ||
12366 !isScalarFPTypeInSSEReg(TheVT));
12368 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12369 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12370 // The low 32 bits of the fist result will have the correct uint32 result.
12371 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12375 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12376 DstTy.getSimpleVT() >= MVT::i16 &&
12377 "Unknown FP_TO_INT to lower!");
12379 // These are really Legal.
12380 if (DstTy == MVT::i32 &&
12381 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12382 return std::make_pair(SDValue(), SDValue());
12383 if (Subtarget->is64Bit() &&
12384 DstTy == MVT::i64 &&
12385 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12386 return std::make_pair(SDValue(), SDValue());
12388 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12390 MachineFunction &MF = DAG.getMachineFunction();
12391 unsigned MemSize = DstTy.getSizeInBits()/8;
12392 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12393 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12396 switch (DstTy.getSimpleVT().SimpleTy) {
12397 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12398 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12399 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12400 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12403 SDValue Chain = DAG.getEntryNode();
12404 SDValue Value = Op.getOperand(0);
12405 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12407 if (UnsignedFixup) {
12409 // Conversion to unsigned i64 is implemented with a select,
12410 // depending on whether the source value fits in the range
12411 // of a signed i64. Let Thresh be the FP equivalent of
12412 // 0x8000000000000000ULL.
12414 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12415 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12416 // Fist-to-mem64 FistSrc
12417 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12418 // to XOR'ing the high 32 bits with Adjust.
12420 // Being a power of 2, Thresh is exactly representable in all FP formats.
12421 // For X87 we'd like to use the smallest FP type for this constant, but
12422 // for DAG type consistency we have to match the FP operand type.
12424 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12425 APFloat::opStatus Status = APFloat::opOK;
12426 bool LosesInfo = false;
12427 if (TheVT == MVT::f64)
12428 // The rounding mode is irrelevant as the conversion should be exact.
12429 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12431 else if (TheVT == MVT::f80)
12432 Status = Thresh.convert(APFloat::x87DoubleExtended,
12433 APFloat::rmNearestTiesToEven, &LosesInfo);
12435 assert(Status == APFloat::opOK && !LosesInfo &&
12436 "FP conversion should have been exact");
12438 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12440 SDValue Cmp = DAG.getSetCC(DL,
12441 getSetCCResultType(DAG.getDataLayout(),
12442 *DAG.getContext(), TheVT),
12443 Value, ThreshVal, ISD::SETLT);
12444 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12445 DAG.getConstant(0, DL, MVT::i32),
12446 DAG.getConstant(0x80000000, DL, MVT::i32));
12447 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12448 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12449 *DAG.getContext(), TheVT),
12450 Value, ThreshVal, ISD::SETLT);
12451 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12454 // FIXME This causes a redundant load/store if the SSE-class value is already
12455 // in memory, such as if it is on the callstack.
12456 if (isScalarFPTypeInSSEReg(TheVT)) {
12457 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12458 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12459 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12461 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12463 Chain, StackSlot, DAG.getValueType(TheVT)
12466 MachineMemOperand *MMO =
12467 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12468 MachineMemOperand::MOLoad, MemSize, MemSize);
12469 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12470 Chain = Value.getValue(1);
12471 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12472 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12475 MachineMemOperand *MMO =
12476 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12477 MachineMemOperand::MOStore, MemSize, MemSize);
12479 if (UnsignedFixup) {
12481 // Insert the FIST, load its result as two i32's,
12482 // and XOR the high i32 with Adjust.
12484 SDValue FistOps[] = { Chain, Value, StackSlot };
12485 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12486 FistOps, DstTy, MMO);
12488 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12489 MachinePointerInfo(),
12490 false, false, false, 0);
12491 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12492 DAG.getConstant(4, DL, PtrVT));
12494 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12495 MachinePointerInfo(),
12496 false, false, false, 0);
12497 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12499 if (Subtarget->is64Bit()) {
12500 // Join High32 and Low32 into a 64-bit result.
12501 // (High32 << 32) | Low32
12502 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12503 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12504 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12505 DAG.getConstant(32, DL, MVT::i8));
12506 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12507 return std::make_pair(Result, SDValue());
12510 SDValue ResultOps[] = { Low32, High32 };
12512 SDValue pair = IsReplace
12513 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12514 : DAG.getMergeValues(ResultOps, DL);
12515 return std::make_pair(pair, SDValue());
12517 // Build the FP_TO_INT*_IN_MEM
12518 SDValue Ops[] = { Chain, Value, StackSlot };
12519 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12521 return std::make_pair(FIST, StackSlot);
12525 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12526 const X86Subtarget *Subtarget) {
12527 MVT VT = Op->getSimpleValueType(0);
12528 SDValue In = Op->getOperand(0);
12529 MVT InVT = In.getSimpleValueType();
12532 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12533 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12535 // Optimize vectors in AVX mode:
12538 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12539 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12540 // Concat upper and lower parts.
12543 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12544 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12545 // Concat upper and lower parts.
12548 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12549 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12550 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12553 if (Subtarget->hasInt256())
12554 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12556 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12557 SDValue Undef = DAG.getUNDEF(InVT);
12558 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12559 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12560 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12562 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12563 VT.getVectorNumElements()/2);
12565 OpLo = DAG.getBitcast(HVT, OpLo);
12566 OpHi = DAG.getBitcast(HVT, OpHi);
12568 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12571 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12572 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12573 MVT VT = Op->getSimpleValueType(0);
12574 SDValue In = Op->getOperand(0);
12575 MVT InVT = In.getSimpleValueType();
12577 unsigned int NumElts = VT.getVectorNumElements();
12578 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12581 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12582 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12584 assert(InVT.getVectorElementType() == MVT::i1);
12585 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12587 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12589 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12591 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12592 if (VT.is512BitVector())
12594 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12597 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12598 SelectionDAG &DAG) {
12599 if (Subtarget->hasFp256())
12600 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12606 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12607 SelectionDAG &DAG) {
12609 MVT VT = Op.getSimpleValueType();
12610 SDValue In = Op.getOperand(0);
12611 MVT SVT = In.getSimpleValueType();
12613 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12614 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12616 if (Subtarget->hasFp256())
12617 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12620 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12621 VT.getVectorNumElements() != SVT.getVectorNumElements());
12625 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12627 MVT VT = Op.getSimpleValueType();
12628 SDValue In = Op.getOperand(0);
12629 MVT InVT = In.getSimpleValueType();
12631 if (VT == MVT::i1) {
12632 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12633 "Invalid scalar TRUNCATE operation");
12634 if (InVT.getSizeInBits() >= 32)
12636 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12637 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12639 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12640 "Invalid TRUNCATE operation");
12642 // move vector to mask - truncate solution for SKX
12643 if (VT.getVectorElementType() == MVT::i1) {
12644 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12645 Subtarget->hasBWI())
12646 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12647 if ((InVT.is256BitVector() || InVT.is128BitVector())
12648 && InVT.getScalarSizeInBits() <= 16 &&
12649 Subtarget->hasBWI() && Subtarget->hasVLX())
12650 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12651 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12652 Subtarget->hasDQI())
12653 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12654 if ((InVT.is256BitVector() || InVT.is128BitVector())
12655 && InVT.getScalarSizeInBits() >= 32 &&
12656 Subtarget->hasDQI() && Subtarget->hasVLX())
12657 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12660 if (VT.getVectorElementType() == MVT::i1) {
12661 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12662 unsigned NumElts = InVT.getVectorNumElements();
12663 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12664 if (InVT.getSizeInBits() < 512) {
12665 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12666 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12671 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12672 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12673 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12676 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12677 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12678 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12679 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12681 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12682 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12683 if (Subtarget->hasInt256()) {
12684 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12685 In = DAG.getBitcast(MVT::v8i32, In);
12686 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12688 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12689 DAG.getIntPtrConstant(0, DL));
12692 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12693 DAG.getIntPtrConstant(0, DL));
12694 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12695 DAG.getIntPtrConstant(2, DL));
12696 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12697 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12698 static const int ShufMask[] = {0, 2, 4, 6};
12699 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12702 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12703 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12704 if (Subtarget->hasInt256()) {
12705 In = DAG.getBitcast(MVT::v32i8, In);
12707 SmallVector<SDValue,32> pshufbMask;
12708 for (unsigned i = 0; i < 2; ++i) {
12709 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12710 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12711 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12712 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12713 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12714 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12715 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12716 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12717 for (unsigned j = 0; j < 8; ++j)
12718 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12720 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12721 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12722 In = DAG.getBitcast(MVT::v4i64, In);
12724 static const int ShufMask[] = {0, 2, -1, -1};
12725 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12727 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12728 DAG.getIntPtrConstant(0, DL));
12729 return DAG.getBitcast(VT, In);
12732 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12733 DAG.getIntPtrConstant(0, DL));
12735 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12736 DAG.getIntPtrConstant(4, DL));
12738 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12739 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12741 // The PSHUFB mask:
12742 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12743 -1, -1, -1, -1, -1, -1, -1, -1};
12745 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12746 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12747 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12749 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12750 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12752 // The MOVLHPS Mask:
12753 static const int ShufMask2[] = {0, 1, 4, 5};
12754 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12755 return DAG.getBitcast(MVT::v8i16, res);
12758 // Handle truncation of V256 to V128 using shuffles.
12759 if (!VT.is128BitVector() || !InVT.is256BitVector())
12762 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12764 unsigned NumElems = VT.getVectorNumElements();
12765 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12767 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12768 // Prepare truncation shuffle mask
12769 for (unsigned i = 0; i != NumElems; ++i)
12770 MaskVec[i] = i * 2;
12771 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12772 DAG.getUNDEF(NVT), &MaskVec[0]);
12773 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12774 DAG.getIntPtrConstant(0, DL));
12777 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12778 SelectionDAG &DAG) const {
12779 assert(!Op.getSimpleValueType().isVector());
12781 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12782 /*IsSigned=*/ true, /*IsReplace=*/ false);
12783 SDValue FIST = Vals.first, StackSlot = Vals.second;
12784 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12785 if (!FIST.getNode())
12788 if (StackSlot.getNode())
12789 // Load the result.
12790 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12791 FIST, StackSlot, MachinePointerInfo(),
12792 false, false, false, 0);
12794 // The node is the result.
12798 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12799 SelectionDAG &DAG) const {
12800 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12801 /*IsSigned=*/ false, /*IsReplace=*/ false);
12802 SDValue FIST = Vals.first, StackSlot = Vals.second;
12803 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12804 if (!FIST.getNode())
12807 if (StackSlot.getNode())
12808 // Load the result.
12809 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12810 FIST, StackSlot, MachinePointerInfo(),
12811 false, false, false, 0);
12813 // The node is the result.
12817 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12819 MVT VT = Op.getSimpleValueType();
12820 SDValue In = Op.getOperand(0);
12821 MVT SVT = In.getSimpleValueType();
12823 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12825 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12826 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12827 In, DAG.getUNDEF(SVT)));
12830 /// The only differences between FABS and FNEG are the mask and the logic op.
12831 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12832 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12833 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12834 "Wrong opcode for lowering FABS or FNEG.");
12836 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12838 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12839 // into an FNABS. We'll lower the FABS after that if it is still in use.
12841 for (SDNode *User : Op->uses())
12842 if (User->getOpcode() == ISD::FNEG)
12846 MVT VT = Op.getSimpleValueType();
12848 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12849 // decide if we should generate a 16-byte constant mask when we only need 4 or
12850 // 8 bytes for the scalar case.
12856 if (VT.isVector()) {
12858 EltVT = VT.getVectorElementType();
12859 NumElts = VT.getVectorNumElements();
12861 // There are no scalar bitwise logical SSE/AVX instructions, so we
12862 // generate a 16-byte vector constant and logic op even for the scalar case.
12863 // Using a 16-byte mask allows folding the load of the mask with
12864 // the logic op, so it can save (~4 bytes) on code size.
12865 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12867 NumElts = (VT == MVT::f64) ? 2 : 4;
12870 unsigned EltBits = EltVT.getSizeInBits();
12871 LLVMContext *Context = DAG.getContext();
12872 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12874 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12875 Constant *C = ConstantInt::get(*Context, MaskElt);
12876 C = ConstantVector::getSplat(NumElts, C);
12877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12878 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12879 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12881 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12882 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12883 false, false, false, Alignment);
12885 SDValue Op0 = Op.getOperand(0);
12886 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12888 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12889 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12892 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12894 // For the scalar case extend to a 128-bit vector, perform the logic op,
12895 // and extract the scalar result back out.
12896 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12897 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12898 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12899 DAG.getIntPtrConstant(0, dl));
12902 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12904 LLVMContext *Context = DAG.getContext();
12905 SDValue Op0 = Op.getOperand(0);
12906 SDValue Op1 = Op.getOperand(1);
12908 MVT VT = Op.getSimpleValueType();
12909 MVT SrcVT = Op1.getSimpleValueType();
12911 // If second operand is smaller, extend it first.
12912 if (SrcVT.bitsLT(VT)) {
12913 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12916 // And if it is bigger, shrink it first.
12917 if (SrcVT.bitsGT(VT)) {
12918 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12922 // At this point the operands and the result should have the same
12923 // type, and that won't be f80 since that is not custom lowered.
12925 const fltSemantics &Sem =
12926 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12927 const unsigned SizeInBits = VT.getSizeInBits();
12929 SmallVector<Constant *, 4> CV(
12930 VT == MVT::f64 ? 2 : 4,
12931 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12933 // First, clear all bits but the sign bit from the second operand (sign).
12934 CV[0] = ConstantFP::get(*Context,
12935 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12936 Constant *C = ConstantVector::get(CV);
12937 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12938 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12940 // Perform all logic operations as 16-byte vectors because there are no
12941 // scalar FP logic instructions in SSE. This allows load folding of the
12942 // constants into the logic instructions.
12943 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12945 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12946 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12947 false, false, false, 16);
12948 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12949 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12951 // Next, clear the sign bit from the first operand (magnitude).
12952 // If it's a constant, we can clear it here.
12953 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12954 APFloat APF = Op0CN->getValueAPF();
12955 // If the magnitude is a positive zero, the sign bit alone is enough.
12956 if (APF.isPosZero())
12957 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12958 DAG.getIntPtrConstant(0, dl));
12960 CV[0] = ConstantFP::get(*Context, APF);
12962 CV[0] = ConstantFP::get(
12964 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12966 C = ConstantVector::get(CV);
12967 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12969 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12970 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12971 false, false, false, 16);
12972 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12973 if (!isa<ConstantFPSDNode>(Op0)) {
12974 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12975 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12977 // OR the magnitude value with the sign bit.
12978 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12979 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12980 DAG.getIntPtrConstant(0, dl));
12983 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12984 SDValue N0 = Op.getOperand(0);
12986 MVT VT = Op.getSimpleValueType();
12988 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12989 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12990 DAG.getConstant(1, dl, VT));
12991 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12994 // Check whether an OR'd tree is PTEST-able.
12995 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12996 SelectionDAG &DAG) {
12997 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12999 if (!Subtarget->hasSSE41())
13002 if (!Op->hasOneUse())
13005 SDNode *N = Op.getNode();
13008 SmallVector<SDValue, 8> Opnds;
13009 DenseMap<SDValue, unsigned> VecInMap;
13010 SmallVector<SDValue, 8> VecIns;
13011 EVT VT = MVT::Other;
13013 // Recognize a special case where a vector is casted into wide integer to
13015 Opnds.push_back(N->getOperand(0));
13016 Opnds.push_back(N->getOperand(1));
13018 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13019 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13020 // BFS traverse all OR'd operands.
13021 if (I->getOpcode() == ISD::OR) {
13022 Opnds.push_back(I->getOperand(0));
13023 Opnds.push_back(I->getOperand(1));
13024 // Re-evaluate the number of nodes to be traversed.
13025 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13029 // Quit if a non-EXTRACT_VECTOR_ELT
13030 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13033 // Quit if without a constant index.
13034 SDValue Idx = I->getOperand(1);
13035 if (!isa<ConstantSDNode>(Idx))
13038 SDValue ExtractedFromVec = I->getOperand(0);
13039 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13040 if (M == VecInMap.end()) {
13041 VT = ExtractedFromVec.getValueType();
13042 // Quit if not 128/256-bit vector.
13043 if (!VT.is128BitVector() && !VT.is256BitVector())
13045 // Quit if not the same type.
13046 if (VecInMap.begin() != VecInMap.end() &&
13047 VT != VecInMap.begin()->first.getValueType())
13049 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13050 VecIns.push_back(ExtractedFromVec);
13052 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13055 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13056 "Not extracted from 128-/256-bit vector.");
13058 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13060 for (DenseMap<SDValue, unsigned>::const_iterator
13061 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13062 // Quit if not all elements are used.
13063 if (I->second != FullMask)
13067 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13069 // Cast all vectors into TestVT for PTEST.
13070 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13071 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13073 // If more than one full vectors are evaluated, OR them first before PTEST.
13074 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13075 // Each iteration will OR 2 nodes and append the result until there is only
13076 // 1 node left, i.e. the final OR'd value of all vectors.
13077 SDValue LHS = VecIns[Slot];
13078 SDValue RHS = VecIns[Slot + 1];
13079 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13082 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13083 VecIns.back(), VecIns.back());
13086 /// \brief return true if \c Op has a use that doesn't just read flags.
13087 static bool hasNonFlagsUse(SDValue Op) {
13088 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13090 SDNode *User = *UI;
13091 unsigned UOpNo = UI.getOperandNo();
13092 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13093 // Look pass truncate.
13094 UOpNo = User->use_begin().getOperandNo();
13095 User = *User->use_begin();
13098 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13099 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13105 /// Emit nodes that will be selected as "test Op0,Op0", or something
13107 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13108 SelectionDAG &DAG) const {
13109 if (Op.getValueType() == MVT::i1) {
13110 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13111 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13112 DAG.getConstant(0, dl, MVT::i8));
13114 // CF and OF aren't always set the way we want. Determine which
13115 // of these we need.
13116 bool NeedCF = false;
13117 bool NeedOF = false;
13120 case X86::COND_A: case X86::COND_AE:
13121 case X86::COND_B: case X86::COND_BE:
13124 case X86::COND_G: case X86::COND_GE:
13125 case X86::COND_L: case X86::COND_LE:
13126 case X86::COND_O: case X86::COND_NO: {
13127 // Check if we really need to set the
13128 // Overflow flag. If NoSignedWrap is present
13129 // that is not actually needed.
13130 switch (Op->getOpcode()) {
13135 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13136 if (BinNode->Flags.hasNoSignedWrap())
13146 // See if we can use the EFLAGS value from the operand instead of
13147 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13148 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13149 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13150 // Emit a CMP with 0, which is the TEST pattern.
13151 //if (Op.getValueType() == MVT::i1)
13152 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13153 // DAG.getConstant(0, MVT::i1));
13154 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13155 DAG.getConstant(0, dl, Op.getValueType()));
13157 unsigned Opcode = 0;
13158 unsigned NumOperands = 0;
13160 // Truncate operations may prevent the merge of the SETCC instruction
13161 // and the arithmetic instruction before it. Attempt to truncate the operands
13162 // of the arithmetic instruction and use a reduced bit-width instruction.
13163 bool NeedTruncation = false;
13164 SDValue ArithOp = Op;
13165 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13166 SDValue Arith = Op->getOperand(0);
13167 // Both the trunc and the arithmetic op need to have one user each.
13168 if (Arith->hasOneUse())
13169 switch (Arith.getOpcode()) {
13176 NeedTruncation = true;
13182 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13183 // which may be the result of a CAST. We use the variable 'Op', which is the
13184 // non-casted variable when we check for possible users.
13185 switch (ArithOp.getOpcode()) {
13187 // Due to an isel shortcoming, be conservative if this add is likely to be
13188 // selected as part of a load-modify-store instruction. When the root node
13189 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13190 // uses of other nodes in the match, such as the ADD in this case. This
13191 // leads to the ADD being left around and reselected, with the result being
13192 // two adds in the output. Alas, even if none our users are stores, that
13193 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13194 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13195 // climbing the DAG back to the root, and it doesn't seem to be worth the
13197 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13198 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13199 if (UI->getOpcode() != ISD::CopyToReg &&
13200 UI->getOpcode() != ISD::SETCC &&
13201 UI->getOpcode() != ISD::STORE)
13204 if (ConstantSDNode *C =
13205 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13206 // An add of one will be selected as an INC.
13207 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13208 Opcode = X86ISD::INC;
13213 // An add of negative one (subtract of one) will be selected as a DEC.
13214 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13215 Opcode = X86ISD::DEC;
13221 // Otherwise use a regular EFLAGS-setting add.
13222 Opcode = X86ISD::ADD;
13227 // If we have a constant logical shift that's only used in a comparison
13228 // against zero turn it into an equivalent AND. This allows turning it into
13229 // a TEST instruction later.
13230 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13231 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13232 EVT VT = Op.getValueType();
13233 unsigned BitWidth = VT.getSizeInBits();
13234 unsigned ShAmt = Op->getConstantOperandVal(1);
13235 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13237 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13238 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13239 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13240 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13242 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13243 DAG.getConstant(Mask, dl, VT));
13244 DAG.ReplaceAllUsesWith(Op, New);
13250 // If the primary and result isn't used, don't bother using X86ISD::AND,
13251 // because a TEST instruction will be better.
13252 if (!hasNonFlagsUse(Op))
13258 // Due to the ISEL shortcoming noted above, be conservative if this op is
13259 // likely to be selected as part of a load-modify-store instruction.
13260 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13261 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13262 if (UI->getOpcode() == ISD::STORE)
13265 // Otherwise use a regular EFLAGS-setting instruction.
13266 switch (ArithOp.getOpcode()) {
13267 default: llvm_unreachable("unexpected operator!");
13268 case ISD::SUB: Opcode = X86ISD::SUB; break;
13269 case ISD::XOR: Opcode = X86ISD::XOR; break;
13270 case ISD::AND: Opcode = X86ISD::AND; break;
13272 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13273 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13274 if (EFLAGS.getNode())
13277 Opcode = X86ISD::OR;
13291 return SDValue(Op.getNode(), 1);
13297 // If we found that truncation is beneficial, perform the truncation and
13299 if (NeedTruncation) {
13300 EVT VT = Op.getValueType();
13301 SDValue WideVal = Op->getOperand(0);
13302 EVT WideVT = WideVal.getValueType();
13303 unsigned ConvertedOp = 0;
13304 // Use a target machine opcode to prevent further DAGCombine
13305 // optimizations that may separate the arithmetic operations
13306 // from the setcc node.
13307 switch (WideVal.getOpcode()) {
13309 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13310 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13311 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13312 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13313 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13317 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13318 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13319 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13320 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13321 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13327 // Emit a CMP with 0, which is the TEST pattern.
13328 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13329 DAG.getConstant(0, dl, Op.getValueType()));
13331 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13332 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13334 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13335 DAG.ReplaceAllUsesWith(Op, New);
13336 return SDValue(New.getNode(), 1);
13339 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13341 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13342 SDLoc dl, SelectionDAG &DAG) const {
13343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13344 if (C->getAPIntValue() == 0)
13345 return EmitTest(Op0, X86CC, dl, DAG);
13347 if (Op0.getValueType() == MVT::i1)
13348 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13351 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13352 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13353 // Do the comparison at i32 if it's smaller, besides the Atom case.
13354 // This avoids subregister aliasing issues. Keep the smaller reference
13355 // if we're optimizing for size, however, as that'll allow better folding
13356 // of memory operations.
13357 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13358 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13359 !Subtarget->isAtom()) {
13360 unsigned ExtendOp =
13361 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13362 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13363 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13365 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13366 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13367 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13369 return SDValue(Sub.getNode(), 1);
13371 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13374 /// Convert a comparison if required by the subtarget.
13375 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13376 SelectionDAG &DAG) const {
13377 // If the subtarget does not support the FUCOMI instruction, floating-point
13378 // comparisons have to be converted.
13379 if (Subtarget->hasCMov() ||
13380 Cmp.getOpcode() != X86ISD::CMP ||
13381 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13382 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13385 // The instruction selector will select an FUCOM instruction instead of
13386 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13387 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13388 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13390 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13391 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13392 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13393 DAG.getConstant(8, dl, MVT::i8));
13394 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13395 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13398 /// The minimum architected relative accuracy is 2^-12. We need one
13399 /// Newton-Raphson step to have a good float result (24 bits of precision).
13400 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13401 DAGCombinerInfo &DCI,
13402 unsigned &RefinementSteps,
13403 bool &UseOneConstNR) const {
13404 EVT VT = Op.getValueType();
13405 const char *RecipOp;
13407 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13408 // TODO: Add support for AVX512 (v16f32).
13409 // It is likely not profitable to do this for f64 because a double-precision
13410 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13411 // instructions: convert to single, rsqrtss, convert back to double, refine
13412 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13413 // along with FMA, this could be a throughput win.
13414 if (VT == MVT::f32 && Subtarget->hasSSE1())
13416 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13417 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13418 RecipOp = "vec-sqrtf";
13422 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13423 if (!Recips.isEnabled(RecipOp))
13426 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13427 UseOneConstNR = false;
13428 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13431 /// The minimum architected relative accuracy is 2^-12. We need one
13432 /// Newton-Raphson step to have a good float result (24 bits of precision).
13433 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13434 DAGCombinerInfo &DCI,
13435 unsigned &RefinementSteps) const {
13436 EVT VT = Op.getValueType();
13437 const char *RecipOp;
13439 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13440 // TODO: Add support for AVX512 (v16f32).
13441 // It is likely not profitable to do this for f64 because a double-precision
13442 // reciprocal estimate with refinement on x86 prior to FMA requires
13443 // 15 instructions: convert to single, rcpss, convert back to double, refine
13444 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13445 // along with FMA, this could be a throughput win.
13446 if (VT == MVT::f32 && Subtarget->hasSSE1())
13448 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13449 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13450 RecipOp = "vec-divf";
13454 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13455 if (!Recips.isEnabled(RecipOp))
13458 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13459 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13462 /// If we have at least two divisions that use the same divisor, convert to
13463 /// multplication by a reciprocal. This may need to be adjusted for a given
13464 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13465 /// This is because we still need one division to calculate the reciprocal and
13466 /// then we need two multiplies by that reciprocal as replacements for the
13467 /// original divisions.
13468 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13472 static bool isAllOnes(SDValue V) {
13473 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13474 return C && C->isAllOnesValue();
13477 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13478 /// if it's possible.
13479 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13480 SDLoc dl, SelectionDAG &DAG) const {
13481 SDValue Op0 = And.getOperand(0);
13482 SDValue Op1 = And.getOperand(1);
13483 if (Op0.getOpcode() == ISD::TRUNCATE)
13484 Op0 = Op0.getOperand(0);
13485 if (Op1.getOpcode() == ISD::TRUNCATE)
13486 Op1 = Op1.getOperand(0);
13489 if (Op1.getOpcode() == ISD::SHL)
13490 std::swap(Op0, Op1);
13491 if (Op0.getOpcode() == ISD::SHL) {
13492 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13493 if (And00C->getZExtValue() == 1) {
13494 // If we looked past a truncate, check that it's only truncating away
13496 unsigned BitWidth = Op0.getValueSizeInBits();
13497 unsigned AndBitWidth = And.getValueSizeInBits();
13498 if (BitWidth > AndBitWidth) {
13500 DAG.computeKnownBits(Op0, Zeros, Ones);
13501 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13505 RHS = Op0.getOperand(1);
13507 } else if (Op1.getOpcode() == ISD::Constant) {
13508 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13509 uint64_t AndRHSVal = AndRHS->getZExtValue();
13510 SDValue AndLHS = Op0;
13512 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13513 LHS = AndLHS.getOperand(0);
13514 RHS = AndLHS.getOperand(1);
13517 // Use BT if the immediate can't be encoded in a TEST instruction.
13518 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13520 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13524 if (LHS.getNode()) {
13525 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13526 // instruction. Since the shift amount is in-range-or-undefined, we know
13527 // that doing a bittest on the i32 value is ok. We extend to i32 because
13528 // the encoding for the i16 version is larger than the i32 version.
13529 // Also promote i16 to i32 for performance / code size reason.
13530 if (LHS.getValueType() == MVT::i8 ||
13531 LHS.getValueType() == MVT::i16)
13532 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13534 // If the operand types disagree, extend the shift amount to match. Since
13535 // BT ignores high bits (like shifts) we can use anyextend.
13536 if (LHS.getValueType() != RHS.getValueType())
13537 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13539 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13540 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13541 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13542 DAG.getConstant(Cond, dl, MVT::i8), BT);
13548 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13550 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13555 // SSE Condition code mapping:
13564 switch (SetCCOpcode) {
13565 default: llvm_unreachable("Unexpected SETCC condition");
13567 case ISD::SETEQ: SSECC = 0; break;
13569 case ISD::SETGT: Swap = true; // Fallthrough
13571 case ISD::SETOLT: SSECC = 1; break;
13573 case ISD::SETGE: Swap = true; // Fallthrough
13575 case ISD::SETOLE: SSECC = 2; break;
13576 case ISD::SETUO: SSECC = 3; break;
13578 case ISD::SETNE: SSECC = 4; break;
13579 case ISD::SETULE: Swap = true; // Fallthrough
13580 case ISD::SETUGE: SSECC = 5; break;
13581 case ISD::SETULT: Swap = true; // Fallthrough
13582 case ISD::SETUGT: SSECC = 6; break;
13583 case ISD::SETO: SSECC = 7; break;
13585 case ISD::SETONE: SSECC = 8; break;
13588 std::swap(Op0, Op1);
13593 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13594 // ones, and then concatenate the result back.
13595 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13596 MVT VT = Op.getSimpleValueType();
13598 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13599 "Unsupported value type for operation");
13601 unsigned NumElems = VT.getVectorNumElements();
13603 SDValue CC = Op.getOperand(2);
13605 // Extract the LHS vectors
13606 SDValue LHS = Op.getOperand(0);
13607 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13608 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13610 // Extract the RHS vectors
13611 SDValue RHS = Op.getOperand(1);
13612 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13613 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13615 // Issue the operation on the smaller types and concatenate the result back
13616 MVT EltVT = VT.getVectorElementType();
13617 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13618 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13619 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13620 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13623 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13624 SDValue Op0 = Op.getOperand(0);
13625 SDValue Op1 = Op.getOperand(1);
13626 SDValue CC = Op.getOperand(2);
13627 MVT VT = Op.getSimpleValueType();
13630 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13631 "Unexpected type for boolean compare operation");
13632 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13633 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13634 DAG.getConstant(-1, dl, VT));
13635 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13636 DAG.getConstant(-1, dl, VT));
13637 switch (SetCCOpcode) {
13638 default: llvm_unreachable("Unexpected SETCC condition");
13640 // (x == y) -> ~(x ^ y)
13641 return DAG.getNode(ISD::XOR, dl, VT,
13642 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13643 DAG.getConstant(-1, dl, VT));
13645 // (x != y) -> (x ^ y)
13646 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13649 // (x > y) -> (x & ~y)
13650 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13653 // (x < y) -> (~x & y)
13654 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13657 // (x <= y) -> (~x | y)
13658 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13661 // (x >=y) -> (x | ~y)
13662 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13666 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13667 const X86Subtarget *Subtarget) {
13668 SDValue Op0 = Op.getOperand(0);
13669 SDValue Op1 = Op.getOperand(1);
13670 SDValue CC = Op.getOperand(2);
13671 MVT VT = Op.getSimpleValueType();
13674 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13675 Op.getValueType().getScalarType() == MVT::i1 &&
13676 "Cannot set masked compare for this operation");
13678 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13680 bool Unsigned = false;
13683 switch (SetCCOpcode) {
13684 default: llvm_unreachable("Unexpected SETCC condition");
13685 case ISD::SETNE: SSECC = 4; break;
13686 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13687 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13688 case ISD::SETLT: Swap = true; //fall-through
13689 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13690 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13691 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13692 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13693 case ISD::SETULE: Unsigned = true; //fall-through
13694 case ISD::SETLE: SSECC = 2; break;
13698 std::swap(Op0, Op1);
13700 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13701 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13702 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13703 DAG.getConstant(SSECC, dl, MVT::i8));
13706 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13707 /// operand \p Op1. If non-trivial (for example because it's not constant)
13708 /// return an empty value.
13709 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13711 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13715 MVT VT = Op1.getSimpleValueType();
13716 MVT EVT = VT.getVectorElementType();
13717 unsigned n = VT.getVectorNumElements();
13718 SmallVector<SDValue, 8> ULTOp1;
13720 for (unsigned i = 0; i < n; ++i) {
13721 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13722 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13725 // Avoid underflow.
13726 APInt Val = Elt->getAPIntValue();
13730 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13733 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13736 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13737 SelectionDAG &DAG) {
13738 SDValue Op0 = Op.getOperand(0);
13739 SDValue Op1 = Op.getOperand(1);
13740 SDValue CC = Op.getOperand(2);
13741 MVT VT = Op.getSimpleValueType();
13742 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13743 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13748 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13749 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13752 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13753 unsigned Opc = X86ISD::CMPP;
13754 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13755 assert(VT.getVectorNumElements() <= 16);
13756 Opc = X86ISD::CMPM;
13758 // In the two special cases we can't handle, emit two comparisons.
13761 unsigned CombineOpc;
13762 if (SetCCOpcode == ISD::SETUEQ) {
13763 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13765 assert(SetCCOpcode == ISD::SETONE);
13766 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13769 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13770 DAG.getConstant(CC0, dl, MVT::i8));
13771 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13772 DAG.getConstant(CC1, dl, MVT::i8));
13773 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13775 // Handle all other FP comparisons here.
13776 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13777 DAG.getConstant(SSECC, dl, MVT::i8));
13780 // Break 256-bit integer vector compare into smaller ones.
13781 if (VT.is256BitVector() && !Subtarget->hasInt256())
13782 return Lower256IntVSETCC(Op, DAG);
13784 EVT OpVT = Op1.getValueType();
13785 if (OpVT.getVectorElementType() == MVT::i1)
13786 return LowerBoolVSETCC_AVX512(Op, DAG);
13788 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13789 if (Subtarget->hasAVX512()) {
13790 if (Op1.getValueType().is512BitVector() ||
13791 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13792 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13793 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13795 // In AVX-512 architecture setcc returns mask with i1 elements,
13796 // But there is no compare instruction for i8 and i16 elements in KNL.
13797 // We are not talking about 512-bit operands in this case, these
13798 // types are illegal.
13800 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13801 OpVT.getVectorElementType().getSizeInBits() >= 8))
13802 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13803 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13806 // We are handling one of the integer comparisons here. Since SSE only has
13807 // GT and EQ comparisons for integer, swapping operands and multiple
13808 // operations may be required for some comparisons.
13810 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13811 bool Subus = false;
13813 switch (SetCCOpcode) {
13814 default: llvm_unreachable("Unexpected SETCC condition");
13815 case ISD::SETNE: Invert = true;
13816 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13817 case ISD::SETLT: Swap = true;
13818 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13819 case ISD::SETGE: Swap = true;
13820 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13821 Invert = true; break;
13822 case ISD::SETULT: Swap = true;
13823 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13824 FlipSigns = true; break;
13825 case ISD::SETUGE: Swap = true;
13826 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13827 FlipSigns = true; Invert = true; break;
13830 // Special case: Use min/max operations for SETULE/SETUGE
13831 MVT VET = VT.getVectorElementType();
13833 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13834 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13837 switch (SetCCOpcode) {
13839 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13840 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13843 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13846 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13847 if (!MinMax && hasSubus) {
13848 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13850 // t = psubus Op0, Op1
13851 // pcmpeq t, <0..0>
13852 switch (SetCCOpcode) {
13854 case ISD::SETULT: {
13855 // If the comparison is against a constant we can turn this into a
13856 // setule. With psubus, setule does not require a swap. This is
13857 // beneficial because the constant in the register is no longer
13858 // destructed as the destination so it can be hoisted out of a loop.
13859 // Only do this pre-AVX since vpcmp* is no longer destructive.
13860 if (Subtarget->hasAVX())
13862 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13863 if (ULEOp1.getNode()) {
13865 Subus = true; Invert = false; Swap = false;
13869 // Psubus is better than flip-sign because it requires no inversion.
13870 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13871 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13875 Opc = X86ISD::SUBUS;
13881 std::swap(Op0, Op1);
13883 // Check that the operation in question is available (most are plain SSE2,
13884 // but PCMPGTQ and PCMPEQQ have different requirements).
13885 if (VT == MVT::v2i64) {
13886 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13887 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13889 // First cast everything to the right type.
13890 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13891 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13893 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13894 // bits of the inputs before performing those operations. The lower
13895 // compare is always unsigned.
13898 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13900 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13901 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13902 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13903 Sign, Zero, Sign, Zero);
13905 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13906 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13908 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13909 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13910 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13912 // Create masks for only the low parts/high parts of the 64 bit integers.
13913 static const int MaskHi[] = { 1, 1, 3, 3 };
13914 static const int MaskLo[] = { 0, 0, 2, 2 };
13915 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13916 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13917 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13919 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13920 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13923 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13925 return DAG.getBitcast(VT, Result);
13928 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13929 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13930 // pcmpeqd + pshufd + pand.
13931 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13933 // First cast everything to the right type.
13934 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13935 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13938 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13940 // Make sure the lower and upper halves are both all-ones.
13941 static const int Mask[] = { 1, 0, 3, 2 };
13942 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13943 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13946 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13948 return DAG.getBitcast(VT, Result);
13952 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13953 // bits of the inputs before performing those operations.
13955 EVT EltVT = VT.getVectorElementType();
13956 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13958 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13959 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13962 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13964 // If the logical-not of the result is required, perform that now.
13966 Result = DAG.getNOT(dl, Result, VT);
13969 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13972 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13973 getZeroVector(VT, Subtarget, DAG, dl));
13978 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13980 MVT VT = Op.getSimpleValueType();
13982 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13984 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13985 && "SetCC type must be 8-bit or 1-bit integer");
13986 SDValue Op0 = Op.getOperand(0);
13987 SDValue Op1 = Op.getOperand(1);
13989 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13991 // Optimize to BT if possible.
13992 // Lower (X & (1 << N)) == 0 to BT(X, N).
13993 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13994 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13995 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13996 Op1.getOpcode() == ISD::Constant &&
13997 cast<ConstantSDNode>(Op1)->isNullValue() &&
13998 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13999 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14000 if (NewSetCC.getNode()) {
14002 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14007 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14009 if (Op1.getOpcode() == ISD::Constant &&
14010 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14011 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14012 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14014 // If the input is a setcc, then reuse the input setcc or use a new one with
14015 // the inverted condition.
14016 if (Op0.getOpcode() == X86ISD::SETCC) {
14017 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14018 bool Invert = (CC == ISD::SETNE) ^
14019 cast<ConstantSDNode>(Op1)->isNullValue();
14023 CCode = X86::GetOppositeBranchCondition(CCode);
14024 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14025 DAG.getConstant(CCode, dl, MVT::i8),
14026 Op0.getOperand(1));
14028 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14032 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14033 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14034 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14036 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14037 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14040 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14041 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14042 if (X86CC == X86::COND_INVALID)
14045 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14046 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14047 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14048 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14050 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14054 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14055 static bool isX86LogicalCmp(SDValue Op) {
14056 unsigned Opc = Op.getNode()->getOpcode();
14057 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14058 Opc == X86ISD::SAHF)
14060 if (Op.getResNo() == 1 &&
14061 (Opc == X86ISD::ADD ||
14062 Opc == X86ISD::SUB ||
14063 Opc == X86ISD::ADC ||
14064 Opc == X86ISD::SBB ||
14065 Opc == X86ISD::SMUL ||
14066 Opc == X86ISD::UMUL ||
14067 Opc == X86ISD::INC ||
14068 Opc == X86ISD::DEC ||
14069 Opc == X86ISD::OR ||
14070 Opc == X86ISD::XOR ||
14071 Opc == X86ISD::AND))
14074 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14080 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14081 if (V.getOpcode() != ISD::TRUNCATE)
14084 SDValue VOp0 = V.getOperand(0);
14085 unsigned InBits = VOp0.getValueSizeInBits();
14086 unsigned Bits = V.getValueSizeInBits();
14087 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14090 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14091 bool addTest = true;
14092 SDValue Cond = Op.getOperand(0);
14093 SDValue Op1 = Op.getOperand(1);
14094 SDValue Op2 = Op.getOperand(2);
14096 EVT VT = Op1.getValueType();
14099 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14100 // are available or VBLENDV if AVX is available.
14101 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14102 if (Cond.getOpcode() == ISD::SETCC &&
14103 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14104 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14105 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14106 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14107 int SSECC = translateX86FSETCC(
14108 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14111 if (Subtarget->hasAVX512()) {
14112 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14113 DAG.getConstant(SSECC, DL, MVT::i8));
14114 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14117 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14118 DAG.getConstant(SSECC, DL, MVT::i8));
14120 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14121 // of 3 logic instructions for size savings and potentially speed.
14122 // Unfortunately, there is no scalar form of VBLENDV.
14124 // If either operand is a constant, don't try this. We can expect to
14125 // optimize away at least one of the logic instructions later in that
14126 // case, so that sequence would be faster than a variable blend.
14128 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14129 // uses XMM0 as the selection register. That may need just as many
14130 // instructions as the AND/ANDN/OR sequence due to register moves, so
14133 if (Subtarget->hasAVX() &&
14134 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14136 // Convert to vectors, do a VSELECT, and convert back to scalar.
14137 // All of the conversions should be optimized away.
14139 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14140 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14141 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14142 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14144 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14145 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14147 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14149 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14150 VSel, DAG.getIntPtrConstant(0, DL));
14152 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14153 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14154 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14158 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14160 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14161 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14162 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14163 Op1Scalar = Op1.getOperand(0);
14165 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14166 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14167 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14168 Op2Scalar = Op2.getOperand(0);
14169 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14170 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14171 Op1Scalar.getValueType(),
14172 Cond, Op1Scalar, Op2Scalar);
14173 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14174 return DAG.getBitcast(VT, newSelect);
14175 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14176 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14177 DAG.getIntPtrConstant(0, DL));
14181 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14182 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14183 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14184 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14185 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14186 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14187 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14189 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14192 if (Cond.getOpcode() == ISD::SETCC) {
14193 SDValue NewCond = LowerSETCC(Cond, DAG);
14194 if (NewCond.getNode())
14198 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14199 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14200 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14201 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14202 if (Cond.getOpcode() == X86ISD::SETCC &&
14203 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14204 isZero(Cond.getOperand(1).getOperand(1))) {
14205 SDValue Cmp = Cond.getOperand(1);
14207 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14209 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14210 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14211 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14213 SDValue CmpOp0 = Cmp.getOperand(0);
14214 // Apply further optimizations for special cases
14215 // (select (x != 0), -1, 0) -> neg & sbb
14216 // (select (x == 0), 0, -1) -> neg & sbb
14217 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14218 if (YC->isNullValue() &&
14219 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14220 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14221 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14222 DAG.getConstant(0, DL,
14223 CmpOp0.getValueType()),
14225 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14226 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14227 SDValue(Neg.getNode(), 1));
14231 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14232 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14233 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14235 SDValue Res = // Res = 0 or -1.
14236 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14237 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14239 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14240 Res = DAG.getNOT(DL, Res, Res.getValueType());
14242 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14243 if (!N2C || !N2C->isNullValue())
14244 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14249 // Look past (and (setcc_carry (cmp ...)), 1).
14250 if (Cond.getOpcode() == ISD::AND &&
14251 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14252 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14253 if (C && C->getAPIntValue() == 1)
14254 Cond = Cond.getOperand(0);
14257 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14258 // setting operand in place of the X86ISD::SETCC.
14259 unsigned CondOpcode = Cond.getOpcode();
14260 if (CondOpcode == X86ISD::SETCC ||
14261 CondOpcode == X86ISD::SETCC_CARRY) {
14262 CC = Cond.getOperand(0);
14264 SDValue Cmp = Cond.getOperand(1);
14265 unsigned Opc = Cmp.getOpcode();
14266 MVT VT = Op.getSimpleValueType();
14268 bool IllegalFPCMov = false;
14269 if (VT.isFloatingPoint() && !VT.isVector() &&
14270 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14271 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14273 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14274 Opc == X86ISD::BT) { // FIXME
14278 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14279 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14280 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14281 Cond.getOperand(0).getValueType() != MVT::i8)) {
14282 SDValue LHS = Cond.getOperand(0);
14283 SDValue RHS = Cond.getOperand(1);
14284 unsigned X86Opcode;
14287 switch (CondOpcode) {
14288 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14289 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14290 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14291 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14292 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14293 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14294 default: llvm_unreachable("unexpected overflowing operator");
14296 if (CondOpcode == ISD::UMULO)
14297 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14300 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14302 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14304 if (CondOpcode == ISD::UMULO)
14305 Cond = X86Op.getValue(2);
14307 Cond = X86Op.getValue(1);
14309 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14314 // Look past the truncate if the high bits are known zero.
14315 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14316 Cond = Cond.getOperand(0);
14318 // We know the result of AND is compared against zero. Try to match
14320 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14321 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14322 if (NewSetCC.getNode()) {
14323 CC = NewSetCC.getOperand(0);
14324 Cond = NewSetCC.getOperand(1);
14331 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14332 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14335 // a < b ? -1 : 0 -> RES = ~setcc_carry
14336 // a < b ? 0 : -1 -> RES = setcc_carry
14337 // a >= b ? -1 : 0 -> RES = setcc_carry
14338 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14339 if (Cond.getOpcode() == X86ISD::SUB) {
14340 Cond = ConvertCmpIfNecessary(Cond, DAG);
14341 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14343 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14344 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14345 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14346 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14348 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14349 return DAG.getNOT(DL, Res, Res.getValueType());
14354 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14355 // widen the cmov and push the truncate through. This avoids introducing a new
14356 // branch during isel and doesn't add any extensions.
14357 if (Op.getValueType() == MVT::i8 &&
14358 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14359 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14360 if (T1.getValueType() == T2.getValueType() &&
14361 // Blacklist CopyFromReg to avoid partial register stalls.
14362 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14363 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14364 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14365 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14369 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14370 // condition is true.
14371 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14372 SDValue Ops[] = { Op2, Op1, CC, Cond };
14373 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14376 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14377 const X86Subtarget *Subtarget,
14378 SelectionDAG &DAG) {
14379 MVT VT = Op->getSimpleValueType(0);
14380 SDValue In = Op->getOperand(0);
14381 MVT InVT = In.getSimpleValueType();
14382 MVT VTElt = VT.getVectorElementType();
14383 MVT InVTElt = InVT.getVectorElementType();
14387 if ((InVTElt == MVT::i1) &&
14388 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14389 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14391 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14392 VTElt.getSizeInBits() <= 16)) ||
14394 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14395 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14397 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14398 VTElt.getSizeInBits() >= 32))))
14399 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14401 unsigned int NumElts = VT.getVectorNumElements();
14403 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14406 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14407 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14408 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14409 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14412 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14413 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14415 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14418 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14420 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14421 if (VT.is512BitVector())
14423 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14426 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14427 const X86Subtarget *Subtarget,
14428 SelectionDAG &DAG) {
14429 SDValue In = Op->getOperand(0);
14430 MVT VT = Op->getSimpleValueType(0);
14431 MVT InVT = In.getSimpleValueType();
14432 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14434 MVT InSVT = InVT.getScalarType();
14435 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14437 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14439 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14444 // SSE41 targets can use the pmovsx* instructions directly.
14445 if (Subtarget->hasSSE41())
14446 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14448 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14452 // As SRAI is only available on i16/i32 types, we expand only up to i32
14453 // and handle i64 separately.
14454 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14455 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14456 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14457 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14458 Curr = DAG.getBitcast(CurrVT, Curr);
14461 SDValue SignExt = Curr;
14462 if (CurrVT != InVT) {
14463 unsigned SignExtShift =
14464 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14465 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14466 DAG.getConstant(SignExtShift, dl, MVT::i8));
14472 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14473 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14474 DAG.getConstant(31, dl, MVT::i8));
14475 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14476 return DAG.getBitcast(VT, Ext);
14482 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14483 SelectionDAG &DAG) {
14484 MVT VT = Op->getSimpleValueType(0);
14485 SDValue In = Op->getOperand(0);
14486 MVT InVT = In.getSimpleValueType();
14489 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14490 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14492 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14493 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14494 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14497 if (Subtarget->hasInt256())
14498 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14500 // Optimize vectors in AVX mode
14501 // Sign extend v8i16 to v8i32 and
14504 // Divide input vector into two parts
14505 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14506 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14507 // concat the vectors to original VT
14509 unsigned NumElems = InVT.getVectorNumElements();
14510 SDValue Undef = DAG.getUNDEF(InVT);
14512 SmallVector<int,8> ShufMask1(NumElems, -1);
14513 for (unsigned i = 0; i != NumElems/2; ++i)
14516 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14518 SmallVector<int,8> ShufMask2(NumElems, -1);
14519 for (unsigned i = 0; i != NumElems/2; ++i)
14520 ShufMask2[i] = i + NumElems/2;
14522 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14524 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14525 VT.getVectorNumElements()/2);
14527 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14528 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14530 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14533 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14534 // may emit an illegal shuffle but the expansion is still better than scalar
14535 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14536 // we'll emit a shuffle and a arithmetic shift.
14537 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14538 // TODO: It is possible to support ZExt by zeroing the undef values during
14539 // the shuffle phase or after the shuffle.
14540 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14541 SelectionDAG &DAG) {
14542 MVT RegVT = Op.getSimpleValueType();
14543 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14544 assert(RegVT.isInteger() &&
14545 "We only custom lower integer vector sext loads.");
14547 // Nothing useful we can do without SSE2 shuffles.
14548 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14550 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14552 EVT MemVT = Ld->getMemoryVT();
14553 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14554 unsigned RegSz = RegVT.getSizeInBits();
14556 ISD::LoadExtType Ext = Ld->getExtensionType();
14558 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14559 && "Only anyext and sext are currently implemented.");
14560 assert(MemVT != RegVT && "Cannot extend to the same type");
14561 assert(MemVT.isVector() && "Must load a vector from memory");
14563 unsigned NumElems = RegVT.getVectorNumElements();
14564 unsigned MemSz = MemVT.getSizeInBits();
14565 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14567 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14568 // The only way in which we have a legal 256-bit vector result but not the
14569 // integer 256-bit operations needed to directly lower a sextload is if we
14570 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14571 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14572 // correctly legalized. We do this late to allow the canonical form of
14573 // sextload to persist throughout the rest of the DAG combiner -- it wants
14574 // to fold together any extensions it can, and so will fuse a sign_extend
14575 // of an sextload into a sextload targeting a wider value.
14577 if (MemSz == 128) {
14578 // Just switch this to a normal load.
14579 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14580 "it must be a legal 128-bit vector "
14582 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14583 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14584 Ld->isInvariant(), Ld->getAlignment());
14586 assert(MemSz < 128 &&
14587 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14588 // Do an sext load to a 128-bit vector type. We want to use the same
14589 // number of elements, but elements half as wide. This will end up being
14590 // recursively lowered by this routine, but will succeed as we definitely
14591 // have all the necessary features if we're using AVX1.
14593 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14594 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14596 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14597 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14598 Ld->isNonTemporal(), Ld->isInvariant(),
14599 Ld->getAlignment());
14602 // Replace chain users with the new chain.
14603 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14604 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14606 // Finally, do a normal sign-extend to the desired register.
14607 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14610 // All sizes must be a power of two.
14611 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14612 "Non-power-of-two elements are not custom lowered!");
14614 // Attempt to load the original value using scalar loads.
14615 // Find the largest scalar type that divides the total loaded size.
14616 MVT SclrLoadTy = MVT::i8;
14617 for (MVT Tp : MVT::integer_valuetypes()) {
14618 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14623 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14624 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14626 SclrLoadTy = MVT::f64;
14628 // Calculate the number of scalar loads that we need to perform
14629 // in order to load our vector from memory.
14630 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14632 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14633 "Can only lower sext loads with a single scalar load!");
14635 unsigned loadRegZize = RegSz;
14636 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14639 // Represent our vector as a sequence of elements which are the
14640 // largest scalar that we can load.
14641 EVT LoadUnitVecVT = EVT::getVectorVT(
14642 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14644 // Represent the data using the same element type that is stored in
14645 // memory. In practice, we ''widen'' MemVT.
14647 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14648 loadRegZize / MemVT.getScalarType().getSizeInBits());
14650 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14651 "Invalid vector type");
14653 // We can't shuffle using an illegal type.
14654 assert(TLI.isTypeLegal(WideVecVT) &&
14655 "We only lower types that form legal widened vector types");
14657 SmallVector<SDValue, 8> Chains;
14658 SDValue Ptr = Ld->getBasePtr();
14659 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14660 TLI.getPointerTy(DAG.getDataLayout()));
14661 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14663 for (unsigned i = 0; i < NumLoads; ++i) {
14664 // Perform a single load.
14665 SDValue ScalarLoad =
14666 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14667 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14668 Ld->getAlignment());
14669 Chains.push_back(ScalarLoad.getValue(1));
14670 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14671 // another round of DAGCombining.
14673 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14675 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14676 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14678 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14681 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14683 // Bitcast the loaded value to a vector of the original element type, in
14684 // the size of the target vector type.
14685 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14686 unsigned SizeRatio = RegSz / MemSz;
14688 if (Ext == ISD::SEXTLOAD) {
14689 // If we have SSE4.1, we can directly emit a VSEXT node.
14690 if (Subtarget->hasSSE41()) {
14691 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14692 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14696 // Otherwise we'll shuffle the small elements in the high bits of the
14697 // larger type and perform an arithmetic shift. If the shift is not legal
14698 // it's better to scalarize.
14699 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14700 "We can't implement a sext load without an arithmetic right shift!");
14702 // Redistribute the loaded elements into the different locations.
14703 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14704 for (unsigned i = 0; i != NumElems; ++i)
14705 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14707 SDValue Shuff = DAG.getVectorShuffle(
14708 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14710 Shuff = DAG.getBitcast(RegVT, Shuff);
14712 // Build the arithmetic shift.
14713 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14714 MemVT.getVectorElementType().getSizeInBits();
14716 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14717 DAG.getConstant(Amt, dl, RegVT));
14719 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14723 // Redistribute the loaded elements into the different locations.
14724 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14725 for (unsigned i = 0; i != NumElems; ++i)
14726 ShuffleVec[i * SizeRatio] = i;
14728 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14729 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14731 // Bitcast to the requested type.
14732 Shuff = DAG.getBitcast(RegVT, Shuff);
14733 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14737 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14738 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14739 // from the AND / OR.
14740 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14741 Opc = Op.getOpcode();
14742 if (Opc != ISD::OR && Opc != ISD::AND)
14744 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14745 Op.getOperand(0).hasOneUse() &&
14746 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14747 Op.getOperand(1).hasOneUse());
14750 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14751 // 1 and that the SETCC node has a single use.
14752 static bool isXor1OfSetCC(SDValue Op) {
14753 if (Op.getOpcode() != ISD::XOR)
14755 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14756 if (N1C && N1C->getAPIntValue() == 1) {
14757 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14758 Op.getOperand(0).hasOneUse();
14763 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14764 bool addTest = true;
14765 SDValue Chain = Op.getOperand(0);
14766 SDValue Cond = Op.getOperand(1);
14767 SDValue Dest = Op.getOperand(2);
14770 bool Inverted = false;
14772 if (Cond.getOpcode() == ISD::SETCC) {
14773 // Check for setcc([su]{add,sub,mul}o == 0).
14774 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14775 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14776 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14777 Cond.getOperand(0).getResNo() == 1 &&
14778 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14779 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14780 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14781 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14782 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14783 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14785 Cond = Cond.getOperand(0);
14787 SDValue NewCond = LowerSETCC(Cond, DAG);
14788 if (NewCond.getNode())
14793 // FIXME: LowerXALUO doesn't handle these!!
14794 else if (Cond.getOpcode() == X86ISD::ADD ||
14795 Cond.getOpcode() == X86ISD::SUB ||
14796 Cond.getOpcode() == X86ISD::SMUL ||
14797 Cond.getOpcode() == X86ISD::UMUL)
14798 Cond = LowerXALUO(Cond, DAG);
14801 // Look pass (and (setcc_carry (cmp ...)), 1).
14802 if (Cond.getOpcode() == ISD::AND &&
14803 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14804 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14805 if (C && C->getAPIntValue() == 1)
14806 Cond = Cond.getOperand(0);
14809 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14810 // setting operand in place of the X86ISD::SETCC.
14811 unsigned CondOpcode = Cond.getOpcode();
14812 if (CondOpcode == X86ISD::SETCC ||
14813 CondOpcode == X86ISD::SETCC_CARRY) {
14814 CC = Cond.getOperand(0);
14816 SDValue Cmp = Cond.getOperand(1);
14817 unsigned Opc = Cmp.getOpcode();
14818 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14819 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14823 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14827 // These can only come from an arithmetic instruction with overflow,
14828 // e.g. SADDO, UADDO.
14829 Cond = Cond.getNode()->getOperand(1);
14835 CondOpcode = Cond.getOpcode();
14836 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14837 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14838 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14839 Cond.getOperand(0).getValueType() != MVT::i8)) {
14840 SDValue LHS = Cond.getOperand(0);
14841 SDValue RHS = Cond.getOperand(1);
14842 unsigned X86Opcode;
14845 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14846 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14848 switch (CondOpcode) {
14849 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14851 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14853 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14856 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14857 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14861 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14864 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14865 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14866 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14867 default: llvm_unreachable("unexpected overflowing operator");
14870 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14871 if (CondOpcode == ISD::UMULO)
14872 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14875 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14877 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14879 if (CondOpcode == ISD::UMULO)
14880 Cond = X86Op.getValue(2);
14882 Cond = X86Op.getValue(1);
14884 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14888 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14889 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14890 if (CondOpc == ISD::OR) {
14891 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14892 // two branches instead of an explicit OR instruction with a
14894 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14895 isX86LogicalCmp(Cmp)) {
14896 CC = Cond.getOperand(0).getOperand(0);
14897 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14898 Chain, Dest, CC, Cmp);
14899 CC = Cond.getOperand(1).getOperand(0);
14903 } else { // ISD::AND
14904 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14905 // two branches instead of an explicit AND instruction with a
14906 // separate test. However, we only do this if this block doesn't
14907 // have a fall-through edge, because this requires an explicit
14908 // jmp when the condition is false.
14909 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14910 isX86LogicalCmp(Cmp) &&
14911 Op.getNode()->hasOneUse()) {
14912 X86::CondCode CCode =
14913 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14914 CCode = X86::GetOppositeBranchCondition(CCode);
14915 CC = DAG.getConstant(CCode, dl, MVT::i8);
14916 SDNode *User = *Op.getNode()->use_begin();
14917 // Look for an unconditional branch following this conditional branch.
14918 // We need this because we need to reverse the successors in order
14919 // to implement FCMP_OEQ.
14920 if (User->getOpcode() == ISD::BR) {
14921 SDValue FalseBB = User->getOperand(1);
14923 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14924 assert(NewBR == User);
14928 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14929 Chain, Dest, CC, Cmp);
14930 X86::CondCode CCode =
14931 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14932 CCode = X86::GetOppositeBranchCondition(CCode);
14933 CC = DAG.getConstant(CCode, dl, MVT::i8);
14939 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14940 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14941 // It should be transformed during dag combiner except when the condition
14942 // is set by a arithmetics with overflow node.
14943 X86::CondCode CCode =
14944 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14945 CCode = X86::GetOppositeBranchCondition(CCode);
14946 CC = DAG.getConstant(CCode, dl, MVT::i8);
14947 Cond = Cond.getOperand(0).getOperand(1);
14949 } else if (Cond.getOpcode() == ISD::SETCC &&
14950 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14951 // For FCMP_OEQ, we can emit
14952 // two branches instead of an explicit AND instruction with a
14953 // separate test. However, we only do this if this block doesn't
14954 // have a fall-through edge, because this requires an explicit
14955 // jmp when the condition is false.
14956 if (Op.getNode()->hasOneUse()) {
14957 SDNode *User = *Op.getNode()->use_begin();
14958 // Look for an unconditional branch following this conditional branch.
14959 // We need this because we need to reverse the successors in order
14960 // to implement FCMP_OEQ.
14961 if (User->getOpcode() == ISD::BR) {
14962 SDValue FalseBB = User->getOperand(1);
14964 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14965 assert(NewBR == User);
14969 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14970 Cond.getOperand(0), Cond.getOperand(1));
14971 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14972 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14973 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14974 Chain, Dest, CC, Cmp);
14975 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14980 } else if (Cond.getOpcode() == ISD::SETCC &&
14981 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14982 // For FCMP_UNE, we can emit
14983 // two branches instead of an explicit AND instruction with a
14984 // separate test. However, we only do this if this block doesn't
14985 // have a fall-through edge, because this requires an explicit
14986 // jmp when the condition is false.
14987 if (Op.getNode()->hasOneUse()) {
14988 SDNode *User = *Op.getNode()->use_begin();
14989 // Look for an unconditional branch following this conditional branch.
14990 // We need this because we need to reverse the successors in order
14991 // to implement FCMP_UNE.
14992 if (User->getOpcode() == ISD::BR) {
14993 SDValue FalseBB = User->getOperand(1);
14995 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14996 assert(NewBR == User);
14999 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15000 Cond.getOperand(0), Cond.getOperand(1));
15001 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15002 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15003 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15004 Chain, Dest, CC, Cmp);
15005 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15015 // Look pass the truncate if the high bits are known zero.
15016 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15017 Cond = Cond.getOperand(0);
15019 // We know the result of AND is compared against zero. Try to match
15021 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15022 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15023 if (NewSetCC.getNode()) {
15024 CC = NewSetCC.getOperand(0);
15025 Cond = NewSetCC.getOperand(1);
15032 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15033 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15034 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15036 Cond = ConvertCmpIfNecessary(Cond, DAG);
15037 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15038 Chain, Dest, CC, Cond);
15041 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15042 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15043 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15044 // that the guard pages used by the OS virtual memory manager are allocated in
15045 // correct sequence.
15047 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15048 SelectionDAG &DAG) const {
15049 MachineFunction &MF = DAG.getMachineFunction();
15050 bool SplitStack = MF.shouldSplitStack();
15051 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15057 SDNode* Node = Op.getNode();
15059 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15060 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15061 " not tell us which reg is the stack pointer!");
15062 EVT VT = Node->getValueType(0);
15063 SDValue Tmp1 = SDValue(Node, 0);
15064 SDValue Tmp2 = SDValue(Node, 1);
15065 SDValue Tmp3 = Node->getOperand(2);
15066 SDValue Chain = Tmp1.getOperand(0);
15068 // Chain the dynamic stack allocation so that it doesn't modify the stack
15069 // pointer when other instructions are using the stack.
15070 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15073 SDValue Size = Tmp2.getOperand(1);
15074 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15075 Chain = SP.getValue(1);
15076 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15077 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15078 unsigned StackAlign = TFI.getStackAlignment();
15079 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15080 if (Align > StackAlign)
15081 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15082 DAG.getConstant(-(uint64_t)Align, dl, VT));
15083 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15085 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15086 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15089 SDValue Ops[2] = { Tmp1, Tmp2 };
15090 return DAG.getMergeValues(Ops, dl);
15094 SDValue Chain = Op.getOperand(0);
15095 SDValue Size = Op.getOperand(1);
15096 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15097 EVT VT = Op.getNode()->getValueType(0);
15099 bool Is64Bit = Subtarget->is64Bit();
15100 MVT SPTy = getPointerTy(DAG.getDataLayout());
15103 MachineRegisterInfo &MRI = MF.getRegInfo();
15106 // The 64 bit implementation of segmented stacks needs to clobber both r10
15107 // r11. This makes it impossible to use it along with nested parameters.
15108 const Function *F = MF.getFunction();
15110 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15112 if (I->hasNestAttr())
15113 report_fatal_error("Cannot use segmented stacks with functions that "
15114 "have nested arguments.");
15117 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15118 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15119 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15120 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15121 DAG.getRegister(Vreg, SPTy));
15122 SDValue Ops1[2] = { Value, Chain };
15123 return DAG.getMergeValues(Ops1, dl);
15126 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15128 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15129 Flag = Chain.getValue(1);
15130 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15132 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15134 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15135 unsigned SPReg = RegInfo->getStackRegister();
15136 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15137 Chain = SP.getValue(1);
15140 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15141 DAG.getConstant(-(uint64_t)Align, dl, VT));
15142 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15145 SDValue Ops1[2] = { SP, Chain };
15146 return DAG.getMergeValues(Ops1, dl);
15150 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15151 MachineFunction &MF = DAG.getMachineFunction();
15152 auto PtrVT = getPointerTy(MF.getDataLayout());
15153 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15155 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15158 if (!Subtarget->is64Bit() ||
15159 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15160 // vastart just stores the address of the VarArgsFrameIndex slot into the
15161 // memory location argument.
15162 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15163 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15164 MachinePointerInfo(SV), false, false, 0);
15168 // gp_offset (0 - 6 * 8)
15169 // fp_offset (48 - 48 + 8 * 16)
15170 // overflow_arg_area (point to parameters coming in memory).
15172 SmallVector<SDValue, 8> MemOps;
15173 SDValue FIN = Op.getOperand(1);
15175 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15176 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15178 FIN, MachinePointerInfo(SV), false, false, 0);
15179 MemOps.push_back(Store);
15182 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15183 Store = DAG.getStore(Op.getOperand(0), DL,
15184 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15186 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15187 MemOps.push_back(Store);
15189 // Store ptr to overflow_arg_area
15190 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15191 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15192 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15193 MachinePointerInfo(SV, 8),
15195 MemOps.push_back(Store);
15197 // Store ptr to reg_save_area.
15198 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15199 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15200 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15201 MachinePointerInfo(SV, 16), false, false, 0);
15202 MemOps.push_back(Store);
15203 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15206 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15207 assert(Subtarget->is64Bit() &&
15208 "LowerVAARG only handles 64-bit va_arg!");
15209 assert(Op.getNode()->getNumOperands() == 4);
15211 MachineFunction &MF = DAG.getMachineFunction();
15212 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15213 // The Win64 ABI uses char* instead of a structure.
15214 return DAG.expandVAArg(Op.getNode());
15216 SDValue Chain = Op.getOperand(0);
15217 SDValue SrcPtr = Op.getOperand(1);
15218 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15219 unsigned Align = Op.getConstantOperandVal(3);
15222 EVT ArgVT = Op.getNode()->getValueType(0);
15223 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15224 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15227 // Decide which area this value should be read from.
15228 // TODO: Implement the AMD64 ABI in its entirety. This simple
15229 // selection mechanism works only for the basic types.
15230 if (ArgVT == MVT::f80) {
15231 llvm_unreachable("va_arg for f80 not yet implemented");
15232 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15233 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15234 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15235 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15237 llvm_unreachable("Unhandled argument type in LowerVAARG");
15240 if (ArgMode == 2) {
15241 // Sanity Check: Make sure using fp_offset makes sense.
15242 assert(!Subtarget->useSoftFloat() &&
15243 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15244 Subtarget->hasSSE1());
15247 // Insert VAARG_64 node into the DAG
15248 // VAARG_64 returns two values: Variable Argument Address, Chain
15249 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15250 DAG.getConstant(ArgMode, dl, MVT::i8),
15251 DAG.getConstant(Align, dl, MVT::i32)};
15252 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15253 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15254 VTs, InstOps, MVT::i64,
15255 MachinePointerInfo(SV),
15257 /*Volatile=*/false,
15259 /*WriteMem=*/true);
15260 Chain = VAARG.getValue(1);
15262 // Load the next argument and return it
15263 return DAG.getLoad(ArgVT, dl,
15266 MachinePointerInfo(),
15267 false, false, false, 0);
15270 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15271 SelectionDAG &DAG) {
15272 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15273 // where a va_list is still an i8*.
15274 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15275 if (Subtarget->isCallingConvWin64(
15276 DAG.getMachineFunction().getFunction()->getCallingConv()))
15277 // Probably a Win64 va_copy.
15278 return DAG.expandVACopy(Op.getNode());
15280 SDValue Chain = Op.getOperand(0);
15281 SDValue DstPtr = Op.getOperand(1);
15282 SDValue SrcPtr = Op.getOperand(2);
15283 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15284 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15287 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15288 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15290 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15293 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15294 // amount is a constant. Takes immediate version of shift as input.
15295 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15296 SDValue SrcOp, uint64_t ShiftAmt,
15297 SelectionDAG &DAG) {
15298 MVT ElementType = VT.getVectorElementType();
15300 // Fold this packed shift into its first operand if ShiftAmt is 0.
15304 // Check for ShiftAmt >= element width
15305 if (ShiftAmt >= ElementType.getSizeInBits()) {
15306 if (Opc == X86ISD::VSRAI)
15307 ShiftAmt = ElementType.getSizeInBits() - 1;
15309 return DAG.getConstant(0, dl, VT);
15312 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15313 && "Unknown target vector shift-by-constant node");
15315 // Fold this packed vector shift into a build vector if SrcOp is a
15316 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15317 if (VT == SrcOp.getSimpleValueType() &&
15318 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15319 SmallVector<SDValue, 8> Elts;
15320 unsigned NumElts = SrcOp->getNumOperands();
15321 ConstantSDNode *ND;
15324 default: llvm_unreachable(nullptr);
15325 case X86ISD::VSHLI:
15326 for (unsigned i=0; i!=NumElts; ++i) {
15327 SDValue CurrentOp = SrcOp->getOperand(i);
15328 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15329 Elts.push_back(CurrentOp);
15332 ND = cast<ConstantSDNode>(CurrentOp);
15333 const APInt &C = ND->getAPIntValue();
15334 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15337 case X86ISD::VSRLI:
15338 for (unsigned i=0; i!=NumElts; ++i) {
15339 SDValue CurrentOp = SrcOp->getOperand(i);
15340 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15341 Elts.push_back(CurrentOp);
15344 ND = cast<ConstantSDNode>(CurrentOp);
15345 const APInt &C = ND->getAPIntValue();
15346 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15349 case X86ISD::VSRAI:
15350 for (unsigned i=0; i!=NumElts; ++i) {
15351 SDValue CurrentOp = SrcOp->getOperand(i);
15352 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15353 Elts.push_back(CurrentOp);
15356 ND = cast<ConstantSDNode>(CurrentOp);
15357 const APInt &C = ND->getAPIntValue();
15358 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15363 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15366 return DAG.getNode(Opc, dl, VT, SrcOp,
15367 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15370 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15371 // may or may not be a constant. Takes immediate version of shift as input.
15372 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15373 SDValue SrcOp, SDValue ShAmt,
15374 SelectionDAG &DAG) {
15375 MVT SVT = ShAmt.getSimpleValueType();
15376 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15378 // Catch shift-by-constant.
15379 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15380 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15381 CShAmt->getZExtValue(), DAG);
15383 // Change opcode to non-immediate version
15385 default: llvm_unreachable("Unknown target vector shift node");
15386 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15387 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15388 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15391 const X86Subtarget &Subtarget =
15392 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15393 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15394 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15395 // Let the shuffle legalizer expand this shift amount node.
15396 SDValue Op0 = ShAmt.getOperand(0);
15397 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15398 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15400 // Need to build a vector containing shift amount.
15401 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15402 SmallVector<SDValue, 4> ShOps;
15403 ShOps.push_back(ShAmt);
15404 if (SVT == MVT::i32) {
15405 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15406 ShOps.push_back(DAG.getUNDEF(SVT));
15408 ShOps.push_back(DAG.getUNDEF(SVT));
15410 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15411 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15414 // The return type has to be a 128-bit type with the same element
15415 // type as the input type.
15416 MVT EltVT = VT.getVectorElementType();
15417 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15419 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15420 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15423 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15424 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15425 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15426 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15427 SDValue PreservedSrc,
15428 const X86Subtarget *Subtarget,
15429 SelectionDAG &DAG) {
15430 EVT VT = Op.getValueType();
15431 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15432 MVT::i1, VT.getVectorNumElements());
15433 SDValue VMask = SDValue();
15434 unsigned OpcodeSelect = ISD::VSELECT;
15437 assert(MaskVT.isSimple() && "invalid mask type");
15439 if (isAllOnes(Mask))
15442 if (MaskVT.bitsGT(Mask.getValueType())) {
15443 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15444 MaskVT.getSizeInBits());
15445 VMask = DAG.getBitcast(MaskVT,
15446 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15448 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15449 Mask.getValueType().getSizeInBits());
15450 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15451 // are extracted by EXTRACT_SUBVECTOR.
15452 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15453 DAG.getBitcast(BitcastVT, Mask),
15454 DAG.getIntPtrConstant(0, dl));
15457 switch (Op.getOpcode()) {
15459 case X86ISD::PCMPEQM:
15460 case X86ISD::PCMPGTM:
15462 case X86ISD::CMPMU:
15463 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15464 case X86ISD::VTRUNC:
15465 case X86ISD::VTRUNCS:
15466 case X86ISD::VTRUNCUS:
15467 // We can't use ISD::VSELECT here because it is not always "Legal"
15468 // for the destination type. For example vpmovqb require only AVX512
15469 // and vselect that can operate on byte element type require BWI
15470 OpcodeSelect = X86ISD::SELECT;
15473 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15474 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15475 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15478 /// \brief Creates an SDNode for a predicated scalar operation.
15479 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15480 /// The mask is coming as MVT::i8 and it should be truncated
15481 /// to MVT::i1 while lowering masking intrinsics.
15482 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15483 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15484 /// for a scalar instruction.
15485 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15486 SDValue PreservedSrc,
15487 const X86Subtarget *Subtarget,
15488 SelectionDAG &DAG) {
15489 if (isAllOnes(Mask))
15492 EVT VT = Op.getValueType();
15494 // The mask should be of type MVT::i1
15495 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15497 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15498 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15499 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15502 static int getSEHRegistrationNodeSize(const Function *Fn) {
15503 if (!Fn->hasPersonalityFn())
15504 report_fatal_error(
15505 "querying registration node size for function without personality");
15506 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15507 // WinEHStatePass for the full struct definition.
15508 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15509 case EHPersonality::MSVC_X86SEH: return 24;
15510 case EHPersonality::MSVC_CXX: return 16;
15513 report_fatal_error("can only recover FP for MSVC EH personality functions");
15516 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15517 /// function or when returning to a parent frame after catching an exception, we
15518 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15519 /// Here's the math:
15520 /// RegNodeBase = EntryEBP - RegNodeSize
15521 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15522 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15523 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15524 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15525 SDValue EntryEBP) {
15526 MachineFunction &MF = DAG.getMachineFunction();
15529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15530 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15532 // It's possible that the parent function no longer has a personality function
15533 // if the exceptional code was optimized away, in which case we just return
15534 // the incoming EBP.
15535 if (!Fn->hasPersonalityFn())
15538 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15540 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15542 MCSymbol *OffsetSym =
15543 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15544 GlobalValue::getRealLinkageName(Fn->getName()));
15545 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15546 SDValue RegNodeFrameOffset =
15547 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15549 // RegNodeBase = EntryEBP - RegNodeSize
15550 // ParentFP = RegNodeBase - RegNodeFrameOffset
15551 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15552 DAG.getConstant(RegNodeSize, dl, PtrVT));
15553 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15556 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15557 SelectionDAG &DAG) {
15559 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15560 EVT VT = Op.getValueType();
15561 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15563 switch(IntrData->Type) {
15564 case INTR_TYPE_1OP:
15565 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15566 case INTR_TYPE_2OP:
15567 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15569 case INTR_TYPE_3OP:
15570 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15571 Op.getOperand(2), Op.getOperand(3));
15572 case INTR_TYPE_4OP:
15573 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15574 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15575 case INTR_TYPE_1OP_MASK_RM: {
15576 SDValue Src = Op.getOperand(1);
15577 SDValue PassThru = Op.getOperand(2);
15578 SDValue Mask = Op.getOperand(3);
15579 SDValue RoundingMode;
15580 // We allways add rounding mode to the Node.
15581 // If the rounding mode is not specified, we add the
15582 // "current direction" mode.
15583 if (Op.getNumOperands() == 4)
15585 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15587 RoundingMode = Op.getOperand(4);
15588 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15589 if (IntrWithRoundingModeOpcode != 0)
15590 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15591 X86::STATIC_ROUNDING::CUR_DIRECTION)
15592 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15593 dl, Op.getValueType(), Src, RoundingMode),
15594 Mask, PassThru, Subtarget, DAG);
15595 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15597 Mask, PassThru, Subtarget, DAG);
15599 case INTR_TYPE_1OP_MASK: {
15600 SDValue Src = Op.getOperand(1);
15601 SDValue PassThru = Op.getOperand(2);
15602 SDValue Mask = Op.getOperand(3);
15603 // We add rounding mode to the Node when
15604 // - RM Opcode is specified and
15605 // - RM is not "current direction".
15606 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15607 if (IntrWithRoundingModeOpcode != 0) {
15608 SDValue Rnd = Op.getOperand(4);
15609 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15610 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15611 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15612 dl, Op.getValueType(),
15614 Mask, PassThru, Subtarget, DAG);
15617 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15618 Mask, PassThru, Subtarget, DAG);
15620 case INTR_TYPE_SCALAR_MASK_RM: {
15621 SDValue Src1 = Op.getOperand(1);
15622 SDValue Src2 = Op.getOperand(2);
15623 SDValue Src0 = Op.getOperand(3);
15624 SDValue Mask = Op.getOperand(4);
15625 // There are 2 kinds of intrinsics in this group:
15626 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15627 // (2) With rounding mode and sae - 7 operands.
15628 if (Op.getNumOperands() == 6) {
15629 SDValue Sae = Op.getOperand(5);
15630 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15631 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15633 Mask, Src0, Subtarget, DAG);
15635 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15636 SDValue RoundingMode = Op.getOperand(5);
15637 SDValue Sae = Op.getOperand(6);
15638 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15639 RoundingMode, Sae),
15640 Mask, Src0, Subtarget, DAG);
15642 case INTR_TYPE_2OP_MASK: {
15643 SDValue Src1 = Op.getOperand(1);
15644 SDValue Src2 = Op.getOperand(2);
15645 SDValue PassThru = Op.getOperand(3);
15646 SDValue Mask = Op.getOperand(4);
15647 // We specify 2 possible opcodes for intrinsics with rounding modes.
15648 // First, we check if the intrinsic may have non-default rounding mode,
15649 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15650 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15651 if (IntrWithRoundingModeOpcode != 0) {
15652 SDValue Rnd = Op.getOperand(5);
15653 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15654 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15655 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15656 dl, Op.getValueType(),
15658 Mask, PassThru, Subtarget, DAG);
15661 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15663 Mask, PassThru, Subtarget, DAG);
15665 case INTR_TYPE_2OP_MASK_RM: {
15666 SDValue Src1 = Op.getOperand(1);
15667 SDValue Src2 = Op.getOperand(2);
15668 SDValue PassThru = Op.getOperand(3);
15669 SDValue Mask = Op.getOperand(4);
15670 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15671 // First, we check if the intrinsic have rounding mode (6 operands),
15672 // if not, we set rounding mode to "current".
15674 if (Op.getNumOperands() == 6)
15675 Rnd = Op.getOperand(5);
15677 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15678 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15680 Mask, PassThru, Subtarget, DAG);
15682 case INTR_TYPE_3OP_MASK_RM: {
15683 SDValue Src1 = Op.getOperand(1);
15684 SDValue Src2 = Op.getOperand(2);
15685 SDValue Imm = Op.getOperand(3);
15686 SDValue PassThru = Op.getOperand(4);
15687 SDValue Mask = Op.getOperand(5);
15688 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15689 // First, we check if the intrinsic have rounding mode (7 operands),
15690 // if not, we set rounding mode to "current".
15692 if (Op.getNumOperands() == 7)
15693 Rnd = Op.getOperand(6);
15695 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15696 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15697 Src1, Src2, Imm, Rnd),
15698 Mask, PassThru, Subtarget, DAG);
15700 case INTR_TYPE_3OP_IMM8_MASK:
15701 case INTR_TYPE_3OP_MASK: {
15702 SDValue Src1 = Op.getOperand(1);
15703 SDValue Src2 = Op.getOperand(2);
15704 SDValue Src3 = Op.getOperand(3);
15705 SDValue PassThru = Op.getOperand(4);
15706 SDValue Mask = Op.getOperand(5);
15708 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15709 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15710 // We specify 2 possible opcodes for intrinsics with rounding modes.
15711 // First, we check if the intrinsic may have non-default rounding mode,
15712 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15713 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15714 if (IntrWithRoundingModeOpcode != 0) {
15715 SDValue Rnd = Op.getOperand(6);
15716 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15717 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15718 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15719 dl, Op.getValueType(),
15720 Src1, Src2, Src3, Rnd),
15721 Mask, PassThru, Subtarget, DAG);
15724 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15726 Mask, PassThru, Subtarget, DAG);
15728 case VPERM_3OP_MASKZ:
15729 case VPERM_3OP_MASK:
15732 case FMA_OP_MASK: {
15733 SDValue Src1 = Op.getOperand(1);
15734 SDValue Src2 = Op.getOperand(2);
15735 SDValue Src3 = Op.getOperand(3);
15736 SDValue Mask = Op.getOperand(4);
15737 EVT VT = Op.getValueType();
15738 SDValue PassThru = SDValue();
15740 // set PassThru element
15741 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15742 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15743 else if (IntrData->Type == FMA_OP_MASK3)
15748 // We specify 2 possible opcodes for intrinsics with rounding modes.
15749 // First, we check if the intrinsic may have non-default rounding mode,
15750 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15751 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15752 if (IntrWithRoundingModeOpcode != 0) {
15753 SDValue Rnd = Op.getOperand(5);
15754 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15755 X86::STATIC_ROUNDING::CUR_DIRECTION)
15756 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15757 dl, Op.getValueType(),
15758 Src1, Src2, Src3, Rnd),
15759 Mask, PassThru, Subtarget, DAG);
15761 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15762 dl, Op.getValueType(),
15764 Mask, PassThru, Subtarget, DAG);
15767 case CMP_MASK_CC: {
15768 // Comparison intrinsics with masks.
15769 // Example of transformation:
15770 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15771 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15773 // (v8i1 (insert_subvector undef,
15774 // (v2i1 (and (PCMPEQM %a, %b),
15775 // (extract_subvector
15776 // (v8i1 (bitcast %mask)), 0))), 0))))
15777 EVT VT = Op.getOperand(1).getValueType();
15778 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15779 VT.getVectorNumElements());
15780 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15781 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15782 Mask.getValueType().getSizeInBits());
15784 if (IntrData->Type == CMP_MASK_CC) {
15785 SDValue CC = Op.getOperand(3);
15786 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15787 // We specify 2 possible opcodes for intrinsics with rounding modes.
15788 // First, we check if the intrinsic may have non-default rounding mode,
15789 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15790 if (IntrData->Opc1 != 0) {
15791 SDValue Rnd = Op.getOperand(5);
15792 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15793 X86::STATIC_ROUNDING::CUR_DIRECTION)
15794 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15795 Op.getOperand(2), CC, Rnd);
15797 //default rounding mode
15799 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15800 Op.getOperand(2), CC);
15803 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15804 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15807 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15808 DAG.getTargetConstant(0, dl,
15811 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15812 DAG.getUNDEF(BitcastVT), CmpMask,
15813 DAG.getIntPtrConstant(0, dl));
15814 return DAG.getBitcast(Op.getValueType(), Res);
15816 case COMI: { // Comparison intrinsics
15817 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15818 SDValue LHS = Op.getOperand(1);
15819 SDValue RHS = Op.getOperand(2);
15820 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15821 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15822 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15823 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15824 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15825 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15828 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15829 Op.getOperand(1), Op.getOperand(2), DAG);
15831 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15832 Op.getSimpleValueType(),
15834 Op.getOperand(2), DAG),
15835 Op.getOperand(4), Op.getOperand(3), Subtarget,
15837 case COMPRESS_EXPAND_IN_REG: {
15838 SDValue Mask = Op.getOperand(3);
15839 SDValue DataToCompress = Op.getOperand(1);
15840 SDValue PassThru = Op.getOperand(2);
15841 if (isAllOnes(Mask)) // return data as is
15842 return Op.getOperand(1);
15844 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15846 Mask, PassThru, Subtarget, DAG);
15849 SDValue Mask = Op.getOperand(3);
15850 EVT VT = Op.getValueType();
15851 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15852 VT.getVectorNumElements());
15853 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15854 Mask.getValueType().getSizeInBits());
15856 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15857 DAG.getBitcast(BitcastVT, Mask),
15858 DAG.getIntPtrConstant(0, dl));
15859 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15868 default: return SDValue(); // Don't custom lower most intrinsics.
15870 case Intrinsic::x86_avx2_permd:
15871 case Intrinsic::x86_avx2_permps:
15872 // Operands intentionally swapped. Mask is last operand to intrinsic,
15873 // but second operand for node/instruction.
15874 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15875 Op.getOperand(2), Op.getOperand(1));
15877 // ptest and testp intrinsics. The intrinsic these come from are designed to
15878 // return an integer value, not just an instruction so lower it to the ptest
15879 // or testp pattern and a setcc for the result.
15880 case Intrinsic::x86_sse41_ptestz:
15881 case Intrinsic::x86_sse41_ptestc:
15882 case Intrinsic::x86_sse41_ptestnzc:
15883 case Intrinsic::x86_avx_ptestz_256:
15884 case Intrinsic::x86_avx_ptestc_256:
15885 case Intrinsic::x86_avx_ptestnzc_256:
15886 case Intrinsic::x86_avx_vtestz_ps:
15887 case Intrinsic::x86_avx_vtestc_ps:
15888 case Intrinsic::x86_avx_vtestnzc_ps:
15889 case Intrinsic::x86_avx_vtestz_pd:
15890 case Intrinsic::x86_avx_vtestc_pd:
15891 case Intrinsic::x86_avx_vtestnzc_pd:
15892 case Intrinsic::x86_avx_vtestz_ps_256:
15893 case Intrinsic::x86_avx_vtestc_ps_256:
15894 case Intrinsic::x86_avx_vtestnzc_ps_256:
15895 case Intrinsic::x86_avx_vtestz_pd_256:
15896 case Intrinsic::x86_avx_vtestc_pd_256:
15897 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15898 bool IsTestPacked = false;
15901 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15902 case Intrinsic::x86_avx_vtestz_ps:
15903 case Intrinsic::x86_avx_vtestz_pd:
15904 case Intrinsic::x86_avx_vtestz_ps_256:
15905 case Intrinsic::x86_avx_vtestz_pd_256:
15906 IsTestPacked = true; // Fallthrough
15907 case Intrinsic::x86_sse41_ptestz:
15908 case Intrinsic::x86_avx_ptestz_256:
15910 X86CC = X86::COND_E;
15912 case Intrinsic::x86_avx_vtestc_ps:
15913 case Intrinsic::x86_avx_vtestc_pd:
15914 case Intrinsic::x86_avx_vtestc_ps_256:
15915 case Intrinsic::x86_avx_vtestc_pd_256:
15916 IsTestPacked = true; // Fallthrough
15917 case Intrinsic::x86_sse41_ptestc:
15918 case Intrinsic::x86_avx_ptestc_256:
15920 X86CC = X86::COND_B;
15922 case Intrinsic::x86_avx_vtestnzc_ps:
15923 case Intrinsic::x86_avx_vtestnzc_pd:
15924 case Intrinsic::x86_avx_vtestnzc_ps_256:
15925 case Intrinsic::x86_avx_vtestnzc_pd_256:
15926 IsTestPacked = true; // Fallthrough
15927 case Intrinsic::x86_sse41_ptestnzc:
15928 case Intrinsic::x86_avx_ptestnzc_256:
15930 X86CC = X86::COND_A;
15934 SDValue LHS = Op.getOperand(1);
15935 SDValue RHS = Op.getOperand(2);
15936 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15937 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15938 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15939 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15940 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15942 case Intrinsic::x86_avx512_kortestz_w:
15943 case Intrinsic::x86_avx512_kortestc_w: {
15944 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15945 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15946 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15947 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15948 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15949 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15950 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15953 case Intrinsic::x86_sse42_pcmpistria128:
15954 case Intrinsic::x86_sse42_pcmpestria128:
15955 case Intrinsic::x86_sse42_pcmpistric128:
15956 case Intrinsic::x86_sse42_pcmpestric128:
15957 case Intrinsic::x86_sse42_pcmpistrio128:
15958 case Intrinsic::x86_sse42_pcmpestrio128:
15959 case Intrinsic::x86_sse42_pcmpistris128:
15960 case Intrinsic::x86_sse42_pcmpestris128:
15961 case Intrinsic::x86_sse42_pcmpistriz128:
15962 case Intrinsic::x86_sse42_pcmpestriz128: {
15966 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15967 case Intrinsic::x86_sse42_pcmpistria128:
15968 Opcode = X86ISD::PCMPISTRI;
15969 X86CC = X86::COND_A;
15971 case Intrinsic::x86_sse42_pcmpestria128:
15972 Opcode = X86ISD::PCMPESTRI;
15973 X86CC = X86::COND_A;
15975 case Intrinsic::x86_sse42_pcmpistric128:
15976 Opcode = X86ISD::PCMPISTRI;
15977 X86CC = X86::COND_B;
15979 case Intrinsic::x86_sse42_pcmpestric128:
15980 Opcode = X86ISD::PCMPESTRI;
15981 X86CC = X86::COND_B;
15983 case Intrinsic::x86_sse42_pcmpistrio128:
15984 Opcode = X86ISD::PCMPISTRI;
15985 X86CC = X86::COND_O;
15987 case Intrinsic::x86_sse42_pcmpestrio128:
15988 Opcode = X86ISD::PCMPESTRI;
15989 X86CC = X86::COND_O;
15991 case Intrinsic::x86_sse42_pcmpistris128:
15992 Opcode = X86ISD::PCMPISTRI;
15993 X86CC = X86::COND_S;
15995 case Intrinsic::x86_sse42_pcmpestris128:
15996 Opcode = X86ISD::PCMPESTRI;
15997 X86CC = X86::COND_S;
15999 case Intrinsic::x86_sse42_pcmpistriz128:
16000 Opcode = X86ISD::PCMPISTRI;
16001 X86CC = X86::COND_E;
16003 case Intrinsic::x86_sse42_pcmpestriz128:
16004 Opcode = X86ISD::PCMPESTRI;
16005 X86CC = X86::COND_E;
16008 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16009 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16010 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16011 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16012 DAG.getConstant(X86CC, dl, MVT::i8),
16013 SDValue(PCMP.getNode(), 1));
16014 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16017 case Intrinsic::x86_sse42_pcmpistri128:
16018 case Intrinsic::x86_sse42_pcmpestri128: {
16020 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16021 Opcode = X86ISD::PCMPISTRI;
16023 Opcode = X86ISD::PCMPESTRI;
16025 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16026 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16027 return DAG.getNode(Opcode, dl, VTs, NewOps);
16030 case Intrinsic::x86_seh_lsda: {
16031 // Compute the symbol for the LSDA. We know it'll get emitted later.
16032 MachineFunction &MF = DAG.getMachineFunction();
16033 SDValue Op1 = Op.getOperand(1);
16034 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16035 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16036 GlobalValue::getRealLinkageName(Fn->getName()));
16038 // Generate a simple absolute symbol reference. This intrinsic is only
16039 // supported on 32-bit Windows, which isn't PIC.
16040 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16041 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16044 case Intrinsic::x86_seh_recoverfp: {
16045 SDValue FnOp = Op.getOperand(1);
16046 SDValue IncomingFPOp = Op.getOperand(2);
16047 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16048 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16050 report_fatal_error(
16051 "llvm.x86.seh.recoverfp must take a function as the first argument");
16052 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16055 case Intrinsic::localaddress: {
16056 // Returns one of the stack, base, or frame pointer registers, depending on
16057 // which is used to reference local variables.
16058 MachineFunction &MF = DAG.getMachineFunction();
16059 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16061 if (RegInfo->hasBasePointer(MF))
16062 Reg = RegInfo->getBaseRegister();
16063 else // This function handles the SP or FP case.
16064 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16065 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16070 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16071 SDValue Src, SDValue Mask, SDValue Base,
16072 SDValue Index, SDValue ScaleOp, SDValue Chain,
16073 const X86Subtarget * Subtarget) {
16075 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16077 llvm_unreachable("Invalid scale type");
16078 unsigned ScaleVal = C->getZExtValue();
16079 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16080 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16082 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16083 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16084 Index.getSimpleValueType().getVectorNumElements());
16086 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16088 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16090 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16091 Mask.getValueType().getSizeInBits());
16093 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16094 // are extracted by EXTRACT_SUBVECTOR.
16095 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16096 DAG.getBitcast(BitcastVT, Mask),
16097 DAG.getIntPtrConstant(0, dl));
16099 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16100 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16101 SDValue Segment = DAG.getRegister(0, MVT::i32);
16102 if (Src.getOpcode() == ISD::UNDEF)
16103 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16104 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16105 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16106 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16107 return DAG.getMergeValues(RetOps, dl);
16110 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16111 SDValue Src, SDValue Mask, SDValue Base,
16112 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16116 llvm_unreachable("Invalid scale type");
16117 unsigned ScaleVal = C->getZExtValue();
16118 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16119 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16121 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16122 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16123 SDValue Segment = DAG.getRegister(0, MVT::i32);
16124 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16125 Index.getSimpleValueType().getVectorNumElements());
16127 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16129 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16131 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16132 Mask.getValueType().getSizeInBits());
16134 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16135 // are extracted by EXTRACT_SUBVECTOR.
16136 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16137 DAG.getBitcast(BitcastVT, Mask),
16138 DAG.getIntPtrConstant(0, dl));
16140 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16141 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16142 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16143 return SDValue(Res, 1);
16146 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16147 SDValue Mask, SDValue Base, SDValue Index,
16148 SDValue ScaleOp, SDValue Chain) {
16150 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16151 assert(C && "Invalid scale type");
16152 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16153 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16154 SDValue Segment = DAG.getRegister(0, MVT::i32);
16156 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16158 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16160 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16162 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16163 //SDVTList VTs = DAG.getVTList(MVT::Other);
16164 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16165 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16166 return SDValue(Res, 0);
16169 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16170 // read performance monitor counters (x86_rdpmc).
16171 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16172 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16173 SmallVectorImpl<SDValue> &Results) {
16174 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16175 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16178 // The ECX register is used to select the index of the performance counter
16180 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16182 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16184 // Reads the content of a 64-bit performance counter and returns it in the
16185 // registers EDX:EAX.
16186 if (Subtarget->is64Bit()) {
16187 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16188 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16191 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16192 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16195 Chain = HI.getValue(1);
16197 if (Subtarget->is64Bit()) {
16198 // The EAX register is loaded with the low-order 32 bits. The EDX register
16199 // is loaded with the supported high-order bits of the counter.
16200 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16201 DAG.getConstant(32, DL, MVT::i8));
16202 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16203 Results.push_back(Chain);
16207 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16208 SDValue Ops[] = { LO, HI };
16209 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16210 Results.push_back(Pair);
16211 Results.push_back(Chain);
16214 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16215 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16216 // also used to custom lower READCYCLECOUNTER nodes.
16217 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16218 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16219 SmallVectorImpl<SDValue> &Results) {
16220 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16221 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16224 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16225 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16226 // and the EAX register is loaded with the low-order 32 bits.
16227 if (Subtarget->is64Bit()) {
16228 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16229 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16232 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16233 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16236 SDValue Chain = HI.getValue(1);
16238 if (Opcode == X86ISD::RDTSCP_DAG) {
16239 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16241 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16242 // the ECX register. Add 'ecx' explicitly to the chain.
16243 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16245 // Explicitly store the content of ECX at the location passed in input
16246 // to the 'rdtscp' intrinsic.
16247 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16248 MachinePointerInfo(), false, false, 0);
16251 if (Subtarget->is64Bit()) {
16252 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16253 // the EAX register is loaded with the low-order 32 bits.
16254 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16255 DAG.getConstant(32, DL, MVT::i8));
16256 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16257 Results.push_back(Chain);
16261 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16262 SDValue Ops[] = { LO, HI };
16263 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16264 Results.push_back(Pair);
16265 Results.push_back(Chain);
16268 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16269 SelectionDAG &DAG) {
16270 SmallVector<SDValue, 2> Results;
16272 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16274 return DAG.getMergeValues(Results, DL);
16277 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16278 SelectionDAG &DAG) {
16279 MachineFunction &MF = DAG.getMachineFunction();
16280 const Function *Fn = MF.getFunction();
16282 SDValue Chain = Op.getOperand(0);
16284 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16285 "using llvm.x86.seh.restoreframe requires a frame pointer");
16287 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16288 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16290 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16291 unsigned FrameReg =
16292 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16293 unsigned SPReg = RegInfo->getStackRegister();
16294 unsigned SlotSize = RegInfo->getSlotSize();
16296 // Get incoming EBP.
16297 SDValue IncomingEBP =
16298 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16300 // SP is saved in the first field of every registration node, so load
16301 // [EBP-RegNodeSize] into SP.
16302 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16303 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16304 DAG.getConstant(-RegNodeSize, dl, VT));
16306 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16307 false, VT.getScalarSizeInBits() / 8);
16308 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16310 if (!RegInfo->needsStackRealignment(MF)) {
16311 // Adjust EBP to point back to the original frame position.
16312 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16313 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16315 assert(RegInfo->hasBasePointer(MF) &&
16316 "functions with Win32 EH must use frame or base pointer register");
16318 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16319 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16320 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16322 // Reload the spilled EBP value, now that the stack and base pointers are
16324 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16325 X86FI->setHasSEHFramePtrSave(true);
16326 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16327 X86FI->setSEHFramePtrSaveIndex(FI);
16328 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16329 MachinePointerInfo(), false, false, false,
16330 VT.getScalarSizeInBits() / 8);
16331 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16337 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16338 /// return truncate Store/MaskedStore Node
16339 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16343 SDValue Mask = Op.getOperand(4);
16344 SDValue DataToTruncate = Op.getOperand(3);
16345 SDValue Addr = Op.getOperand(2);
16346 SDValue Chain = Op.getOperand(0);
16348 EVT VT = DataToTruncate.getValueType();
16349 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16350 ElementType, VT.getVectorNumElements());
16352 if (isAllOnes(Mask)) // return just a truncate store
16353 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16354 MachinePointerInfo(), SVT, false, false,
16355 SVT.getScalarSizeInBits()/8);
16357 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16358 MVT::i1, VT.getVectorNumElements());
16359 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16360 Mask.getValueType().getSizeInBits());
16361 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16362 // are extracted by EXTRACT_SUBVECTOR.
16363 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16364 DAG.getBitcast(BitcastVT, Mask),
16365 DAG.getIntPtrConstant(0, dl));
16367 MachineMemOperand *MMO = DAG.getMachineFunction().
16368 getMachineMemOperand(MachinePointerInfo(),
16369 MachineMemOperand::MOStore, SVT.getStoreSize(),
16370 SVT.getScalarSizeInBits()/8);
16372 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16373 VMask, SVT, MMO, true);
16376 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16377 SelectionDAG &DAG) {
16378 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16380 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16382 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16383 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16388 switch(IntrData->Type) {
16390 llvm_unreachable("Unknown Intrinsic Type");
16394 // Emit the node with the right value type.
16395 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16396 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16398 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16399 // Otherwise return the value from Rand, which is always 0, casted to i32.
16400 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16401 DAG.getConstant(1, dl, Op->getValueType(1)),
16402 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16403 SDValue(Result.getNode(), 1) };
16404 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16405 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16408 // Return { result, isValid, chain }.
16409 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16410 SDValue(Result.getNode(), 2));
16413 //gather(v1, mask, index, base, scale);
16414 SDValue Chain = Op.getOperand(0);
16415 SDValue Src = Op.getOperand(2);
16416 SDValue Base = Op.getOperand(3);
16417 SDValue Index = Op.getOperand(4);
16418 SDValue Mask = Op.getOperand(5);
16419 SDValue Scale = Op.getOperand(6);
16420 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16424 //scatter(base, mask, index, v1, scale);
16425 SDValue Chain = Op.getOperand(0);
16426 SDValue Base = Op.getOperand(2);
16427 SDValue Mask = Op.getOperand(3);
16428 SDValue Index = Op.getOperand(4);
16429 SDValue Src = Op.getOperand(5);
16430 SDValue Scale = Op.getOperand(6);
16431 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16435 SDValue Hint = Op.getOperand(6);
16436 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16437 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16438 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16439 SDValue Chain = Op.getOperand(0);
16440 SDValue Mask = Op.getOperand(2);
16441 SDValue Index = Op.getOperand(3);
16442 SDValue Base = Op.getOperand(4);
16443 SDValue Scale = Op.getOperand(5);
16444 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16446 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16448 SmallVector<SDValue, 2> Results;
16449 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16451 return DAG.getMergeValues(Results, dl);
16453 // Read Performance Monitoring Counters.
16455 SmallVector<SDValue, 2> Results;
16456 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16457 return DAG.getMergeValues(Results, dl);
16459 // XTEST intrinsics.
16461 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16462 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16463 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16464 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16466 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16467 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16468 Ret, SDValue(InTrans.getNode(), 1));
16472 SmallVector<SDValue, 2> Results;
16473 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16474 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16475 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16476 DAG.getConstant(-1, dl, MVT::i8));
16477 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16478 Op.getOperand(4), GenCF.getValue(1));
16479 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16480 Op.getOperand(5), MachinePointerInfo(),
16482 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16483 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16485 Results.push_back(SetCC);
16486 Results.push_back(Store);
16487 return DAG.getMergeValues(Results, dl);
16489 case COMPRESS_TO_MEM: {
16491 SDValue Mask = Op.getOperand(4);
16492 SDValue DataToCompress = Op.getOperand(3);
16493 SDValue Addr = Op.getOperand(2);
16494 SDValue Chain = Op.getOperand(0);
16496 EVT VT = DataToCompress.getValueType();
16497 if (isAllOnes(Mask)) // return just a store
16498 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16499 MachinePointerInfo(), false, false,
16500 VT.getScalarSizeInBits()/8);
16502 SDValue Compressed =
16503 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16504 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16505 return DAG.getStore(Chain, dl, Compressed, Addr,
16506 MachinePointerInfo(), false, false,
16507 VT.getScalarSizeInBits()/8);
16509 case TRUNCATE_TO_MEM_VI8:
16510 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16511 case TRUNCATE_TO_MEM_VI16:
16512 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16513 case TRUNCATE_TO_MEM_VI32:
16514 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16515 case EXPAND_FROM_MEM: {
16517 SDValue Mask = Op.getOperand(4);
16518 SDValue PassThru = Op.getOperand(3);
16519 SDValue Addr = Op.getOperand(2);
16520 SDValue Chain = Op.getOperand(0);
16521 EVT VT = Op.getValueType();
16523 if (isAllOnes(Mask)) // return just a load
16524 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16525 false, VT.getScalarSizeInBits()/8);
16527 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16528 false, false, false,
16529 VT.getScalarSizeInBits()/8);
16531 SDValue Results[] = {
16532 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16533 Mask, PassThru, Subtarget, DAG), Chain};
16534 return DAG.getMergeValues(Results, dl);
16539 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16540 SelectionDAG &DAG) const {
16541 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16542 MFI->setReturnAddressIsTaken(true);
16544 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16547 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16552 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16553 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16554 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16555 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16556 DAG.getNode(ISD::ADD, dl, PtrVT,
16557 FrameAddr, Offset),
16558 MachinePointerInfo(), false, false, false, 0);
16561 // Just load the return address.
16562 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16563 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16564 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16567 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16568 MachineFunction &MF = DAG.getMachineFunction();
16569 MachineFrameInfo *MFI = MF.getFrameInfo();
16570 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16571 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16572 EVT VT = Op.getValueType();
16574 MFI->setFrameAddressIsTaken(true);
16576 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16577 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16578 // is not possible to crawl up the stack without looking at the unwind codes
16580 int FrameAddrIndex = FuncInfo->getFAIndex();
16581 if (!FrameAddrIndex) {
16582 // Set up a frame object for the return address.
16583 unsigned SlotSize = RegInfo->getSlotSize();
16584 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16585 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16586 FuncInfo->setFAIndex(FrameAddrIndex);
16588 return DAG.getFrameIndex(FrameAddrIndex, VT);
16591 unsigned FrameReg =
16592 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16593 SDLoc dl(Op); // FIXME probably not meaningful
16594 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16595 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16596 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16597 "Invalid Frame Register!");
16598 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16600 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16601 MachinePointerInfo(),
16602 false, false, false, 0);
16606 // FIXME? Maybe this could be a TableGen attribute on some registers and
16607 // this table could be generated automatically from RegInfo.
16608 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16609 SelectionDAG &DAG) const {
16610 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16611 const MachineFunction &MF = DAG.getMachineFunction();
16613 unsigned Reg = StringSwitch<unsigned>(RegName)
16614 .Case("esp", X86::ESP)
16615 .Case("rsp", X86::RSP)
16616 .Case("ebp", X86::EBP)
16617 .Case("rbp", X86::RBP)
16620 if (Reg == X86::EBP || Reg == X86::RBP) {
16621 if (!TFI.hasFP(MF))
16622 report_fatal_error("register " + StringRef(RegName) +
16623 " is allocatable: function has no frame pointer");
16626 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16627 unsigned FrameReg =
16628 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16629 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16630 "Invalid Frame Register!");
16638 report_fatal_error("Invalid register name global variable");
16641 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16642 SelectionDAG &DAG) const {
16643 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16644 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16647 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16648 SDValue Chain = Op.getOperand(0);
16649 SDValue Offset = Op.getOperand(1);
16650 SDValue Handler = Op.getOperand(2);
16653 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16654 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16655 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16656 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16657 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16658 "Invalid Frame Register!");
16659 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16660 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16662 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16663 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16665 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16666 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16668 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16670 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16671 DAG.getRegister(StoreAddrReg, PtrVT));
16674 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16675 SDValue Chain = Op.getOperand(0);
16676 SDValue Dest = Op.getOperand(1);
16679 MVT PtrVT = getPointerTy(DAG.getDataLayout());
16680 unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16682 // Load the address of the destination block.
16683 MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16684 SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16685 unsigned WrapperKind =
16686 Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16687 SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16688 Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16689 return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16690 DAG.getRegister(ReturnReg, PtrVT));
16693 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16694 SelectionDAG &DAG) const {
16696 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16697 DAG.getVTList(MVT::i32, MVT::Other),
16698 Op.getOperand(0), Op.getOperand(1));
16701 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16702 SelectionDAG &DAG) const {
16704 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16705 Op.getOperand(0), Op.getOperand(1));
16708 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16709 return Op.getOperand(0);
16712 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16713 SelectionDAG &DAG) const {
16714 SDValue Root = Op.getOperand(0);
16715 SDValue Trmp = Op.getOperand(1); // trampoline
16716 SDValue FPtr = Op.getOperand(2); // nested function
16717 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16720 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16721 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16723 if (Subtarget->is64Bit()) {
16724 SDValue OutChains[6];
16726 // Large code-model.
16727 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16728 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16730 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16731 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16733 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16735 // Load the pointer to the nested function into R11.
16736 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16737 SDValue Addr = Trmp;
16738 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16739 Addr, MachinePointerInfo(TrmpAddr),
16742 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16743 DAG.getConstant(2, dl, MVT::i64));
16744 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16745 MachinePointerInfo(TrmpAddr, 2),
16748 // Load the 'nest' parameter value into R10.
16749 // R10 is specified in X86CallingConv.td
16750 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16751 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16752 DAG.getConstant(10, dl, MVT::i64));
16753 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16754 Addr, MachinePointerInfo(TrmpAddr, 10),
16757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16758 DAG.getConstant(12, dl, MVT::i64));
16759 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16760 MachinePointerInfo(TrmpAddr, 12),
16763 // Jump to the nested function.
16764 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16765 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16766 DAG.getConstant(20, dl, MVT::i64));
16767 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16768 Addr, MachinePointerInfo(TrmpAddr, 20),
16771 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16772 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16773 DAG.getConstant(22, dl, MVT::i64));
16774 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16775 Addr, MachinePointerInfo(TrmpAddr, 22),
16778 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16780 const Function *Func =
16781 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16782 CallingConv::ID CC = Func->getCallingConv();
16787 llvm_unreachable("Unsupported calling convention");
16788 case CallingConv::C:
16789 case CallingConv::X86_StdCall: {
16790 // Pass 'nest' parameter in ECX.
16791 // Must be kept in sync with X86CallingConv.td
16792 NestReg = X86::ECX;
16794 // Check that ECX wasn't needed by an 'inreg' parameter.
16795 FunctionType *FTy = Func->getFunctionType();
16796 const AttributeSet &Attrs = Func->getAttributes();
16798 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16799 unsigned InRegCount = 0;
16802 for (FunctionType::param_iterator I = FTy->param_begin(),
16803 E = FTy->param_end(); I != E; ++I, ++Idx)
16804 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16805 auto &DL = DAG.getDataLayout();
16806 // FIXME: should only count parameters that are lowered to integers.
16807 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16810 if (InRegCount > 2) {
16811 report_fatal_error("Nest register in use - reduce number of inreg"
16817 case CallingConv::X86_FastCall:
16818 case CallingConv::X86_ThisCall:
16819 case CallingConv::Fast:
16820 // Pass 'nest' parameter in EAX.
16821 // Must be kept in sync with X86CallingConv.td
16822 NestReg = X86::EAX;
16826 SDValue OutChains[4];
16827 SDValue Addr, Disp;
16829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16830 DAG.getConstant(10, dl, MVT::i32));
16831 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16833 // This is storing the opcode for MOV32ri.
16834 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16835 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16836 OutChains[0] = DAG.getStore(Root, dl,
16837 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16838 Trmp, MachinePointerInfo(TrmpAddr),
16841 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16842 DAG.getConstant(1, dl, MVT::i32));
16843 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16844 MachinePointerInfo(TrmpAddr, 1),
16847 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16848 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16849 DAG.getConstant(5, dl, MVT::i32));
16850 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16851 Addr, MachinePointerInfo(TrmpAddr, 5),
16854 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16855 DAG.getConstant(6, dl, MVT::i32));
16856 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16857 MachinePointerInfo(TrmpAddr, 6),
16860 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16864 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16865 SelectionDAG &DAG) const {
16867 The rounding mode is in bits 11:10 of FPSR, and has the following
16869 00 Round to nearest
16874 FLT_ROUNDS, on the other hand, expects the following:
16881 To perform the conversion, we do:
16882 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16885 MachineFunction &MF = DAG.getMachineFunction();
16886 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16887 unsigned StackAlignment = TFI.getStackAlignment();
16888 MVT VT = Op.getSimpleValueType();
16891 // Save FP Control Word to stack slot
16892 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16893 SDValue StackSlot =
16894 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16896 MachineMemOperand *MMO =
16897 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16898 MachineMemOperand::MOStore, 2, 2);
16900 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16901 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16902 DAG.getVTList(MVT::Other),
16903 Ops, MVT::i16, MMO);
16905 // Load FP Control Word from stack slot
16906 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16907 MachinePointerInfo(), false, false, false, 0);
16909 // Transform as necessary
16911 DAG.getNode(ISD::SRL, DL, MVT::i16,
16912 DAG.getNode(ISD::AND, DL, MVT::i16,
16913 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16914 DAG.getConstant(11, DL, MVT::i8));
16916 DAG.getNode(ISD::SRL, DL, MVT::i16,
16917 DAG.getNode(ISD::AND, DL, MVT::i16,
16918 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16919 DAG.getConstant(9, DL, MVT::i8));
16922 DAG.getNode(ISD::AND, DL, MVT::i16,
16923 DAG.getNode(ISD::ADD, DL, MVT::i16,
16924 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16925 DAG.getConstant(1, DL, MVT::i16)),
16926 DAG.getConstant(3, DL, MVT::i16));
16928 return DAG.getNode((VT.getSizeInBits() < 16 ?
16929 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16932 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16933 MVT VT = Op.getSimpleValueType();
16935 unsigned NumBits = VT.getSizeInBits();
16938 Op = Op.getOperand(0);
16939 if (VT == MVT::i8) {
16940 // Zero extend to i32 since there is not an i8 bsr.
16942 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16945 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16946 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16947 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16949 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16952 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16953 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16956 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16958 // Finally xor with NumBits-1.
16959 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16960 DAG.getConstant(NumBits - 1, dl, OpVT));
16963 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16967 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16968 MVT VT = Op.getSimpleValueType();
16970 unsigned NumBits = VT.getSizeInBits();
16973 Op = Op.getOperand(0);
16974 if (VT == MVT::i8) {
16975 // Zero extend to i32 since there is not an i8 bsr.
16977 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16980 // Issue a bsr (scan bits in reverse).
16981 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16982 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16984 // And xor with NumBits-1.
16985 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16986 DAG.getConstant(NumBits - 1, dl, OpVT));
16989 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16993 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16994 MVT VT = Op.getSimpleValueType();
16995 unsigned NumBits = VT.getSizeInBits();
16997 Op = Op.getOperand(0);
16999 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17000 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17001 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17003 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17006 DAG.getConstant(NumBits, dl, VT),
17007 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17010 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17013 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17014 // ones, and then concatenate the result back.
17015 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17016 MVT VT = Op.getSimpleValueType();
17018 assert(VT.is256BitVector() && VT.isInteger() &&
17019 "Unsupported value type for operation");
17021 unsigned NumElems = VT.getVectorNumElements();
17024 // Extract the LHS vectors
17025 SDValue LHS = Op.getOperand(0);
17026 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17027 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17029 // Extract the RHS vectors
17030 SDValue RHS = Op.getOperand(1);
17031 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17032 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17034 MVT EltVT = VT.getVectorElementType();
17035 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17037 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17038 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17039 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17042 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17043 if (Op.getValueType() == MVT::i1)
17044 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17045 Op.getOperand(0), Op.getOperand(1));
17046 assert(Op.getSimpleValueType().is256BitVector() &&
17047 Op.getSimpleValueType().isInteger() &&
17048 "Only handle AVX 256-bit vector integer operation");
17049 return Lower256IntArith(Op, DAG);
17052 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17053 if (Op.getValueType() == MVT::i1)
17054 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17055 Op.getOperand(0), Op.getOperand(1));
17056 assert(Op.getSimpleValueType().is256BitVector() &&
17057 Op.getSimpleValueType().isInteger() &&
17058 "Only handle AVX 256-bit vector integer operation");
17059 return Lower256IntArith(Op, DAG);
17062 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17063 assert(Op.getSimpleValueType().is256BitVector() &&
17064 Op.getSimpleValueType().isInteger() &&
17065 "Only handle AVX 256-bit vector integer operation");
17066 return Lower256IntArith(Op, DAG);
17069 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17070 SelectionDAG &DAG) {
17072 MVT VT = Op.getSimpleValueType();
17075 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17077 // Decompose 256-bit ops into smaller 128-bit ops.
17078 if (VT.is256BitVector() && !Subtarget->hasInt256())
17079 return Lower256IntArith(Op, DAG);
17081 SDValue A = Op.getOperand(0);
17082 SDValue B = Op.getOperand(1);
17084 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17085 // pairs, multiply and truncate.
17086 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17087 if (Subtarget->hasInt256()) {
17088 if (VT == MVT::v32i8) {
17089 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17090 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17091 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17092 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17093 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17094 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17095 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17096 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17097 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17098 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17101 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17102 return DAG.getNode(
17103 ISD::TRUNCATE, dl, VT,
17104 DAG.getNode(ISD::MUL, dl, ExVT,
17105 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17106 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17109 assert(VT == MVT::v16i8 &&
17110 "Pre-AVX2 support only supports v16i8 multiplication");
17111 MVT ExVT = MVT::v8i16;
17113 // Extract the lo parts and sign extend to i16
17115 if (Subtarget->hasSSE41()) {
17116 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17117 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17119 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17120 -1, 4, -1, 5, -1, 6, -1, 7};
17121 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17122 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17123 ALo = DAG.getBitcast(ExVT, ALo);
17124 BLo = DAG.getBitcast(ExVT, BLo);
17125 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17126 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17129 // Extract the hi parts and sign extend to i16
17131 if (Subtarget->hasSSE41()) {
17132 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17133 -1, -1, -1, -1, -1, -1, -1, -1};
17134 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17135 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17136 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17137 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17139 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17140 -1, 12, -1, 13, -1, 14, -1, 15};
17141 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17142 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17143 AHi = DAG.getBitcast(ExVT, AHi);
17144 BHi = DAG.getBitcast(ExVT, BHi);
17145 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17146 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17149 // Multiply, mask the lower 8bits of the lo/hi results and pack
17150 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17151 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17152 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17153 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17154 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17157 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17158 if (VT == MVT::v4i32) {
17159 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17160 "Should not custom lower when pmuldq is available!");
17162 // Extract the odd parts.
17163 static const int UnpackMask[] = { 1, -1, 3, -1 };
17164 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17165 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17167 // Multiply the even parts.
17168 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17169 // Now multiply odd parts.
17170 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17172 Evens = DAG.getBitcast(VT, Evens);
17173 Odds = DAG.getBitcast(VT, Odds);
17175 // Merge the two vectors back together with a shuffle. This expands into 2
17177 static const int ShufMask[] = { 0, 4, 2, 6 };
17178 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17181 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17182 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17184 // Ahi = psrlqi(a, 32);
17185 // Bhi = psrlqi(b, 32);
17187 // AloBlo = pmuludq(a, b);
17188 // AloBhi = pmuludq(a, Bhi);
17189 // AhiBlo = pmuludq(Ahi, b);
17191 // AloBhi = psllqi(AloBhi, 32);
17192 // AhiBlo = psllqi(AhiBlo, 32);
17193 // return AloBlo + AloBhi + AhiBlo;
17195 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17196 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17198 SDValue AhiBlo = Ahi;
17199 SDValue AloBhi = Bhi;
17200 // Bit cast to 32-bit vectors for MULUDQ
17201 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17202 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17203 A = DAG.getBitcast(MulVT, A);
17204 B = DAG.getBitcast(MulVT, B);
17205 Ahi = DAG.getBitcast(MulVT, Ahi);
17206 Bhi = DAG.getBitcast(MulVT, Bhi);
17208 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17209 // After shifting right const values the result may be all-zero.
17210 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17211 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17212 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17214 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17215 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17216 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17219 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17220 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17223 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17224 assert(Subtarget->isTargetWin64() && "Unexpected target");
17225 EVT VT = Op.getValueType();
17226 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17227 "Unexpected return type for lowering");
17231 switch (Op->getOpcode()) {
17232 default: llvm_unreachable("Unexpected request for libcall!");
17233 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17234 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17235 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17236 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17237 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17238 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17242 SDValue InChain = DAG.getEntryNode();
17244 TargetLowering::ArgListTy Args;
17245 TargetLowering::ArgListEntry Entry;
17246 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17247 EVT ArgVT = Op->getOperand(i).getValueType();
17248 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17249 "Unexpected argument type for lowering");
17250 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17251 Entry.Node = StackPtr;
17252 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17254 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17255 Entry.Ty = PointerType::get(ArgTy,0);
17256 Entry.isSExt = false;
17257 Entry.isZExt = false;
17258 Args.push_back(Entry);
17261 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17262 getPointerTy(DAG.getDataLayout()));
17264 TargetLowering::CallLoweringInfo CLI(DAG);
17265 CLI.setDebugLoc(dl).setChain(InChain)
17266 .setCallee(getLibcallCallingConv(LC),
17267 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17268 Callee, std::move(Args), 0)
17269 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17271 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17272 return DAG.getBitcast(VT, CallInfo.first);
17275 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17276 SelectionDAG &DAG) {
17277 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17278 EVT VT = Op0.getValueType();
17281 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17282 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17284 // PMULxD operations multiply each even value (starting at 0) of LHS with
17285 // the related value of RHS and produce a widen result.
17286 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17287 // => <2 x i64> <ae|cg>
17289 // In other word, to have all the results, we need to perform two PMULxD:
17290 // 1. one with the even values.
17291 // 2. one with the odd values.
17292 // To achieve #2, with need to place the odd values at an even position.
17294 // Place the odd value at an even position (basically, shift all values 1
17295 // step to the left):
17296 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17297 // <a|b|c|d> => <b|undef|d|undef>
17298 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17299 // <e|f|g|h> => <f|undef|h|undef>
17300 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17302 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17304 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17305 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17307 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17308 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17309 // => <2 x i64> <ae|cg>
17310 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17311 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17312 // => <2 x i64> <bf|dh>
17313 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17315 // Shuffle it back into the right order.
17316 SDValue Highs, Lows;
17317 if (VT == MVT::v8i32) {
17318 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17319 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17320 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17321 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17323 const int HighMask[] = {1, 5, 3, 7};
17324 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17325 const int LowMask[] = {0, 4, 2, 6};
17326 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17329 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17330 // unsigned multiply.
17331 if (IsSigned && !Subtarget->hasSSE41()) {
17332 SDValue ShAmt = DAG.getConstant(
17334 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17335 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17336 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17337 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17338 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17340 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17341 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17344 // The first result of MUL_LOHI is actually the low value, followed by the
17346 SDValue Ops[] = {Lows, Highs};
17347 return DAG.getMergeValues(Ops, dl);
17350 // Return true if the required (according to Opcode) shift-imm form is natively
17351 // supported by the Subtarget
17352 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17354 if (VT.getScalarSizeInBits() < 16)
17357 if (VT.is512BitVector() &&
17358 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17361 bool LShift = VT.is128BitVector() ||
17362 (VT.is256BitVector() && Subtarget->hasInt256());
17364 bool AShift = LShift && (Subtarget->hasVLX() ||
17365 (VT != MVT::v2i64 && VT != MVT::v4i64));
17366 return (Opcode == ISD::SRA) ? AShift : LShift;
17369 // The shift amount is a variable, but it is the same for all vector lanes.
17370 // These instructions are defined together with shift-immediate.
17372 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17374 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17377 // Return true if the required (according to Opcode) variable-shift form is
17378 // natively supported by the Subtarget
17379 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17382 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17385 // vXi16 supported only on AVX-512, BWI
17386 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17389 if (VT.is512BitVector() || Subtarget->hasVLX())
17392 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17393 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17394 return (Opcode == ISD::SRA) ? AShift : LShift;
17397 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17398 const X86Subtarget *Subtarget) {
17399 MVT VT = Op.getSimpleValueType();
17401 SDValue R = Op.getOperand(0);
17402 SDValue Amt = Op.getOperand(1);
17404 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17405 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17407 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17408 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17409 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17410 SDValue Ex = DAG.getBitcast(ExVT, R);
17412 if (ShiftAmt >= 32) {
17413 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17415 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17416 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17417 ShiftAmt - 32, DAG);
17418 if (VT == MVT::v2i64)
17419 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17420 if (VT == MVT::v4i64)
17421 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17422 {9, 1, 11, 3, 13, 5, 15, 7});
17424 // SRA upper i32, SHL whole i64 and select lower i32.
17425 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17428 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17429 Lower = DAG.getBitcast(ExVT, Lower);
17430 if (VT == MVT::v2i64)
17431 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17432 if (VT == MVT::v4i64)
17433 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17434 {8, 1, 10, 3, 12, 5, 14, 7});
17436 return DAG.getBitcast(VT, Ex);
17439 // Optimize shl/srl/sra with constant shift amount.
17440 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17441 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17442 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17444 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17445 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17447 // i64 SRA needs to be performed as partial shifts.
17448 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17449 Op.getOpcode() == ISD::SRA)
17450 return ArithmeticShiftRight64(ShiftAmt);
17452 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17453 unsigned NumElts = VT.getVectorNumElements();
17454 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17456 if (Op.getOpcode() == ISD::SHL) {
17457 // Simple i8 add case
17459 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17461 // Make a large shift.
17462 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17464 SHL = DAG.getBitcast(VT, SHL);
17465 // Zero out the rightmost bits.
17466 SmallVector<SDValue, 32> V(
17467 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17468 return DAG.getNode(ISD::AND, dl, VT, SHL,
17469 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17471 if (Op.getOpcode() == ISD::SRL) {
17472 // Make a large shift.
17473 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17475 SRL = DAG.getBitcast(VT, SRL);
17476 // Zero out the leftmost bits.
17477 SmallVector<SDValue, 32> V(
17478 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17479 return DAG.getNode(ISD::AND, dl, VT, SRL,
17480 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17482 if (Op.getOpcode() == ISD::SRA) {
17483 if (ShiftAmt == 7) {
17484 // ashr(R, 7) === cmp_slt(R, 0)
17485 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17486 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17489 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17490 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17491 SmallVector<SDValue, 32> V(NumElts,
17492 DAG.getConstant(128 >> ShiftAmt, dl,
17494 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17495 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17496 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17499 llvm_unreachable("Unknown shift opcode.");
17504 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17505 if (!Subtarget->is64Bit() &&
17506 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17508 // Peek through any splat that was introduced for i64 shift vectorization.
17509 int SplatIndex = -1;
17510 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17511 if (SVN->isSplat()) {
17512 SplatIndex = SVN->getSplatIndex();
17513 Amt = Amt.getOperand(0);
17514 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17515 "Splat shuffle referencing second operand");
17518 if (Amt.getOpcode() != ISD::BITCAST ||
17519 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17522 Amt = Amt.getOperand(0);
17523 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17524 VT.getVectorNumElements();
17525 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17526 uint64_t ShiftAmt = 0;
17527 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17528 for (unsigned i = 0; i != Ratio; ++i) {
17529 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17533 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17536 // Check remaining shift amounts (if not a splat).
17537 if (SplatIndex < 0) {
17538 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17539 uint64_t ShAmt = 0;
17540 for (unsigned j = 0; j != Ratio; ++j) {
17541 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17545 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17547 if (ShAmt != ShiftAmt)
17552 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17553 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17555 if (Op.getOpcode() == ISD::SRA)
17556 return ArithmeticShiftRight64(ShiftAmt);
17562 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17563 const X86Subtarget* Subtarget) {
17564 MVT VT = Op.getSimpleValueType();
17566 SDValue R = Op.getOperand(0);
17567 SDValue Amt = Op.getOperand(1);
17569 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17570 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17572 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17573 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17575 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17577 EVT EltVT = VT.getVectorElementType();
17579 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17580 // Check if this build_vector node is doing a splat.
17581 // If so, then set BaseShAmt equal to the splat value.
17582 BaseShAmt = BV->getSplatValue();
17583 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17584 BaseShAmt = SDValue();
17586 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17587 Amt = Amt.getOperand(0);
17589 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17590 if (SVN && SVN->isSplat()) {
17591 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17592 SDValue InVec = Amt.getOperand(0);
17593 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17594 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17595 "Unexpected shuffle index found!");
17596 BaseShAmt = InVec.getOperand(SplatIdx);
17597 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17598 if (ConstantSDNode *C =
17599 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17600 if (C->getZExtValue() == SplatIdx)
17601 BaseShAmt = InVec.getOperand(1);
17606 // Avoid introducing an extract element from a shuffle.
17607 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17608 DAG.getIntPtrConstant(SplatIdx, dl));
17612 if (BaseShAmt.getNode()) {
17613 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17614 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17615 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17616 else if (EltVT.bitsLT(MVT::i32))
17617 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17619 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17623 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17624 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17625 Amt.getOpcode() == ISD::BITCAST &&
17626 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17627 Amt = Amt.getOperand(0);
17628 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17629 VT.getVectorNumElements();
17630 std::vector<SDValue> Vals(Ratio);
17631 for (unsigned i = 0; i != Ratio; ++i)
17632 Vals[i] = Amt.getOperand(i);
17633 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17634 for (unsigned j = 0; j != Ratio; ++j)
17635 if (Vals[j] != Amt.getOperand(i + j))
17639 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17640 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17645 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17646 SelectionDAG &DAG) {
17647 MVT VT = Op.getSimpleValueType();
17649 SDValue R = Op.getOperand(0);
17650 SDValue Amt = Op.getOperand(1);
17652 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17653 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17655 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17658 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17661 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17664 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17665 // shifts per-lane and then shuffle the partial results back together.
17666 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17667 // Splat the shift amounts so the scalar shifts above will catch it.
17668 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17669 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17670 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17671 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17672 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17675 // i64 vector arithmetic shift can be emulated with the transform:
17676 // M = lshr(SIGN_BIT, Amt)
17677 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17678 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17679 Op.getOpcode() == ISD::SRA) {
17680 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17681 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17682 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17683 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17684 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17688 // If possible, lower this packed shift into a vector multiply instead of
17689 // expanding it into a sequence of scalar shifts.
17690 // Do this only if the vector shift count is a constant build_vector.
17691 if (Op.getOpcode() == ISD::SHL &&
17692 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17693 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17694 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17695 SmallVector<SDValue, 8> Elts;
17696 EVT SVT = VT.getScalarType();
17697 unsigned SVTBits = SVT.getSizeInBits();
17698 const APInt &One = APInt(SVTBits, 1);
17699 unsigned NumElems = VT.getVectorNumElements();
17701 for (unsigned i=0; i !=NumElems; ++i) {
17702 SDValue Op = Amt->getOperand(i);
17703 if (Op->getOpcode() == ISD::UNDEF) {
17704 Elts.push_back(Op);
17708 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17709 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17710 uint64_t ShAmt = C.getZExtValue();
17711 if (ShAmt >= SVTBits) {
17712 Elts.push_back(DAG.getUNDEF(SVT));
17715 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17717 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17718 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17721 // Lower SHL with variable shift amount.
17722 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17723 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17725 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17726 DAG.getConstant(0x3f800000U, dl, VT));
17727 Op = DAG.getBitcast(MVT::v4f32, Op);
17728 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17729 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17732 // If possible, lower this shift as a sequence of two shifts by
17733 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17735 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17737 // Could be rewritten as:
17738 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17740 // The advantage is that the two shifts from the example would be
17741 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17742 // the vector shift into four scalar shifts plus four pairs of vector
17744 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17745 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17746 unsigned TargetOpcode = X86ISD::MOVSS;
17747 bool CanBeSimplified;
17748 // The splat value for the first packed shift (the 'X' from the example).
17749 SDValue Amt1 = Amt->getOperand(0);
17750 // The splat value for the second packed shift (the 'Y' from the example).
17751 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17752 Amt->getOperand(2);
17754 // See if it is possible to replace this node with a sequence of
17755 // two shifts followed by a MOVSS/MOVSD
17756 if (VT == MVT::v4i32) {
17757 // Check if it is legal to use a MOVSS.
17758 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17759 Amt2 == Amt->getOperand(3);
17760 if (!CanBeSimplified) {
17761 // Otherwise, check if we can still simplify this node using a MOVSD.
17762 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17763 Amt->getOperand(2) == Amt->getOperand(3);
17764 TargetOpcode = X86ISD::MOVSD;
17765 Amt2 = Amt->getOperand(2);
17768 // Do similar checks for the case where the machine value type
17770 CanBeSimplified = Amt1 == Amt->getOperand(1);
17771 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17772 CanBeSimplified = Amt2 == Amt->getOperand(i);
17774 if (!CanBeSimplified) {
17775 TargetOpcode = X86ISD::MOVSD;
17776 CanBeSimplified = true;
17777 Amt2 = Amt->getOperand(4);
17778 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17779 CanBeSimplified = Amt1 == Amt->getOperand(i);
17780 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17781 CanBeSimplified = Amt2 == Amt->getOperand(j);
17785 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17786 isa<ConstantSDNode>(Amt2)) {
17787 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17788 EVT CastVT = MVT::v4i32;
17790 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17791 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17793 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17794 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17795 if (TargetOpcode == X86ISD::MOVSD)
17796 CastVT = MVT::v2i64;
17797 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17798 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17799 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17801 return DAG.getBitcast(VT, Result);
17805 // v4i32 Non Uniform Shifts.
17806 // If the shift amount is constant we can shift each lane using the SSE2
17807 // immediate shifts, else we need to zero-extend each lane to the lower i64
17808 // and shift using the SSE2 variable shifts.
17809 // The separate results can then be blended together.
17810 if (VT == MVT::v4i32) {
17811 unsigned Opc = Op.getOpcode();
17812 SDValue Amt0, Amt1, Amt2, Amt3;
17813 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17814 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17815 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17816 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17817 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17819 // ISD::SHL is handled above but we include it here for completeness.
17822 llvm_unreachable("Unknown target vector shift node");
17824 Opc = X86ISD::VSHL;
17827 Opc = X86ISD::VSRL;
17830 Opc = X86ISD::VSRA;
17833 // The SSE2 shifts use the lower i64 as the same shift amount for
17834 // all lanes and the upper i64 is ignored. These shuffle masks
17835 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17836 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17837 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17838 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17839 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17840 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17843 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17844 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17845 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17846 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17847 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17848 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17849 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17852 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17853 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17854 unsigned ShiftOpcode = Op->getOpcode();
17856 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17857 // On SSE41 targets we make use of the fact that VSELECT lowers
17858 // to PBLENDVB which selects bytes based just on the sign bit.
17859 if (Subtarget->hasSSE41()) {
17860 V0 = DAG.getBitcast(VT, V0);
17861 V1 = DAG.getBitcast(VT, V1);
17862 Sel = DAG.getBitcast(VT, Sel);
17863 return DAG.getBitcast(SelVT,
17864 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17866 // On pre-SSE41 targets we test for the sign bit by comparing to
17867 // zero - a negative value will set all bits of the lanes to true
17868 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17869 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17870 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17871 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17874 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17875 // We can safely do this using i16 shifts as we're only interested in
17876 // the 3 lower bits of each byte.
17877 Amt = DAG.getBitcast(ExtVT, Amt);
17878 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17879 Amt = DAG.getBitcast(VT, Amt);
17881 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17882 // r = VSELECT(r, shift(r, 4), a);
17884 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17885 R = SignBitSelect(VT, Amt, M, R);
17888 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17890 // r = VSELECT(r, shift(r, 2), a);
17891 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17892 R = SignBitSelect(VT, Amt, M, R);
17895 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17897 // return VSELECT(r, shift(r, 1), a);
17898 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17899 R = SignBitSelect(VT, Amt, M, R);
17903 if (Op->getOpcode() == ISD::SRA) {
17904 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17905 // so we can correctly sign extend. We don't care what happens to the
17907 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17908 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17909 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17910 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17911 ALo = DAG.getBitcast(ExtVT, ALo);
17912 AHi = DAG.getBitcast(ExtVT, AHi);
17913 RLo = DAG.getBitcast(ExtVT, RLo);
17914 RHi = DAG.getBitcast(ExtVT, RHi);
17916 // r = VSELECT(r, shift(r, 4), a);
17917 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17918 DAG.getConstant(4, dl, ExtVT));
17919 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17920 DAG.getConstant(4, dl, ExtVT));
17921 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17922 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17925 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17926 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17928 // r = VSELECT(r, shift(r, 2), a);
17929 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17930 DAG.getConstant(2, dl, ExtVT));
17931 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17932 DAG.getConstant(2, dl, ExtVT));
17933 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17934 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17937 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17938 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17940 // r = VSELECT(r, shift(r, 1), a);
17941 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17942 DAG.getConstant(1, dl, ExtVT));
17943 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17944 DAG.getConstant(1, dl, ExtVT));
17945 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17946 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17948 // Logical shift the result back to the lower byte, leaving a zero upper
17950 // meaning that we can safely pack with PACKUSWB.
17952 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17954 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17955 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17959 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17960 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17961 // solution better.
17962 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17963 MVT ExtVT = MVT::v8i32;
17965 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17966 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17967 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17968 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17969 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17972 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17973 MVT ExtVT = MVT::v8i32;
17974 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17975 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17976 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17977 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17978 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17979 ALo = DAG.getBitcast(ExtVT, ALo);
17980 AHi = DAG.getBitcast(ExtVT, AHi);
17981 RLo = DAG.getBitcast(ExtVT, RLo);
17982 RHi = DAG.getBitcast(ExtVT, RHi);
17983 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17984 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17985 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17986 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17987 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17990 if (VT == MVT::v8i16) {
17991 unsigned ShiftOpcode = Op->getOpcode();
17993 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17994 // On SSE41 targets we make use of the fact that VSELECT lowers
17995 // to PBLENDVB which selects bytes based just on the sign bit.
17996 if (Subtarget->hasSSE41()) {
17997 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17998 V0 = DAG.getBitcast(ExtVT, V0);
17999 V1 = DAG.getBitcast(ExtVT, V1);
18000 Sel = DAG.getBitcast(ExtVT, Sel);
18001 return DAG.getBitcast(
18002 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18004 // On pre-SSE41 targets we splat the sign bit - a negative value will
18005 // set all bits of the lanes to true and VSELECT uses that in
18006 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18008 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18009 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18012 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18013 if (Subtarget->hasSSE41()) {
18014 // On SSE41 targets we need to replicate the shift mask in both
18015 // bytes for PBLENDVB.
18018 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18019 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18021 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18024 // r = VSELECT(r, shift(r, 8), a);
18025 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18026 R = SignBitSelect(Amt, M, R);
18029 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18031 // r = VSELECT(r, shift(r, 4), a);
18032 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18033 R = SignBitSelect(Amt, M, R);
18036 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18038 // r = VSELECT(r, shift(r, 2), a);
18039 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18040 R = SignBitSelect(Amt, M, R);
18043 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18045 // return VSELECT(r, shift(r, 1), a);
18046 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18047 R = SignBitSelect(Amt, M, R);
18051 // Decompose 256-bit shifts into smaller 128-bit shifts.
18052 if (VT.is256BitVector()) {
18053 unsigned NumElems = VT.getVectorNumElements();
18054 MVT EltVT = VT.getVectorElementType();
18055 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18057 // Extract the two vectors
18058 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18059 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18061 // Recreate the shift amount vectors
18062 SDValue Amt1, Amt2;
18063 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18064 // Constant shift amount
18065 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18066 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18067 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18069 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18070 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18072 // Variable shift amount
18073 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18074 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18077 // Issue new vector shifts for the smaller types
18078 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18079 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18081 // Concatenate the result back
18082 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18088 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18089 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18090 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18091 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18092 // has only one use.
18093 SDNode *N = Op.getNode();
18094 SDValue LHS = N->getOperand(0);
18095 SDValue RHS = N->getOperand(1);
18096 unsigned BaseOp = 0;
18099 switch (Op.getOpcode()) {
18100 default: llvm_unreachable("Unknown ovf instruction!");
18102 // A subtract of one will be selected as a INC. Note that INC doesn't
18103 // set CF, so we can't do this for UADDO.
18104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18106 BaseOp = X86ISD::INC;
18107 Cond = X86::COND_O;
18110 BaseOp = X86ISD::ADD;
18111 Cond = X86::COND_O;
18114 BaseOp = X86ISD::ADD;
18115 Cond = X86::COND_B;
18118 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18119 // set CF, so we can't do this for USUBO.
18120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18122 BaseOp = X86ISD::DEC;
18123 Cond = X86::COND_O;
18126 BaseOp = X86ISD::SUB;
18127 Cond = X86::COND_O;
18130 BaseOp = X86ISD::SUB;
18131 Cond = X86::COND_B;
18134 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18135 Cond = X86::COND_O;
18137 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18138 if (N->getValueType(0) == MVT::i8) {
18139 BaseOp = X86ISD::UMUL8;
18140 Cond = X86::COND_O;
18143 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18145 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18148 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18149 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18150 SDValue(Sum.getNode(), 2));
18152 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18156 // Also sets EFLAGS.
18157 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18158 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18161 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18162 DAG.getConstant(Cond, DL, MVT::i32),
18163 SDValue(Sum.getNode(), 1));
18165 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18168 /// Returns true if the operand type is exactly twice the native width, and
18169 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18170 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18171 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18172 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18173 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18176 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18177 else if (OpWidth == 128)
18178 return Subtarget->hasCmpxchg16b();
18183 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18184 return needsCmpXchgNb(SI->getValueOperand()->getType());
18187 // Note: this turns large loads into lock cmpxchg8b/16b.
18188 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18189 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18190 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18191 return needsCmpXchgNb(PTy->getElementType());
18194 TargetLoweringBase::AtomicRMWExpansionKind
18195 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18196 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18197 Type *MemType = AI->getType();
18199 // If the operand is too big, we must see if cmpxchg8/16b is available
18200 // and default to library calls otherwise.
18201 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18202 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18203 : AtomicRMWExpansionKind::None;
18206 AtomicRMWInst::BinOp Op = AI->getOperation();
18209 llvm_unreachable("Unknown atomic operation");
18210 case AtomicRMWInst::Xchg:
18211 case AtomicRMWInst::Add:
18212 case AtomicRMWInst::Sub:
18213 // It's better to use xadd, xsub or xchg for these in all cases.
18214 return AtomicRMWExpansionKind::None;
18215 case AtomicRMWInst::Or:
18216 case AtomicRMWInst::And:
18217 case AtomicRMWInst::Xor:
18218 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18219 // prefix to a normal instruction for these operations.
18220 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18221 : AtomicRMWExpansionKind::None;
18222 case AtomicRMWInst::Nand:
18223 case AtomicRMWInst::Max:
18224 case AtomicRMWInst::Min:
18225 case AtomicRMWInst::UMax:
18226 case AtomicRMWInst::UMin:
18227 // These always require a non-trivial set of data operations on x86. We must
18228 // use a cmpxchg loop.
18229 return AtomicRMWExpansionKind::CmpXChg;
18233 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18234 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18235 // no-sse2). There isn't any reason to disable it if the target processor
18237 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18241 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18242 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18243 Type *MemType = AI->getType();
18244 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18245 // there is no benefit in turning such RMWs into loads, and it is actually
18246 // harmful as it introduces a mfence.
18247 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18250 auto Builder = IRBuilder<>(AI);
18251 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18252 auto SynchScope = AI->getSynchScope();
18253 // We must restrict the ordering to avoid generating loads with Release or
18254 // ReleaseAcquire orderings.
18255 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18256 auto Ptr = AI->getPointerOperand();
18258 // Before the load we need a fence. Here is an example lifted from
18259 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18262 // x.store(1, relaxed);
18263 // r1 = y.fetch_add(0, release);
18265 // y.fetch_add(42, acquire);
18266 // r2 = x.load(relaxed);
18267 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18268 // lowered to just a load without a fence. A mfence flushes the store buffer,
18269 // making the optimization clearly correct.
18270 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18271 // otherwise, we might be able to be more aggressive on relaxed idempotent
18272 // rmw. In practice, they do not look useful, so we don't try to be
18273 // especially clever.
18274 if (SynchScope == SingleThread)
18275 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18276 // the IR level, so we must wrap it in an intrinsic.
18279 if (!hasMFENCE(*Subtarget))
18280 // FIXME: it might make sense to use a locked operation here but on a
18281 // different cache-line to prevent cache-line bouncing. In practice it
18282 // is probably a small win, and x86 processors without mfence are rare
18283 // enough that we do not bother.
18287 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18288 Builder.CreateCall(MFence, {});
18290 // Finally we can emit the atomic load.
18291 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18292 AI->getType()->getPrimitiveSizeInBits());
18293 Loaded->setAtomic(Order, SynchScope);
18294 AI->replaceAllUsesWith(Loaded);
18295 AI->eraseFromParent();
18299 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18300 SelectionDAG &DAG) {
18302 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18303 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18304 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18305 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18307 // The only fence that needs an instruction is a sequentially-consistent
18308 // cross-thread fence.
18309 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18310 if (hasMFENCE(*Subtarget))
18311 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18313 SDValue Chain = Op.getOperand(0);
18314 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18316 DAG.getRegister(X86::ESP, MVT::i32), // Base
18317 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18318 DAG.getRegister(0, MVT::i32), // Index
18319 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18320 DAG.getRegister(0, MVT::i32), // Segment.
18324 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18325 return SDValue(Res, 0);
18328 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18329 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18332 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18333 SelectionDAG &DAG) {
18334 MVT T = Op.getSimpleValueType();
18338 switch(T.SimpleTy) {
18339 default: llvm_unreachable("Invalid value type!");
18340 case MVT::i8: Reg = X86::AL; size = 1; break;
18341 case MVT::i16: Reg = X86::AX; size = 2; break;
18342 case MVT::i32: Reg = X86::EAX; size = 4; break;
18344 assert(Subtarget->is64Bit() && "Node not type legal!");
18345 Reg = X86::RAX; size = 8;
18348 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18349 Op.getOperand(2), SDValue());
18350 SDValue Ops[] = { cpIn.getValue(0),
18353 DAG.getTargetConstant(size, DL, MVT::i8),
18354 cpIn.getValue(1) };
18355 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18356 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18357 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18361 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18362 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18363 MVT::i32, cpOut.getValue(2));
18364 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18365 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18368 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18369 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18370 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18374 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18375 SelectionDAG &DAG) {
18376 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18377 MVT DstVT = Op.getSimpleValueType();
18379 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18380 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18381 if (DstVT != MVT::f64)
18382 // This conversion needs to be expanded.
18385 SDValue InVec = Op->getOperand(0);
18387 unsigned NumElts = SrcVT.getVectorNumElements();
18388 EVT SVT = SrcVT.getVectorElementType();
18390 // Widen the vector in input in the case of MVT::v2i32.
18391 // Example: from MVT::v2i32 to MVT::v4i32.
18392 SmallVector<SDValue, 16> Elts;
18393 for (unsigned i = 0, e = NumElts; i != e; ++i)
18394 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18395 DAG.getIntPtrConstant(i, dl)));
18397 // Explicitly mark the extra elements as Undef.
18398 Elts.append(NumElts, DAG.getUNDEF(SVT));
18400 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18401 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18402 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18403 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18404 DAG.getIntPtrConstant(0, dl));
18407 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18408 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18409 assert((DstVT == MVT::i64 ||
18410 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18411 "Unexpected custom BITCAST");
18412 // i64 <=> MMX conversions are Legal.
18413 if (SrcVT==MVT::i64 && DstVT.isVector())
18415 if (DstVT==MVT::i64 && SrcVT.isVector())
18417 // MMX <=> MMX conversions are Legal.
18418 if (SrcVT.isVector() && DstVT.isVector())
18420 // All other conversions need to be expanded.
18424 /// Compute the horizontal sum of bytes in V for the elements of VT.
18426 /// Requires V to be a byte vector and VT to be an integer vector type with
18427 /// wider elements than V's type. The width of the elements of VT determines
18428 /// how many bytes of V are summed horizontally to produce each element of the
18430 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18431 const X86Subtarget *Subtarget,
18432 SelectionDAG &DAG) {
18434 MVT ByteVecVT = V.getSimpleValueType();
18435 MVT EltVT = VT.getVectorElementType();
18436 int NumElts = VT.getVectorNumElements();
18437 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18438 "Expected value to have byte element type.");
18439 assert(EltVT != MVT::i8 &&
18440 "Horizontal byte sum only makes sense for wider elements!");
18441 unsigned VecSize = VT.getSizeInBits();
18442 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18444 // PSADBW instruction horizontally add all bytes and leave the result in i64
18445 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18446 if (EltVT == MVT::i64) {
18447 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18448 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18449 return DAG.getBitcast(VT, V);
18452 if (EltVT == MVT::i32) {
18453 // We unpack the low half and high half into i32s interleaved with zeros so
18454 // that we can use PSADBW to horizontally sum them. The most useful part of
18455 // this is that it lines up the results of two PSADBW instructions to be
18456 // two v2i64 vectors which concatenated are the 4 population counts. We can
18457 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18458 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18459 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18460 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18462 // Do the horizontal sums into two v2i64s.
18463 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18464 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18465 DAG.getBitcast(ByteVecVT, Low), Zeros);
18466 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18467 DAG.getBitcast(ByteVecVT, High), Zeros);
18469 // Merge them together.
18470 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18471 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18472 DAG.getBitcast(ShortVecVT, Low),
18473 DAG.getBitcast(ShortVecVT, High));
18475 return DAG.getBitcast(VT, V);
18478 // The only element type left is i16.
18479 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18481 // To obtain pop count for each i16 element starting from the pop count for
18482 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18483 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18484 // directly supported.
18485 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18486 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18487 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18488 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18489 DAG.getBitcast(ByteVecVT, V));
18490 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18493 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18494 const X86Subtarget *Subtarget,
18495 SelectionDAG &DAG) {
18496 MVT VT = Op.getSimpleValueType();
18497 MVT EltVT = VT.getVectorElementType();
18498 unsigned VecSize = VT.getSizeInBits();
18500 // Implement a lookup table in register by using an algorithm based on:
18501 // http://wm.ite.pl/articles/sse-popcount.html
18503 // The general idea is that every lower byte nibble in the input vector is an
18504 // index into a in-register pre-computed pop count table. We then split up the
18505 // input vector in two new ones: (1) a vector with only the shifted-right
18506 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18507 // masked out higher ones) for each byte. PSHUB is used separately with both
18508 // to index the in-register table. Next, both are added and the result is a
18509 // i8 vector where each element contains the pop count for input byte.
18511 // To obtain the pop count for elements != i8, we follow up with the same
18512 // approach and use additional tricks as described below.
18514 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18515 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18516 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18517 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18519 int NumByteElts = VecSize / 8;
18520 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18521 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18522 SmallVector<SDValue, 16> LUTVec;
18523 for (int i = 0; i < NumByteElts; ++i)
18524 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18525 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18526 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18527 DAG.getConstant(0x0F, DL, MVT::i8));
18528 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18531 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18532 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18533 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18536 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18538 // The input vector is used as the shuffle mask that index elements into the
18539 // LUT. After counting low and high nibbles, add the vector to obtain the
18540 // final pop count per i8 element.
18541 SDValue HighPopCnt =
18542 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18543 SDValue LowPopCnt =
18544 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18545 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18547 if (EltVT == MVT::i8)
18550 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18553 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18554 const X86Subtarget *Subtarget,
18555 SelectionDAG &DAG) {
18556 MVT VT = Op.getSimpleValueType();
18557 assert(VT.is128BitVector() &&
18558 "Only 128-bit vector bitmath lowering supported.");
18560 int VecSize = VT.getSizeInBits();
18561 MVT EltVT = VT.getVectorElementType();
18562 int Len = EltVT.getSizeInBits();
18564 // This is the vectorized version of the "best" algorithm from
18565 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18566 // with a minor tweak to use a series of adds + shifts instead of vector
18567 // multiplications. Implemented for all integer vector types. We only use
18568 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18569 // much faster, even faster than using native popcnt instructions.
18571 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18572 MVT VT = V.getSimpleValueType();
18573 SmallVector<SDValue, 32> Shifters(
18574 VT.getVectorNumElements(),
18575 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18576 return DAG.getNode(OpCode, DL, VT, V,
18577 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18579 auto GetMask = [&](SDValue V, APInt Mask) {
18580 MVT VT = V.getSimpleValueType();
18581 SmallVector<SDValue, 32> Masks(
18582 VT.getVectorNumElements(),
18583 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18584 return DAG.getNode(ISD::AND, DL, VT, V,
18585 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18588 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18589 // x86, so set the SRL type to have elements at least i16 wide. This is
18590 // correct because all of our SRLs are followed immediately by a mask anyways
18591 // that handles any bits that sneak into the high bits of the byte elements.
18592 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18596 // v = v - ((v >> 1) & 0x55555555...)
18598 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18599 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18600 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18602 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18603 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18604 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18605 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18606 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18608 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18609 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18610 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18611 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18613 // At this point, V contains the byte-wise population count, and we are
18614 // merely doing a horizontal sum if necessary to get the wider element
18616 if (EltVT == MVT::i8)
18619 return LowerHorizontalByteSum(
18620 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18624 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18625 SelectionDAG &DAG) {
18626 MVT VT = Op.getSimpleValueType();
18627 // FIXME: Need to add AVX-512 support here!
18628 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18629 "Unknown CTPOP type to handle");
18630 SDLoc DL(Op.getNode());
18631 SDValue Op0 = Op.getOperand(0);
18633 if (!Subtarget->hasSSSE3()) {
18634 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18635 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18636 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18639 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18640 unsigned NumElems = VT.getVectorNumElements();
18642 // Extract each 128-bit vector, compute pop count and concat the result.
18643 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18644 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18646 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18647 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18648 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18651 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18654 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18655 SelectionDAG &DAG) {
18656 assert(Op.getValueType().isVector() &&
18657 "We only do custom lowering for vector population count.");
18658 return LowerVectorCTPOP(Op, Subtarget, DAG);
18661 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18662 SDNode *Node = Op.getNode();
18664 EVT T = Node->getValueType(0);
18665 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18666 DAG.getConstant(0, dl, T), Node->getOperand(2));
18667 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18668 cast<AtomicSDNode>(Node)->getMemoryVT(),
18669 Node->getOperand(0),
18670 Node->getOperand(1), negOp,
18671 cast<AtomicSDNode>(Node)->getMemOperand(),
18672 cast<AtomicSDNode>(Node)->getOrdering(),
18673 cast<AtomicSDNode>(Node)->getSynchScope());
18676 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18677 SDNode *Node = Op.getNode();
18679 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18681 // Convert seq_cst store -> xchg
18682 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18683 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18684 // (The only way to get a 16-byte store is cmpxchg16b)
18685 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18686 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18687 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18688 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18689 cast<AtomicSDNode>(Node)->getMemoryVT(),
18690 Node->getOperand(0),
18691 Node->getOperand(1), Node->getOperand(2),
18692 cast<AtomicSDNode>(Node)->getMemOperand(),
18693 cast<AtomicSDNode>(Node)->getOrdering(),
18694 cast<AtomicSDNode>(Node)->getSynchScope());
18695 return Swap.getValue(1);
18697 // Other atomic stores have a simple pattern.
18701 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18702 EVT VT = Op.getNode()->getSimpleValueType(0);
18704 // Let legalize expand this if it isn't a legal type yet.
18705 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18708 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18711 bool ExtraOp = false;
18712 switch (Op.getOpcode()) {
18713 default: llvm_unreachable("Invalid code");
18714 case ISD::ADDC: Opc = X86ISD::ADD; break;
18715 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18716 case ISD::SUBC: Opc = X86ISD::SUB; break;
18717 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18721 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18723 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18724 Op.getOperand(1), Op.getOperand(2));
18727 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18728 SelectionDAG &DAG) {
18729 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18731 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18732 // which returns the values as { float, float } (in XMM0) or
18733 // { double, double } (which is returned in XMM0, XMM1).
18735 SDValue Arg = Op.getOperand(0);
18736 EVT ArgVT = Arg.getValueType();
18737 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18739 TargetLowering::ArgListTy Args;
18740 TargetLowering::ArgListEntry Entry;
18744 Entry.isSExt = false;
18745 Entry.isZExt = false;
18746 Args.push_back(Entry);
18748 bool isF64 = ArgVT == MVT::f64;
18749 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18750 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18751 // the results are returned via SRet in memory.
18752 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18753 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18755 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18757 Type *RetTy = isF64
18758 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18759 : (Type*)VectorType::get(ArgTy, 4);
18761 TargetLowering::CallLoweringInfo CLI(DAG);
18762 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18763 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18765 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18768 // Returned in xmm0 and xmm1.
18769 return CallResult.first;
18771 // Returned in bits 0:31 and 32:64 xmm0.
18772 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18773 CallResult.first, DAG.getIntPtrConstant(0, dl));
18774 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18775 CallResult.first, DAG.getIntPtrConstant(1, dl));
18776 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18777 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18780 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18781 SelectionDAG &DAG) {
18782 assert(Subtarget->hasAVX512() &&
18783 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18785 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18786 EVT VT = N->getValue().getValueType();
18787 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18790 // X86 scatter kills mask register, so its type should be added to
18791 // the list of return values
18792 if (N->getNumValues() == 1) {
18793 SDValue Index = N->getIndex();
18794 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18795 !Index.getValueType().is512BitVector())
18796 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18798 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18799 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18800 N->getOperand(3), Index };
18802 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18803 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18804 return SDValue(NewScatter.getNode(), 0);
18809 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18810 SelectionDAG &DAG) {
18811 assert(Subtarget->hasAVX512() &&
18812 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18814 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18815 EVT VT = Op.getValueType();
18816 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18819 SDValue Index = N->getIndex();
18820 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18821 !Index.getValueType().is512BitVector()) {
18822 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18823 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18824 N->getOperand(3), Index };
18825 DAG.UpdateNodeOperands(N, Ops);
18830 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18831 SelectionDAG &DAG) const {
18832 // TODO: Eventually, the lowering of these nodes should be informed by or
18833 // deferred to the GC strategy for the function in which they appear. For
18834 // now, however, they must be lowered to something. Since they are logically
18835 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18836 // require special handling for these nodes), lower them as literal NOOPs for
18838 SmallVector<SDValue, 2> Ops;
18840 Ops.push_back(Op.getOperand(0));
18841 if (Op->getGluedNode())
18842 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18845 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18846 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18851 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18852 SelectionDAG &DAG) const {
18853 // TODO: Eventually, the lowering of these nodes should be informed by or
18854 // deferred to the GC strategy for the function in which they appear. For
18855 // now, however, they must be lowered to something. Since they are logically
18856 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18857 // require special handling for these nodes), lower them as literal NOOPs for
18859 SmallVector<SDValue, 2> Ops;
18861 Ops.push_back(Op.getOperand(0));
18862 if (Op->getGluedNode())
18863 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18866 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18867 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18872 /// LowerOperation - Provide custom lowering hooks for some operations.
18874 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18875 switch (Op.getOpcode()) {
18876 default: llvm_unreachable("Should not custom lower this!");
18877 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18878 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18879 return LowerCMP_SWAP(Op, Subtarget, DAG);
18880 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18881 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18882 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18883 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18884 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18885 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18886 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18887 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18888 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18889 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18890 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18891 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18892 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18893 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18894 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18895 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18896 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18897 case ISD::SHL_PARTS:
18898 case ISD::SRA_PARTS:
18899 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18900 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18901 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18902 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18903 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18904 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18905 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18906 case ISD::SIGN_EXTEND_VECTOR_INREG:
18907 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18908 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18909 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18910 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18911 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18913 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18914 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18915 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18916 case ISD::SETCC: return LowerSETCC(Op, DAG);
18917 case ISD::SELECT: return LowerSELECT(Op, DAG);
18918 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18919 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18920 case ISD::VASTART: return LowerVASTART(Op, DAG);
18921 case ISD::VAARG: return LowerVAARG(Op, DAG);
18922 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18923 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18924 case ISD::INTRINSIC_VOID:
18925 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18926 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18927 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18928 case ISD::FRAME_TO_ARGS_OFFSET:
18929 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18930 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18931 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18932 case ISD::CATCHRET: return LowerCATCHRET(Op, DAG);
18933 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18934 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18935 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18936 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18937 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18938 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18939 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18940 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18941 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18942 case ISD::UMUL_LOHI:
18943 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18946 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18952 case ISD::UMULO: return LowerXALUO(Op, DAG);
18953 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18954 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18958 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18959 case ISD::ADD: return LowerADD(Op, DAG);
18960 case ISD::SUB: return LowerSUB(Op, DAG);
18964 case ISD::UMIN: return LowerMINMAX(Op, DAG);
18965 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18966 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18967 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18968 case ISD::GC_TRANSITION_START:
18969 return LowerGC_TRANSITION_START(Op, DAG);
18970 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18974 /// ReplaceNodeResults - Replace a node with an illegal result type
18975 /// with a new node built out of custom code.
18976 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18977 SmallVectorImpl<SDValue>&Results,
18978 SelectionDAG &DAG) const {
18980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18981 switch (N->getOpcode()) {
18983 llvm_unreachable("Do not know how to custom type legalize this operation!");
18984 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18985 case X86ISD::FMINC:
18987 case X86ISD::FMAXC:
18988 case X86ISD::FMAX: {
18989 EVT VT = N->getValueType(0);
18990 if (VT != MVT::v2f32)
18991 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18992 SDValue UNDEF = DAG.getUNDEF(VT);
18993 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18994 N->getOperand(0), UNDEF);
18995 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18996 N->getOperand(1), UNDEF);
18997 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19000 case ISD::SIGN_EXTEND_INREG:
19005 // We don't want to expand or promote these.
19012 case ISD::UDIVREM: {
19013 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19014 Results.push_back(V);
19017 case ISD::FP_TO_SINT:
19018 case ISD::FP_TO_UINT: {
19019 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19021 std::pair<SDValue,SDValue> Vals =
19022 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19023 SDValue FIST = Vals.first, StackSlot = Vals.second;
19024 if (FIST.getNode()) {
19025 EVT VT = N->getValueType(0);
19026 // Return a load from the stack slot.
19027 if (StackSlot.getNode())
19028 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19029 MachinePointerInfo(),
19030 false, false, false, 0));
19032 Results.push_back(FIST);
19036 case ISD::UINT_TO_FP: {
19037 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19038 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19039 N->getValueType(0) != MVT::v2f32)
19041 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19043 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19045 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19046 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19047 DAG.getBitcast(MVT::v2i64, VBias));
19048 Or = DAG.getBitcast(MVT::v2f64, Or);
19049 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19050 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19053 case ISD::FP_ROUND: {
19054 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19056 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19057 Results.push_back(V);
19060 case ISD::FP_EXTEND: {
19061 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19062 // No other ValueType for FP_EXTEND should reach this point.
19063 assert(N->getValueType(0) == MVT::v2f32 &&
19064 "Do not know how to legalize this Node");
19067 case ISD::INTRINSIC_W_CHAIN: {
19068 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19070 default : llvm_unreachable("Do not know how to custom type "
19071 "legalize this intrinsic operation!");
19072 case Intrinsic::x86_rdtsc:
19073 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19075 case Intrinsic::x86_rdtscp:
19076 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19078 case Intrinsic::x86_rdpmc:
19079 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19082 case ISD::READCYCLECOUNTER: {
19083 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19086 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19087 EVT T = N->getValueType(0);
19088 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19089 bool Regs64bit = T == MVT::i128;
19090 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19091 SDValue cpInL, cpInH;
19092 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19093 DAG.getConstant(0, dl, HalfT));
19094 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19095 DAG.getConstant(1, dl, HalfT));
19096 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19097 Regs64bit ? X86::RAX : X86::EAX,
19099 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19100 Regs64bit ? X86::RDX : X86::EDX,
19101 cpInH, cpInL.getValue(1));
19102 SDValue swapInL, swapInH;
19103 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19104 DAG.getConstant(0, dl, HalfT));
19105 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19106 DAG.getConstant(1, dl, HalfT));
19107 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19108 Regs64bit ? X86::RBX : X86::EBX,
19109 swapInL, cpInH.getValue(1));
19110 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19111 Regs64bit ? X86::RCX : X86::ECX,
19112 swapInH, swapInL.getValue(1));
19113 SDValue Ops[] = { swapInH.getValue(0),
19115 swapInH.getValue(1) };
19116 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19117 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19118 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19119 X86ISD::LCMPXCHG8_DAG;
19120 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19121 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19122 Regs64bit ? X86::RAX : X86::EAX,
19123 HalfT, Result.getValue(1));
19124 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19125 Regs64bit ? X86::RDX : X86::EDX,
19126 HalfT, cpOutL.getValue(2));
19127 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19129 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19130 MVT::i32, cpOutH.getValue(2));
19132 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19133 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19134 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19136 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19137 Results.push_back(Success);
19138 Results.push_back(EFLAGS.getValue(1));
19141 case ISD::ATOMIC_SWAP:
19142 case ISD::ATOMIC_LOAD_ADD:
19143 case ISD::ATOMIC_LOAD_SUB:
19144 case ISD::ATOMIC_LOAD_AND:
19145 case ISD::ATOMIC_LOAD_OR:
19146 case ISD::ATOMIC_LOAD_XOR:
19147 case ISD::ATOMIC_LOAD_NAND:
19148 case ISD::ATOMIC_LOAD_MIN:
19149 case ISD::ATOMIC_LOAD_MAX:
19150 case ISD::ATOMIC_LOAD_UMIN:
19151 case ISD::ATOMIC_LOAD_UMAX:
19152 case ISD::ATOMIC_LOAD: {
19153 // Delegate to generic TypeLegalization. Situations we can really handle
19154 // should have already been dealt with by AtomicExpandPass.cpp.
19157 case ISD::BITCAST: {
19158 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19159 EVT DstVT = N->getValueType(0);
19160 EVT SrcVT = N->getOperand(0)->getValueType(0);
19162 if (SrcVT != MVT::f64 ||
19163 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19166 unsigned NumElts = DstVT.getVectorNumElements();
19167 EVT SVT = DstVT.getVectorElementType();
19168 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19169 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19170 MVT::v2f64, N->getOperand(0));
19171 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19173 if (ExperimentalVectorWideningLegalization) {
19174 // If we are legalizing vectors by widening, we already have the desired
19175 // legal vector type, just return it.
19176 Results.push_back(ToVecInt);
19180 SmallVector<SDValue, 8> Elts;
19181 for (unsigned i = 0, e = NumElts; i != e; ++i)
19182 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19183 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19185 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19190 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19191 switch ((X86ISD::NodeType)Opcode) {
19192 case X86ISD::FIRST_NUMBER: break;
19193 case X86ISD::BSF: return "X86ISD::BSF";
19194 case X86ISD::BSR: return "X86ISD::BSR";
19195 case X86ISD::SHLD: return "X86ISD::SHLD";
19196 case X86ISD::SHRD: return "X86ISD::SHRD";
19197 case X86ISD::FAND: return "X86ISD::FAND";
19198 case X86ISD::FANDN: return "X86ISD::FANDN";
19199 case X86ISD::FOR: return "X86ISD::FOR";
19200 case X86ISD::FXOR: return "X86ISD::FXOR";
19201 case X86ISD::FILD: return "X86ISD::FILD";
19202 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19203 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19204 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19205 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19206 case X86ISD::FLD: return "X86ISD::FLD";
19207 case X86ISD::FST: return "X86ISD::FST";
19208 case X86ISD::CALL: return "X86ISD::CALL";
19209 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19210 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19211 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19212 case X86ISD::BT: return "X86ISD::BT";
19213 case X86ISD::CMP: return "X86ISD::CMP";
19214 case X86ISD::COMI: return "X86ISD::COMI";
19215 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19216 case X86ISD::CMPM: return "X86ISD::CMPM";
19217 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19218 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19219 case X86ISD::SETCC: return "X86ISD::SETCC";
19220 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19221 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19222 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19223 case X86ISD::CMOV: return "X86ISD::CMOV";
19224 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19225 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19226 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19227 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19228 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19229 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19230 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19231 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19232 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19233 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19234 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19235 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19236 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19237 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19238 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19239 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19240 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19241 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19242 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19243 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19244 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19245 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19246 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19247 case X86ISD::HADD: return "X86ISD::HADD";
19248 case X86ISD::HSUB: return "X86ISD::HSUB";
19249 case X86ISD::FHADD: return "X86ISD::FHADD";
19250 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19251 case X86ISD::ABS: return "X86ISD::ABS";
19252 case X86ISD::FMAX: return "X86ISD::FMAX";
19253 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19254 case X86ISD::FMIN: return "X86ISD::FMIN";
19255 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19256 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19257 case X86ISD::FMINC: return "X86ISD::FMINC";
19258 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19259 case X86ISD::FRCP: return "X86ISD::FRCP";
19260 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19261 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19262 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19263 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19264 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19265 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19266 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19267 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19268 case X86ISD::CATCHRET: return "X86ISD::CATCHRET";
19269 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19270 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19271 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19272 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19273 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19274 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19275 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19276 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19277 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19278 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19279 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19280 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19281 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19282 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19283 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19284 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19285 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19286 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19287 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19288 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19289 case X86ISD::VSHL: return "X86ISD::VSHL";
19290 case X86ISD::VSRL: return "X86ISD::VSRL";
19291 case X86ISD::VSRA: return "X86ISD::VSRA";
19292 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19293 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19294 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19295 case X86ISD::CMPP: return "X86ISD::CMPP";
19296 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19297 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19298 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19299 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19300 case X86ISD::ADD: return "X86ISD::ADD";
19301 case X86ISD::SUB: return "X86ISD::SUB";
19302 case X86ISD::ADC: return "X86ISD::ADC";
19303 case X86ISD::SBB: return "X86ISD::SBB";
19304 case X86ISD::SMUL: return "X86ISD::SMUL";
19305 case X86ISD::UMUL: return "X86ISD::UMUL";
19306 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19307 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19308 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19309 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19310 case X86ISD::INC: return "X86ISD::INC";
19311 case X86ISD::DEC: return "X86ISD::DEC";
19312 case X86ISD::OR: return "X86ISD::OR";
19313 case X86ISD::XOR: return "X86ISD::XOR";
19314 case X86ISD::AND: return "X86ISD::AND";
19315 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19316 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19317 case X86ISD::PTEST: return "X86ISD::PTEST";
19318 case X86ISD::TESTP: return "X86ISD::TESTP";
19319 case X86ISD::TESTM: return "X86ISD::TESTM";
19320 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19321 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19322 case X86ISD::KTEST: return "X86ISD::KTEST";
19323 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19324 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19325 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19326 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19327 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19328 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19329 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19330 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19331 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19332 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19333 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19334 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19335 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19336 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19337 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19338 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19339 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19340 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19341 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19342 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19343 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19344 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19345 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19346 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19347 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19348 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19349 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19350 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19351 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19352 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19353 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19354 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19355 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19356 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19357 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19358 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19359 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19360 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19361 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19362 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19363 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19364 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19365 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19366 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19367 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19368 case X86ISD::SAHF: return "X86ISD::SAHF";
19369 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19370 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19371 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19372 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19373 case X86ISD::FMADD: return "X86ISD::FMADD";
19374 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19375 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19376 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19377 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19378 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19379 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19380 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19381 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19382 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19383 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19384 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19385 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19386 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19387 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19388 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19389 case X86ISD::XTEST: return "X86ISD::XTEST";
19390 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19391 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19392 case X86ISD::SELECT: return "X86ISD::SELECT";
19393 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19394 case X86ISD::RCP28: return "X86ISD::RCP28";
19395 case X86ISD::EXP2: return "X86ISD::EXP2";
19396 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19397 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19398 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19399 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19400 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19401 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19402 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19403 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19404 case X86ISD::ADDS: return "X86ISD::ADDS";
19405 case X86ISD::SUBS: return "X86ISD::SUBS";
19406 case X86ISD::AVG: return "X86ISD::AVG";
19407 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19408 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19409 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19410 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19411 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19416 // isLegalAddressingMode - Return true if the addressing mode represented
19417 // by AM is legal for this target, for a load/store of the specified type.
19418 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19419 const AddrMode &AM, Type *Ty,
19420 unsigned AS) const {
19421 // X86 supports extremely general addressing modes.
19422 CodeModel::Model M = getTargetMachine().getCodeModel();
19423 Reloc::Model R = getTargetMachine().getRelocationModel();
19425 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19426 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19431 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19433 // If a reference to this global requires an extra load, we can't fold it.
19434 if (isGlobalStubReference(GVFlags))
19437 // If BaseGV requires a register for the PIC base, we cannot also have a
19438 // BaseReg specified.
19439 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19442 // If lower 4G is not available, then we must use rip-relative addressing.
19443 if ((M != CodeModel::Small || R != Reloc::Static) &&
19444 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19448 switch (AM.Scale) {
19454 // These scales always work.
19459 // These scales are formed with basereg+scalereg. Only accept if there is
19464 default: // Other stuff never works.
19471 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19472 unsigned Bits = Ty->getScalarSizeInBits();
19474 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19475 // particularly cheaper than those without.
19479 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19480 // variable shifts just as cheap as scalar ones.
19481 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19484 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19485 // fully general vector.
19489 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19490 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19492 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19493 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19494 return NumBits1 > NumBits2;
19497 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19498 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19501 if (!isTypeLegal(EVT::getEVT(Ty1)))
19504 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19506 // Assuming the caller doesn't have a zeroext or signext return parameter,
19507 // truncation all the way down to i1 is valid.
19511 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19512 return isInt<32>(Imm);
19515 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19516 // Can also use sub to handle negated immediates.
19517 return isInt<32>(Imm);
19520 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19521 if (!VT1.isInteger() || !VT2.isInteger())
19523 unsigned NumBits1 = VT1.getSizeInBits();
19524 unsigned NumBits2 = VT2.getSizeInBits();
19525 return NumBits1 > NumBits2;
19528 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19529 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19530 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19533 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19534 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19535 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19538 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19539 EVT VT1 = Val.getValueType();
19540 if (isZExtFree(VT1, VT2))
19543 if (Val.getOpcode() != ISD::LOAD)
19546 if (!VT1.isSimple() || !VT1.isInteger() ||
19547 !VT2.isSimple() || !VT2.isInteger())
19550 switch (VT1.getSimpleVT().SimpleTy) {
19555 // X86 has 8, 16, and 32-bit zero-extending loads.
19562 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19565 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19566 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19569 VT = VT.getScalarType();
19571 if (!VT.isSimple())
19574 switch (VT.getSimpleVT().SimpleTy) {
19585 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19586 // i16 instructions are longer (0x66 prefix) and potentially slower.
19587 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19590 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19591 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19592 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19593 /// are assumed to be legal.
19595 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19597 if (!VT.isSimple())
19600 // Not for i1 vectors
19601 if (VT.getScalarType() == MVT::i1)
19604 // Very little shuffling can be done for 64-bit vectors right now.
19605 if (VT.getSizeInBits() == 64)
19608 // We only care that the types being shuffled are legal. The lowering can
19609 // handle any possible shuffle mask that results.
19610 return isTypeLegal(VT.getSimpleVT());
19614 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19616 // Just delegate to the generic legality, clear masks aren't special.
19617 return isShuffleMaskLegal(Mask, VT);
19620 //===----------------------------------------------------------------------===//
19621 // X86 Scheduler Hooks
19622 //===----------------------------------------------------------------------===//
19624 /// Utility function to emit xbegin specifying the start of an RTM region.
19625 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19626 const TargetInstrInfo *TII) {
19627 DebugLoc DL = MI->getDebugLoc();
19629 const BasicBlock *BB = MBB->getBasicBlock();
19630 MachineFunction::iterator I = MBB;
19633 // For the v = xbegin(), we generate
19644 MachineBasicBlock *thisMBB = MBB;
19645 MachineFunction *MF = MBB->getParent();
19646 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19647 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19648 MF->insert(I, mainMBB);
19649 MF->insert(I, sinkMBB);
19651 // Transfer the remainder of BB and its successor edges to sinkMBB.
19652 sinkMBB->splice(sinkMBB->begin(), MBB,
19653 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19654 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19658 // # fallthrough to mainMBB
19659 // # abortion to sinkMBB
19660 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19661 thisMBB->addSuccessor(mainMBB);
19662 thisMBB->addSuccessor(sinkMBB);
19666 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19667 mainMBB->addSuccessor(sinkMBB);
19670 // EAX is live into the sinkMBB
19671 sinkMBB->addLiveIn(X86::EAX);
19672 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19673 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19676 MI->eraseFromParent();
19680 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19681 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19682 // in the .td file.
19683 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19684 const TargetInstrInfo *TII) {
19686 switch (MI->getOpcode()) {
19687 default: llvm_unreachable("illegal opcode!");
19688 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19689 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19690 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19691 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19692 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19693 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19694 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19695 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19698 DebugLoc dl = MI->getDebugLoc();
19699 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19701 unsigned NumArgs = MI->getNumOperands();
19702 for (unsigned i = 1; i < NumArgs; ++i) {
19703 MachineOperand &Op = MI->getOperand(i);
19704 if (!(Op.isReg() && Op.isImplicit()))
19705 MIB.addOperand(Op);
19707 if (MI->hasOneMemOperand())
19708 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19710 BuildMI(*BB, MI, dl,
19711 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19712 .addReg(X86::XMM0);
19714 MI->eraseFromParent();
19718 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19719 // defs in an instruction pattern
19720 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19721 const TargetInstrInfo *TII) {
19723 switch (MI->getOpcode()) {
19724 default: llvm_unreachable("illegal opcode!");
19725 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19726 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19727 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19728 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19729 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19730 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19731 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19732 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19735 DebugLoc dl = MI->getDebugLoc();
19736 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19738 unsigned NumArgs = MI->getNumOperands(); // remove the results
19739 for (unsigned i = 1; i < NumArgs; ++i) {
19740 MachineOperand &Op = MI->getOperand(i);
19741 if (!(Op.isReg() && Op.isImplicit()))
19742 MIB.addOperand(Op);
19744 if (MI->hasOneMemOperand())
19745 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19747 BuildMI(*BB, MI, dl,
19748 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19751 MI->eraseFromParent();
19755 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19756 const X86Subtarget *Subtarget) {
19757 DebugLoc dl = MI->getDebugLoc();
19758 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19759 // Address into RAX/EAX, other two args into ECX, EDX.
19760 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19761 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19762 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19763 for (int i = 0; i < X86::AddrNumOperands; ++i)
19764 MIB.addOperand(MI->getOperand(i));
19766 unsigned ValOps = X86::AddrNumOperands;
19767 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19768 .addReg(MI->getOperand(ValOps).getReg());
19769 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19770 .addReg(MI->getOperand(ValOps+1).getReg());
19772 // The instruction doesn't actually take any operands though.
19773 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19775 MI->eraseFromParent(); // The pseudo is gone now.
19779 MachineBasicBlock *
19780 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19781 MachineBasicBlock *MBB) const {
19782 // Emit va_arg instruction on X86-64.
19784 // Operands to this pseudo-instruction:
19785 // 0 ) Output : destination address (reg)
19786 // 1-5) Input : va_list address (addr, i64mem)
19787 // 6 ) ArgSize : Size (in bytes) of vararg type
19788 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19789 // 8 ) Align : Alignment of type
19790 // 9 ) EFLAGS (implicit-def)
19792 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19793 static_assert(X86::AddrNumOperands == 5,
19794 "VAARG_64 assumes 5 address operands");
19796 unsigned DestReg = MI->getOperand(0).getReg();
19797 MachineOperand &Base = MI->getOperand(1);
19798 MachineOperand &Scale = MI->getOperand(2);
19799 MachineOperand &Index = MI->getOperand(3);
19800 MachineOperand &Disp = MI->getOperand(4);
19801 MachineOperand &Segment = MI->getOperand(5);
19802 unsigned ArgSize = MI->getOperand(6).getImm();
19803 unsigned ArgMode = MI->getOperand(7).getImm();
19804 unsigned Align = MI->getOperand(8).getImm();
19806 // Memory Reference
19807 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19808 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19809 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19811 // Machine Information
19812 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19813 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19814 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19815 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19816 DebugLoc DL = MI->getDebugLoc();
19818 // struct va_list {
19821 // i64 overflow_area (address)
19822 // i64 reg_save_area (address)
19824 // sizeof(va_list) = 24
19825 // alignment(va_list) = 8
19827 unsigned TotalNumIntRegs = 6;
19828 unsigned TotalNumXMMRegs = 8;
19829 bool UseGPOffset = (ArgMode == 1);
19830 bool UseFPOffset = (ArgMode == 2);
19831 unsigned MaxOffset = TotalNumIntRegs * 8 +
19832 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19834 /* Align ArgSize to a multiple of 8 */
19835 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19836 bool NeedsAlign = (Align > 8);
19838 MachineBasicBlock *thisMBB = MBB;
19839 MachineBasicBlock *overflowMBB;
19840 MachineBasicBlock *offsetMBB;
19841 MachineBasicBlock *endMBB;
19843 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19844 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19845 unsigned OffsetReg = 0;
19847 if (!UseGPOffset && !UseFPOffset) {
19848 // If we only pull from the overflow region, we don't create a branch.
19849 // We don't need to alter control flow.
19850 OffsetDestReg = 0; // unused
19851 OverflowDestReg = DestReg;
19853 offsetMBB = nullptr;
19854 overflowMBB = thisMBB;
19857 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19858 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19859 // If not, pull from overflow_area. (branch to overflowMBB)
19864 // offsetMBB overflowMBB
19869 // Registers for the PHI in endMBB
19870 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19871 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19873 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19874 MachineFunction *MF = MBB->getParent();
19875 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19876 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19877 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19879 MachineFunction::iterator MBBIter = MBB;
19882 // Insert the new basic blocks
19883 MF->insert(MBBIter, offsetMBB);
19884 MF->insert(MBBIter, overflowMBB);
19885 MF->insert(MBBIter, endMBB);
19887 // Transfer the remainder of MBB and its successor edges to endMBB.
19888 endMBB->splice(endMBB->begin(), thisMBB,
19889 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19890 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19892 // Make offsetMBB and overflowMBB successors of thisMBB
19893 thisMBB->addSuccessor(offsetMBB);
19894 thisMBB->addSuccessor(overflowMBB);
19896 // endMBB is a successor of both offsetMBB and overflowMBB
19897 offsetMBB->addSuccessor(endMBB);
19898 overflowMBB->addSuccessor(endMBB);
19900 // Load the offset value into a register
19901 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19902 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19906 .addDisp(Disp, UseFPOffset ? 4 : 0)
19907 .addOperand(Segment)
19908 .setMemRefs(MMOBegin, MMOEnd);
19910 // Check if there is enough room left to pull this argument.
19911 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19913 .addImm(MaxOffset + 8 - ArgSizeA8);
19915 // Branch to "overflowMBB" if offset >= max
19916 // Fall through to "offsetMBB" otherwise
19917 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19918 .addMBB(overflowMBB);
19921 // In offsetMBB, emit code to use the reg_save_area.
19923 assert(OffsetReg != 0);
19925 // Read the reg_save_area address.
19926 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19927 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19932 .addOperand(Segment)
19933 .setMemRefs(MMOBegin, MMOEnd);
19935 // Zero-extend the offset
19936 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19937 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19940 .addImm(X86::sub_32bit);
19942 // Add the offset to the reg_save_area to get the final address.
19943 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19944 .addReg(OffsetReg64)
19945 .addReg(RegSaveReg);
19947 // Compute the offset for the next argument
19948 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19949 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19951 .addImm(UseFPOffset ? 16 : 8);
19953 // Store it back into the va_list.
19954 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19958 .addDisp(Disp, UseFPOffset ? 4 : 0)
19959 .addOperand(Segment)
19960 .addReg(NextOffsetReg)
19961 .setMemRefs(MMOBegin, MMOEnd);
19964 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19969 // Emit code to use overflow area
19972 // Load the overflow_area address into a register.
19973 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19974 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19979 .addOperand(Segment)
19980 .setMemRefs(MMOBegin, MMOEnd);
19982 // If we need to align it, do so. Otherwise, just copy the address
19983 // to OverflowDestReg.
19985 // Align the overflow address
19986 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19987 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19989 // aligned_addr = (addr + (align-1)) & ~(align-1)
19990 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19991 .addReg(OverflowAddrReg)
19994 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19996 .addImm(~(uint64_t)(Align-1));
19998 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19999 .addReg(OverflowAddrReg);
20002 // Compute the next overflow address after this argument.
20003 // (the overflow address should be kept 8-byte aligned)
20004 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20005 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20006 .addReg(OverflowDestReg)
20007 .addImm(ArgSizeA8);
20009 // Store the new overflow address.
20010 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20015 .addOperand(Segment)
20016 .addReg(NextAddrReg)
20017 .setMemRefs(MMOBegin, MMOEnd);
20019 // If we branched, emit the PHI to the front of endMBB.
20021 BuildMI(*endMBB, endMBB->begin(), DL,
20022 TII->get(X86::PHI), DestReg)
20023 .addReg(OffsetDestReg).addMBB(offsetMBB)
20024 .addReg(OverflowDestReg).addMBB(overflowMBB);
20027 // Erase the pseudo instruction
20028 MI->eraseFromParent();
20033 MachineBasicBlock *
20034 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20036 MachineBasicBlock *MBB) const {
20037 // Emit code to save XMM registers to the stack. The ABI says that the
20038 // number of registers to save is given in %al, so it's theoretically
20039 // possible to do an indirect jump trick to avoid saving all of them,
20040 // however this code takes a simpler approach and just executes all
20041 // of the stores if %al is non-zero. It's less code, and it's probably
20042 // easier on the hardware branch predictor, and stores aren't all that
20043 // expensive anyway.
20045 // Create the new basic blocks. One block contains all the XMM stores,
20046 // and one block is the final destination regardless of whether any
20047 // stores were performed.
20048 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20049 MachineFunction *F = MBB->getParent();
20050 MachineFunction::iterator MBBIter = MBB;
20052 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20053 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20054 F->insert(MBBIter, XMMSaveMBB);
20055 F->insert(MBBIter, EndMBB);
20057 // Transfer the remainder of MBB and its successor edges to EndMBB.
20058 EndMBB->splice(EndMBB->begin(), MBB,
20059 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20060 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20062 // The original block will now fall through to the XMM save block.
20063 MBB->addSuccessor(XMMSaveMBB);
20064 // The XMMSaveMBB will fall through to the end block.
20065 XMMSaveMBB->addSuccessor(EndMBB);
20067 // Now add the instructions.
20068 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20069 DebugLoc DL = MI->getDebugLoc();
20071 unsigned CountReg = MI->getOperand(0).getReg();
20072 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20073 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20075 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20076 // If %al is 0, branch around the XMM save block.
20077 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20078 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20079 MBB->addSuccessor(EndMBB);
20082 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20083 // that was just emitted, but clearly shouldn't be "saved".
20084 assert((MI->getNumOperands() <= 3 ||
20085 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20086 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20087 && "Expected last argument to be EFLAGS");
20088 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20089 // In the XMM save block, save all the XMM argument registers.
20090 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20091 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20092 MachineMemOperand *MMO = F->getMachineMemOperand(
20093 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20094 MachineMemOperand::MOStore,
20095 /*Size=*/16, /*Align=*/16);
20096 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20097 .addFrameIndex(RegSaveFrameIndex)
20098 .addImm(/*Scale=*/1)
20099 .addReg(/*IndexReg=*/0)
20100 .addImm(/*Disp=*/Offset)
20101 .addReg(/*Segment=*/0)
20102 .addReg(MI->getOperand(i).getReg())
20103 .addMemOperand(MMO);
20106 MI->eraseFromParent(); // The pseudo instruction is gone now.
20111 // The EFLAGS operand of SelectItr might be missing a kill marker
20112 // because there were multiple uses of EFLAGS, and ISel didn't know
20113 // which to mark. Figure out whether SelectItr should have had a
20114 // kill marker, and set it if it should. Returns the correct kill
20116 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20117 MachineBasicBlock* BB,
20118 const TargetRegisterInfo* TRI) {
20119 // Scan forward through BB for a use/def of EFLAGS.
20120 MachineBasicBlock::iterator miI(std::next(SelectItr));
20121 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20122 const MachineInstr& mi = *miI;
20123 if (mi.readsRegister(X86::EFLAGS))
20125 if (mi.definesRegister(X86::EFLAGS))
20126 break; // Should have kill-flag - update below.
20129 // If we hit the end of the block, check whether EFLAGS is live into a
20131 if (miI == BB->end()) {
20132 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20133 sEnd = BB->succ_end();
20134 sItr != sEnd; ++sItr) {
20135 MachineBasicBlock* succ = *sItr;
20136 if (succ->isLiveIn(X86::EFLAGS))
20141 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20142 // out. SelectMI should have a kill flag on EFLAGS.
20143 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20147 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20148 // together with other CMOV pseudo-opcodes into a single basic-block with
20149 // conditional jump around it.
20150 static bool isCMOVPseudo(MachineInstr *MI) {
20151 switch (MI->getOpcode()) {
20152 case X86::CMOV_FR32:
20153 case X86::CMOV_FR64:
20154 case X86::CMOV_GR8:
20155 case X86::CMOV_GR16:
20156 case X86::CMOV_GR32:
20157 case X86::CMOV_RFP32:
20158 case X86::CMOV_RFP64:
20159 case X86::CMOV_RFP80:
20160 case X86::CMOV_V2F64:
20161 case X86::CMOV_V2I64:
20162 case X86::CMOV_V4F32:
20163 case X86::CMOV_V4F64:
20164 case X86::CMOV_V4I64:
20165 case X86::CMOV_V16F32:
20166 case X86::CMOV_V8F32:
20167 case X86::CMOV_V8F64:
20168 case X86::CMOV_V8I64:
20169 case X86::CMOV_V8I1:
20170 case X86::CMOV_V16I1:
20171 case X86::CMOV_V32I1:
20172 case X86::CMOV_V64I1:
20180 MachineBasicBlock *
20181 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20182 MachineBasicBlock *BB) const {
20183 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20184 DebugLoc DL = MI->getDebugLoc();
20186 // To "insert" a SELECT_CC instruction, we actually have to insert the
20187 // diamond control-flow pattern. The incoming instruction knows the
20188 // destination vreg to set, the condition code register to branch on, the
20189 // true/false values to select between, and a branch opcode to use.
20190 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20191 MachineFunction::iterator It = BB;
20197 // cmpTY ccX, r1, r2
20199 // fallthrough --> copy0MBB
20200 MachineBasicBlock *thisMBB = BB;
20201 MachineFunction *F = BB->getParent();
20203 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20204 // as described above, by inserting a BB, and then making a PHI at the join
20205 // point to select the true and false operands of the CMOV in the PHI.
20207 // The code also handles two different cases of multiple CMOV opcodes
20211 // In this case, there are multiple CMOVs in a row, all which are based on
20212 // the same condition setting (or the exact opposite condition setting).
20213 // In this case we can lower all the CMOVs using a single inserted BB, and
20214 // then make a number of PHIs at the join point to model the CMOVs. The only
20215 // trickiness here, is that in a case like:
20217 // t2 = CMOV cond1 t1, f1
20218 // t3 = CMOV cond1 t2, f2
20220 // when rewriting this into PHIs, we have to perform some renaming on the
20221 // temps since you cannot have a PHI operand refer to a PHI result earlier
20222 // in the same block. The "simple" but wrong lowering would be:
20224 // t2 = PHI t1(BB1), f1(BB2)
20225 // t3 = PHI t2(BB1), f2(BB2)
20227 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20228 // renaming is to note that on the path through BB1, t2 is really just a
20229 // copy of t1, and do that renaming, properly generating:
20231 // t2 = PHI t1(BB1), f1(BB2)
20232 // t3 = PHI t1(BB1), f2(BB2)
20234 // Case 2, we lower cascaded CMOVs such as
20236 // (CMOV (CMOV F, T, cc1), T, cc2)
20238 // to two successives branches. For that, we look for another CMOV as the
20239 // following instruction.
20241 // Without this, we would add a PHI between the two jumps, which ends up
20242 // creating a few copies all around. For instance, for
20244 // (sitofp (zext (fcmp une)))
20246 // we would generate:
20248 // ucomiss %xmm1, %xmm0
20249 // movss <1.0f>, %xmm0
20250 // movaps %xmm0, %xmm1
20252 // xorps %xmm1, %xmm1
20255 // movaps %xmm1, %xmm0
20259 // because this custom-inserter would have generated:
20271 // A: X = ...; Y = ...
20273 // C: Z = PHI [X, A], [Y, B]
20275 // E: PHI [X, C], [Z, D]
20277 // If we lower both CMOVs in a single step, we can instead generate:
20289 // A: X = ...; Y = ...
20291 // E: PHI [X, A], [X, C], [Y, D]
20293 // Which, in our sitofp/fcmp example, gives us something like:
20295 // ucomiss %xmm1, %xmm0
20296 // movss <1.0f>, %xmm0
20299 // xorps %xmm0, %xmm0
20303 MachineInstr *CascadedCMOV = nullptr;
20304 MachineInstr *LastCMOV = MI;
20305 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20306 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20307 MachineBasicBlock::iterator NextMIIt =
20308 std::next(MachineBasicBlock::iterator(MI));
20310 // Check for case 1, where there are multiple CMOVs with the same condition
20311 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20312 // number of jumps the most.
20314 if (isCMOVPseudo(MI)) {
20315 // See if we have a string of CMOVS with the same condition.
20316 while (NextMIIt != BB->end() &&
20317 isCMOVPseudo(NextMIIt) &&
20318 (NextMIIt->getOperand(3).getImm() == CC ||
20319 NextMIIt->getOperand(3).getImm() == OppCC)) {
20320 LastCMOV = &*NextMIIt;
20325 // This checks for case 2, but only do this if we didn't already find
20326 // case 1, as indicated by LastCMOV == MI.
20327 if (LastCMOV == MI &&
20328 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20329 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20330 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20331 CascadedCMOV = &*NextMIIt;
20334 MachineBasicBlock *jcc1MBB = nullptr;
20336 // If we have a cascaded CMOV, we lower it to two successive branches to
20337 // the same block. EFLAGS is used by both, so mark it as live in the second.
20338 if (CascadedCMOV) {
20339 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20340 F->insert(It, jcc1MBB);
20341 jcc1MBB->addLiveIn(X86::EFLAGS);
20344 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20345 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20346 F->insert(It, copy0MBB);
20347 F->insert(It, sinkMBB);
20349 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20350 // live into the sink and copy blocks.
20351 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20353 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20354 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20355 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20356 copy0MBB->addLiveIn(X86::EFLAGS);
20357 sinkMBB->addLiveIn(X86::EFLAGS);
20360 // Transfer the remainder of BB and its successor edges to sinkMBB.
20361 sinkMBB->splice(sinkMBB->begin(), BB,
20362 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20363 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20365 // Add the true and fallthrough blocks as its successors.
20366 if (CascadedCMOV) {
20367 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20368 BB->addSuccessor(jcc1MBB);
20370 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20371 // jump to the sinkMBB.
20372 jcc1MBB->addSuccessor(copy0MBB);
20373 jcc1MBB->addSuccessor(sinkMBB);
20375 BB->addSuccessor(copy0MBB);
20378 // The true block target of the first (or only) branch is always sinkMBB.
20379 BB->addSuccessor(sinkMBB);
20381 // Create the conditional branch instruction.
20382 unsigned Opc = X86::GetCondBranchFromCond(CC);
20383 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20385 if (CascadedCMOV) {
20386 unsigned Opc2 = X86::GetCondBranchFromCond(
20387 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20388 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20392 // %FalseValue = ...
20393 // # fallthrough to sinkMBB
20394 copy0MBB->addSuccessor(sinkMBB);
20397 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20399 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20400 MachineBasicBlock::iterator MIItEnd =
20401 std::next(MachineBasicBlock::iterator(LastCMOV));
20402 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20403 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20404 MachineInstrBuilder MIB;
20406 // As we are creating the PHIs, we have to be careful if there is more than
20407 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20408 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20409 // That also means that PHI construction must work forward from earlier to
20410 // later, and that the code must maintain a mapping from earlier PHI's
20411 // destination registers, and the registers that went into the PHI.
20413 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20414 unsigned DestReg = MIIt->getOperand(0).getReg();
20415 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20416 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20418 // If this CMOV we are generating is the opposite condition from
20419 // the jump we generated, then we have to swap the operands for the
20420 // PHI that is going to be generated.
20421 if (MIIt->getOperand(3).getImm() == OppCC)
20422 std::swap(Op1Reg, Op2Reg);
20424 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20425 Op1Reg = RegRewriteTable[Op1Reg].first;
20427 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20428 Op2Reg = RegRewriteTable[Op2Reg].second;
20430 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20431 TII->get(X86::PHI), DestReg)
20432 .addReg(Op1Reg).addMBB(copy0MBB)
20433 .addReg(Op2Reg).addMBB(thisMBB);
20435 // Add this PHI to the rewrite table.
20436 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20439 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20440 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20441 if (CascadedCMOV) {
20442 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20443 // Copy the PHI result to the register defined by the second CMOV.
20444 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20445 DL, TII->get(TargetOpcode::COPY),
20446 CascadedCMOV->getOperand(0).getReg())
20447 .addReg(MI->getOperand(0).getReg());
20448 CascadedCMOV->eraseFromParent();
20451 // Now remove the CMOV(s).
20452 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20453 (MIIt++)->eraseFromParent();
20458 MachineBasicBlock *
20459 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20460 MachineBasicBlock *BB) const {
20461 // Combine the following atomic floating-point modification pattern:
20462 // a.store(reg OP a.load(acquire), release)
20463 // Transform them into:
20464 // OPss (%gpr), %xmm
20465 // movss %xmm, (%gpr)
20466 // Or sd equivalent for 64-bit operations.
20468 switch (MI->getOpcode()) {
20469 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20470 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20471 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20473 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20474 DebugLoc DL = MI->getDebugLoc();
20475 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20476 unsigned MSrc = MI->getOperand(0).getReg();
20477 unsigned VSrc = MI->getOperand(5).getReg();
20478 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20479 .addReg(/*Base=*/MSrc)
20480 .addImm(/*Scale=*/1)
20481 .addReg(/*Index=*/0)
20484 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20485 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20487 .addReg(/*Base=*/MSrc)
20488 .addImm(/*Scale=*/1)
20489 .addReg(/*Index=*/0)
20490 .addImm(/*Disp=*/0)
20491 .addReg(/*Segment=*/0);
20492 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20493 MI->eraseFromParent(); // The pseudo instruction is gone now.
20497 MachineBasicBlock *
20498 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20499 MachineBasicBlock *BB) const {
20500 MachineFunction *MF = BB->getParent();
20501 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20502 DebugLoc DL = MI->getDebugLoc();
20503 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20505 assert(MF->shouldSplitStack());
20507 const bool Is64Bit = Subtarget->is64Bit();
20508 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20510 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20511 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20514 // ... [Till the alloca]
20515 // If stacklet is not large enough, jump to mallocMBB
20518 // Allocate by subtracting from RSP
20519 // Jump to continueMBB
20522 // Allocate by call to runtime
20526 // [rest of original BB]
20529 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20530 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20531 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20533 MachineRegisterInfo &MRI = MF->getRegInfo();
20534 const TargetRegisterClass *AddrRegClass =
20535 getRegClassFor(getPointerTy(MF->getDataLayout()));
20537 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20538 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20539 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20540 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20541 sizeVReg = MI->getOperand(1).getReg(),
20542 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20544 MachineFunction::iterator MBBIter = BB;
20547 MF->insert(MBBIter, bumpMBB);
20548 MF->insert(MBBIter, mallocMBB);
20549 MF->insert(MBBIter, continueMBB);
20551 continueMBB->splice(continueMBB->begin(), BB,
20552 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20553 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20555 // Add code to the main basic block to check if the stack limit has been hit,
20556 // and if so, jump to mallocMBB otherwise to bumpMBB.
20557 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20558 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20559 .addReg(tmpSPVReg).addReg(sizeVReg);
20560 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20561 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20562 .addReg(SPLimitVReg);
20563 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20565 // bumpMBB simply decreases the stack pointer, since we know the current
20566 // stacklet has enough space.
20567 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20568 .addReg(SPLimitVReg);
20569 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20570 .addReg(SPLimitVReg);
20571 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20573 // Calls into a routine in libgcc to allocate more space from the heap.
20574 const uint32_t *RegMask =
20575 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20577 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20579 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20580 .addExternalSymbol("__morestack_allocate_stack_space")
20581 .addRegMask(RegMask)
20582 .addReg(X86::RDI, RegState::Implicit)
20583 .addReg(X86::RAX, RegState::ImplicitDefine);
20584 } else if (Is64Bit) {
20585 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20587 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20588 .addExternalSymbol("__morestack_allocate_stack_space")
20589 .addRegMask(RegMask)
20590 .addReg(X86::EDI, RegState::Implicit)
20591 .addReg(X86::EAX, RegState::ImplicitDefine);
20593 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20595 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20596 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20597 .addExternalSymbol("__morestack_allocate_stack_space")
20598 .addRegMask(RegMask)
20599 .addReg(X86::EAX, RegState::ImplicitDefine);
20603 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20606 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20607 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20608 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20610 // Set up the CFG correctly.
20611 BB->addSuccessor(bumpMBB);
20612 BB->addSuccessor(mallocMBB);
20613 mallocMBB->addSuccessor(continueMBB);
20614 bumpMBB->addSuccessor(continueMBB);
20616 // Take care of the PHI nodes.
20617 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20618 MI->getOperand(0).getReg())
20619 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20620 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20622 // Delete the original pseudo instruction.
20623 MI->eraseFromParent();
20626 return continueMBB;
20629 MachineBasicBlock *
20630 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20631 MachineBasicBlock *BB) const {
20632 DebugLoc DL = MI->getDebugLoc();
20634 assert(!Subtarget->isTargetMachO());
20636 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20639 MI->eraseFromParent(); // The pseudo instruction is gone now.
20643 MachineBasicBlock *
20644 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20645 MachineBasicBlock *BB) const {
20646 // This is pretty easy. We're taking the value that we received from
20647 // our load from the relocation, sticking it in either RDI (x86-64)
20648 // or EAX and doing an indirect call. The return value will then
20649 // be in the normal return register.
20650 MachineFunction *F = BB->getParent();
20651 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20652 DebugLoc DL = MI->getDebugLoc();
20654 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20655 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20657 // Get a register mask for the lowered call.
20658 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20659 // proper register mask.
20660 const uint32_t *RegMask =
20661 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20662 if (Subtarget->is64Bit()) {
20663 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20664 TII->get(X86::MOV64rm), X86::RDI)
20666 .addImm(0).addReg(0)
20667 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20668 MI->getOperand(3).getTargetFlags())
20670 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20671 addDirectMem(MIB, X86::RDI);
20672 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20673 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20674 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20675 TII->get(X86::MOV32rm), X86::EAX)
20677 .addImm(0).addReg(0)
20678 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20679 MI->getOperand(3).getTargetFlags())
20681 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20682 addDirectMem(MIB, X86::EAX);
20683 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20685 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20686 TII->get(X86::MOV32rm), X86::EAX)
20687 .addReg(TII->getGlobalBaseReg(F))
20688 .addImm(0).addReg(0)
20689 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20690 MI->getOperand(3).getTargetFlags())
20692 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20693 addDirectMem(MIB, X86::EAX);
20694 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20697 MI->eraseFromParent(); // The pseudo instruction is gone now.
20701 MachineBasicBlock *
20702 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20703 MachineBasicBlock *MBB) const {
20704 DebugLoc DL = MI->getDebugLoc();
20705 MachineFunction *MF = MBB->getParent();
20706 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20707 MachineRegisterInfo &MRI = MF->getRegInfo();
20709 const BasicBlock *BB = MBB->getBasicBlock();
20710 MachineFunction::iterator I = MBB;
20713 // Memory Reference
20714 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20715 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20718 unsigned MemOpndSlot = 0;
20720 unsigned CurOp = 0;
20722 DstReg = MI->getOperand(CurOp++).getReg();
20723 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20724 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20725 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20726 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20728 MemOpndSlot = CurOp;
20730 MVT PVT = getPointerTy(MF->getDataLayout());
20731 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20732 "Invalid Pointer Size!");
20734 // For v = setjmp(buf), we generate
20737 // buf[LabelOffset] = restoreMBB
20738 // SjLjSetup restoreMBB
20744 // v = phi(main, restore)
20747 // if base pointer being used, load it from frame
20750 MachineBasicBlock *thisMBB = MBB;
20751 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20752 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20753 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20754 MF->insert(I, mainMBB);
20755 MF->insert(I, sinkMBB);
20756 MF->push_back(restoreMBB);
20758 MachineInstrBuilder MIB;
20760 // Transfer the remainder of BB and its successor edges to sinkMBB.
20761 sinkMBB->splice(sinkMBB->begin(), MBB,
20762 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20763 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20766 unsigned PtrStoreOpc = 0;
20767 unsigned LabelReg = 0;
20768 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20769 Reloc::Model RM = MF->getTarget().getRelocationModel();
20770 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20771 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20773 // Prepare IP either in reg or imm.
20774 if (!UseImmLabel) {
20775 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20776 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20777 LabelReg = MRI.createVirtualRegister(PtrRC);
20778 if (Subtarget->is64Bit()) {
20779 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20783 .addMBB(restoreMBB)
20786 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20787 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20788 .addReg(XII->getGlobalBaseReg(MF))
20791 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20795 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20797 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20798 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20799 if (i == X86::AddrDisp)
20800 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20802 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20805 MIB.addReg(LabelReg);
20807 MIB.addMBB(restoreMBB);
20808 MIB.setMemRefs(MMOBegin, MMOEnd);
20810 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20811 .addMBB(restoreMBB);
20813 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20814 MIB.addRegMask(RegInfo->getNoPreservedMask());
20815 thisMBB->addSuccessor(mainMBB);
20816 thisMBB->addSuccessor(restoreMBB);
20820 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20821 mainMBB->addSuccessor(sinkMBB);
20824 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20825 TII->get(X86::PHI), DstReg)
20826 .addReg(mainDstReg).addMBB(mainMBB)
20827 .addReg(restoreDstReg).addMBB(restoreMBB);
20830 if (RegInfo->hasBasePointer(*MF)) {
20831 const bool Uses64BitFramePtr =
20832 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20833 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20834 X86FI->setRestoreBasePointer(MF);
20835 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20836 unsigned BasePtr = RegInfo->getBaseRegister();
20837 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20838 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20839 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20840 .setMIFlag(MachineInstr::FrameSetup);
20842 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20843 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20844 restoreMBB->addSuccessor(sinkMBB);
20846 MI->eraseFromParent();
20850 MachineBasicBlock *
20851 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20852 MachineBasicBlock *MBB) const {
20853 DebugLoc DL = MI->getDebugLoc();
20854 MachineFunction *MF = MBB->getParent();
20855 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20856 MachineRegisterInfo &MRI = MF->getRegInfo();
20858 // Memory Reference
20859 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20860 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20862 MVT PVT = getPointerTy(MF->getDataLayout());
20863 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20864 "Invalid Pointer Size!");
20866 const TargetRegisterClass *RC =
20867 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20868 unsigned Tmp = MRI.createVirtualRegister(RC);
20869 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20870 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20871 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20872 unsigned SP = RegInfo->getStackRegister();
20874 MachineInstrBuilder MIB;
20876 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20877 const int64_t SPOffset = 2 * PVT.getStoreSize();
20879 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20880 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20883 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20884 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20885 MIB.addOperand(MI->getOperand(i));
20886 MIB.setMemRefs(MMOBegin, MMOEnd);
20888 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20889 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20890 if (i == X86::AddrDisp)
20891 MIB.addDisp(MI->getOperand(i), LabelOffset);
20893 MIB.addOperand(MI->getOperand(i));
20895 MIB.setMemRefs(MMOBegin, MMOEnd);
20897 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20898 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20899 if (i == X86::AddrDisp)
20900 MIB.addDisp(MI->getOperand(i), SPOffset);
20902 MIB.addOperand(MI->getOperand(i));
20904 MIB.setMemRefs(MMOBegin, MMOEnd);
20906 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20908 MI->eraseFromParent();
20912 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20913 // accumulator loops. Writing back to the accumulator allows the coalescer
20914 // to remove extra copies in the loop.
20915 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20916 MachineBasicBlock *
20917 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20918 MachineBasicBlock *MBB) const {
20919 MachineOperand &AddendOp = MI->getOperand(3);
20921 // Bail out early if the addend isn't a register - we can't switch these.
20922 if (!AddendOp.isReg())
20925 MachineFunction &MF = *MBB->getParent();
20926 MachineRegisterInfo &MRI = MF.getRegInfo();
20928 // Check whether the addend is defined by a PHI:
20929 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20930 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20931 if (!AddendDef.isPHI())
20934 // Look for the following pattern:
20936 // %addend = phi [%entry, 0], [%loop, %result]
20938 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20942 // %addend = phi [%entry, 0], [%loop, %result]
20944 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20946 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20947 assert(AddendDef.getOperand(i).isReg());
20948 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20949 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20950 if (&PHISrcInst == MI) {
20951 // Found a matching instruction.
20952 unsigned NewFMAOpc = 0;
20953 switch (MI->getOpcode()) {
20954 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20955 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20956 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20957 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20958 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20959 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20960 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20961 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20962 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20963 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20964 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20965 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20966 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20967 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20968 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20969 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20970 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20971 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20972 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20973 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20975 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20976 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20977 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20978 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20979 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20980 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20981 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20982 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20983 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20984 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20985 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20986 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20987 default: llvm_unreachable("Unrecognized FMA variant.");
20990 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20991 MachineInstrBuilder MIB =
20992 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20993 .addOperand(MI->getOperand(0))
20994 .addOperand(MI->getOperand(3))
20995 .addOperand(MI->getOperand(2))
20996 .addOperand(MI->getOperand(1));
20997 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20998 MI->eraseFromParent();
21005 MachineBasicBlock *
21006 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21007 MachineBasicBlock *BB) const {
21008 switch (MI->getOpcode()) {
21009 default: llvm_unreachable("Unexpected instr type to insert");
21010 case X86::TAILJMPd64:
21011 case X86::TAILJMPr64:
21012 case X86::TAILJMPm64:
21013 case X86::TAILJMPd64_REX:
21014 case X86::TAILJMPr64_REX:
21015 case X86::TAILJMPm64_REX:
21016 llvm_unreachable("TAILJMP64 would not be touched here.");
21017 case X86::TCRETURNdi64:
21018 case X86::TCRETURNri64:
21019 case X86::TCRETURNmi64:
21021 case X86::WIN_ALLOCA:
21022 return EmitLoweredWinAlloca(MI, BB);
21023 case X86::SEG_ALLOCA_32:
21024 case X86::SEG_ALLOCA_64:
21025 return EmitLoweredSegAlloca(MI, BB);
21026 case X86::TLSCall_32:
21027 case X86::TLSCall_64:
21028 return EmitLoweredTLSCall(MI, BB);
21029 case X86::CMOV_FR32:
21030 case X86::CMOV_FR64:
21031 case X86::CMOV_GR8:
21032 case X86::CMOV_GR16:
21033 case X86::CMOV_GR32:
21034 case X86::CMOV_RFP32:
21035 case X86::CMOV_RFP64:
21036 case X86::CMOV_RFP80:
21037 case X86::CMOV_V2F64:
21038 case X86::CMOV_V2I64:
21039 case X86::CMOV_V4F32:
21040 case X86::CMOV_V4F64:
21041 case X86::CMOV_V4I64:
21042 case X86::CMOV_V16F32:
21043 case X86::CMOV_V8F32:
21044 case X86::CMOV_V8F64:
21045 case X86::CMOV_V8I64:
21046 case X86::CMOV_V8I1:
21047 case X86::CMOV_V16I1:
21048 case X86::CMOV_V32I1:
21049 case X86::CMOV_V64I1:
21050 return EmitLoweredSelect(MI, BB);
21052 case X86::RELEASE_FADD32mr:
21053 case X86::RELEASE_FADD64mr:
21054 return EmitLoweredAtomicFP(MI, BB);
21056 case X86::FP32_TO_INT16_IN_MEM:
21057 case X86::FP32_TO_INT32_IN_MEM:
21058 case X86::FP32_TO_INT64_IN_MEM:
21059 case X86::FP64_TO_INT16_IN_MEM:
21060 case X86::FP64_TO_INT32_IN_MEM:
21061 case X86::FP64_TO_INT64_IN_MEM:
21062 case X86::FP80_TO_INT16_IN_MEM:
21063 case X86::FP80_TO_INT32_IN_MEM:
21064 case X86::FP80_TO_INT64_IN_MEM: {
21065 MachineFunction *F = BB->getParent();
21066 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21067 DebugLoc DL = MI->getDebugLoc();
21069 // Change the floating point control register to use "round towards zero"
21070 // mode when truncating to an integer value.
21071 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21072 addFrameReference(BuildMI(*BB, MI, DL,
21073 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21075 // Load the old value of the high byte of the control word...
21077 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21078 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21081 // Set the high part to be round to zero...
21082 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21085 // Reload the modified control word now...
21086 addFrameReference(BuildMI(*BB, MI, DL,
21087 TII->get(X86::FLDCW16m)), CWFrameIdx);
21089 // Restore the memory image of control word to original value
21090 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21093 // Get the X86 opcode to use.
21095 switch (MI->getOpcode()) {
21096 default: llvm_unreachable("illegal opcode!");
21097 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21098 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21099 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21100 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21101 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21102 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21103 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21104 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21105 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21109 MachineOperand &Op = MI->getOperand(0);
21111 AM.BaseType = X86AddressMode::RegBase;
21112 AM.Base.Reg = Op.getReg();
21114 AM.BaseType = X86AddressMode::FrameIndexBase;
21115 AM.Base.FrameIndex = Op.getIndex();
21117 Op = MI->getOperand(1);
21119 AM.Scale = Op.getImm();
21120 Op = MI->getOperand(2);
21122 AM.IndexReg = Op.getImm();
21123 Op = MI->getOperand(3);
21124 if (Op.isGlobal()) {
21125 AM.GV = Op.getGlobal();
21127 AM.Disp = Op.getImm();
21129 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21130 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21132 // Reload the original control word now.
21133 addFrameReference(BuildMI(*BB, MI, DL,
21134 TII->get(X86::FLDCW16m)), CWFrameIdx);
21136 MI->eraseFromParent(); // The pseudo instruction is gone now.
21139 // String/text processing lowering.
21140 case X86::PCMPISTRM128REG:
21141 case X86::VPCMPISTRM128REG:
21142 case X86::PCMPISTRM128MEM:
21143 case X86::VPCMPISTRM128MEM:
21144 case X86::PCMPESTRM128REG:
21145 case X86::VPCMPESTRM128REG:
21146 case X86::PCMPESTRM128MEM:
21147 case X86::VPCMPESTRM128MEM:
21148 assert(Subtarget->hasSSE42() &&
21149 "Target must have SSE4.2 or AVX features enabled");
21150 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21152 // String/text processing lowering.
21153 case X86::PCMPISTRIREG:
21154 case X86::VPCMPISTRIREG:
21155 case X86::PCMPISTRIMEM:
21156 case X86::VPCMPISTRIMEM:
21157 case X86::PCMPESTRIREG:
21158 case X86::VPCMPESTRIREG:
21159 case X86::PCMPESTRIMEM:
21160 case X86::VPCMPESTRIMEM:
21161 assert(Subtarget->hasSSE42() &&
21162 "Target must have SSE4.2 or AVX features enabled");
21163 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21165 // Thread synchronization.
21167 return EmitMonitor(MI, BB, Subtarget);
21171 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21173 case X86::VASTART_SAVE_XMM_REGS:
21174 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21176 case X86::VAARG_64:
21177 return EmitVAARG64WithCustomInserter(MI, BB);
21179 case X86::EH_SjLj_SetJmp32:
21180 case X86::EH_SjLj_SetJmp64:
21181 return emitEHSjLjSetJmp(MI, BB);
21183 case X86::EH_SjLj_LongJmp32:
21184 case X86::EH_SjLj_LongJmp64:
21185 return emitEHSjLjLongJmp(MI, BB);
21187 case TargetOpcode::STATEPOINT:
21188 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21189 // this point in the process. We diverge later.
21190 return emitPatchPoint(MI, BB);
21192 case TargetOpcode::STACKMAP:
21193 case TargetOpcode::PATCHPOINT:
21194 return emitPatchPoint(MI, BB);
21196 case X86::VFMADDPDr213r:
21197 case X86::VFMADDPSr213r:
21198 case X86::VFMADDSDr213r:
21199 case X86::VFMADDSSr213r:
21200 case X86::VFMSUBPDr213r:
21201 case X86::VFMSUBPSr213r:
21202 case X86::VFMSUBSDr213r:
21203 case X86::VFMSUBSSr213r:
21204 case X86::VFNMADDPDr213r:
21205 case X86::VFNMADDPSr213r:
21206 case X86::VFNMADDSDr213r:
21207 case X86::VFNMADDSSr213r:
21208 case X86::VFNMSUBPDr213r:
21209 case X86::VFNMSUBPSr213r:
21210 case X86::VFNMSUBSDr213r:
21211 case X86::VFNMSUBSSr213r:
21212 case X86::VFMADDSUBPDr213r:
21213 case X86::VFMADDSUBPSr213r:
21214 case X86::VFMSUBADDPDr213r:
21215 case X86::VFMSUBADDPSr213r:
21216 case X86::VFMADDPDr213rY:
21217 case X86::VFMADDPSr213rY:
21218 case X86::VFMSUBPDr213rY:
21219 case X86::VFMSUBPSr213rY:
21220 case X86::VFNMADDPDr213rY:
21221 case X86::VFNMADDPSr213rY:
21222 case X86::VFNMSUBPDr213rY:
21223 case X86::VFNMSUBPSr213rY:
21224 case X86::VFMADDSUBPDr213rY:
21225 case X86::VFMADDSUBPSr213rY:
21226 case X86::VFMSUBADDPDr213rY:
21227 case X86::VFMSUBADDPSr213rY:
21228 return emitFMA3Instr(MI, BB);
21232 //===----------------------------------------------------------------------===//
21233 // X86 Optimization Hooks
21234 //===----------------------------------------------------------------------===//
21236 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21239 const SelectionDAG &DAG,
21240 unsigned Depth) const {
21241 unsigned BitWidth = KnownZero.getBitWidth();
21242 unsigned Opc = Op.getOpcode();
21243 assert((Opc >= ISD::BUILTIN_OP_END ||
21244 Opc == ISD::INTRINSIC_WO_CHAIN ||
21245 Opc == ISD::INTRINSIC_W_CHAIN ||
21246 Opc == ISD::INTRINSIC_VOID) &&
21247 "Should use MaskedValueIsZero if you don't know whether Op"
21248 " is a target node!");
21250 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21264 // These nodes' second result is a boolean.
21265 if (Op.getResNo() == 0)
21268 case X86ISD::SETCC:
21269 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21271 case ISD::INTRINSIC_WO_CHAIN: {
21272 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21273 unsigned NumLoBits = 0;
21276 case Intrinsic::x86_sse_movmsk_ps:
21277 case Intrinsic::x86_avx_movmsk_ps_256:
21278 case Intrinsic::x86_sse2_movmsk_pd:
21279 case Intrinsic::x86_avx_movmsk_pd_256:
21280 case Intrinsic::x86_mmx_pmovmskb:
21281 case Intrinsic::x86_sse2_pmovmskb_128:
21282 case Intrinsic::x86_avx2_pmovmskb: {
21283 // High bits of movmskp{s|d}, pmovmskb are known zero.
21285 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21286 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21287 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21288 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21289 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21290 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21291 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21292 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21294 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21303 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21305 const SelectionDAG &,
21306 unsigned Depth) const {
21307 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21308 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21309 return Op.getValueType().getScalarType().getSizeInBits();
21315 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21316 /// node is a GlobalAddress + offset.
21317 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21318 const GlobalValue* &GA,
21319 int64_t &Offset) const {
21320 if (N->getOpcode() == X86ISD::Wrapper) {
21321 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21322 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21323 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21327 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21330 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21331 /// same as extracting the high 128-bit part of 256-bit vector and then
21332 /// inserting the result into the low part of a new 256-bit vector
21333 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21334 EVT VT = SVOp->getValueType(0);
21335 unsigned NumElems = VT.getVectorNumElements();
21337 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21338 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21339 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21340 SVOp->getMaskElt(j) >= 0)
21346 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21347 /// same as extracting the low 128-bit part of 256-bit vector and then
21348 /// inserting the result into the high part of a new 256-bit vector
21349 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21350 EVT VT = SVOp->getValueType(0);
21351 unsigned NumElems = VT.getVectorNumElements();
21353 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21354 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21355 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21356 SVOp->getMaskElt(j) >= 0)
21362 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21363 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21364 TargetLowering::DAGCombinerInfo &DCI,
21365 const X86Subtarget* Subtarget) {
21367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21368 SDValue V1 = SVOp->getOperand(0);
21369 SDValue V2 = SVOp->getOperand(1);
21370 EVT VT = SVOp->getValueType(0);
21371 unsigned NumElems = VT.getVectorNumElements();
21373 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21374 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21378 // V UNDEF BUILD_VECTOR UNDEF
21380 // CONCAT_VECTOR CONCAT_VECTOR
21383 // RESULT: V + zero extended
21385 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21386 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21387 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21390 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21393 // To match the shuffle mask, the first half of the mask should
21394 // be exactly the first vector, and all the rest a splat with the
21395 // first element of the second one.
21396 for (unsigned i = 0; i != NumElems/2; ++i)
21397 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21398 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21401 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21402 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21403 if (Ld->hasNUsesOfValue(1, 0)) {
21404 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21405 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21407 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21409 Ld->getPointerInfo(),
21410 Ld->getAlignment(),
21411 false/*isVolatile*/, true/*ReadMem*/,
21412 false/*WriteMem*/);
21414 // Make sure the newly-created LOAD is in the same position as Ld in
21415 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21416 // and update uses of Ld's output chain to use the TokenFactor.
21417 if (Ld->hasAnyUseOfValue(1)) {
21418 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21419 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21420 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21421 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21422 SDValue(ResNode.getNode(), 1));
21425 return DAG.getBitcast(VT, ResNode);
21429 // Emit a zeroed vector and insert the desired subvector on its
21431 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21432 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21433 return DCI.CombineTo(N, InsV);
21436 //===--------------------------------------------------------------------===//
21437 // Combine some shuffles into subvector extracts and inserts:
21440 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21441 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21442 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21443 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21444 return DCI.CombineTo(N, InsV);
21447 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21448 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21449 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21450 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21451 return DCI.CombineTo(N, InsV);
21457 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21460 /// This is the leaf of the recursive combinine below. When we have found some
21461 /// chain of single-use x86 shuffle instructions and accumulated the combined
21462 /// shuffle mask represented by them, this will try to pattern match that mask
21463 /// into either a single instruction if there is a special purpose instruction
21464 /// for this operation, or into a PSHUFB instruction which is a fully general
21465 /// instruction but should only be used to replace chains over a certain depth.
21466 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21467 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21468 TargetLowering::DAGCombinerInfo &DCI,
21469 const X86Subtarget *Subtarget) {
21470 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21472 // Find the operand that enters the chain. Note that multiple uses are OK
21473 // here, we're not going to remove the operand we find.
21474 SDValue Input = Op.getOperand(0);
21475 while (Input.getOpcode() == ISD::BITCAST)
21476 Input = Input.getOperand(0);
21478 MVT VT = Input.getSimpleValueType();
21479 MVT RootVT = Root.getSimpleValueType();
21482 // Just remove no-op shuffle masks.
21483 if (Mask.size() == 1) {
21484 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21489 // Use the float domain if the operand type is a floating point type.
21490 bool FloatDomain = VT.isFloatingPoint();
21492 // For floating point shuffles, we don't have free copies in the shuffle
21493 // instructions or the ability to load as part of the instruction, so
21494 // canonicalize their shuffles to UNPCK or MOV variants.
21496 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21497 // vectors because it can have a load folded into it that UNPCK cannot. This
21498 // doesn't preclude something switching to the shorter encoding post-RA.
21500 // FIXME: Should teach these routines about AVX vector widths.
21501 if (FloatDomain && VT.getSizeInBits() == 128) {
21502 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21503 bool Lo = Mask.equals({0, 0});
21506 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21507 // is no slower than UNPCKLPD but has the option to fold the input operand
21508 // into even an unaligned memory load.
21509 if (Lo && Subtarget->hasSSE3()) {
21510 Shuffle = X86ISD::MOVDDUP;
21511 ShuffleVT = MVT::v2f64;
21513 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21514 // than the UNPCK variants.
21515 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21516 ShuffleVT = MVT::v4f32;
21518 if (Depth == 1 && Root->getOpcode() == Shuffle)
21519 return false; // Nothing to do!
21520 Op = DAG.getBitcast(ShuffleVT, Input);
21521 DCI.AddToWorklist(Op.getNode());
21522 if (Shuffle == X86ISD::MOVDDUP)
21523 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21525 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21526 DCI.AddToWorklist(Op.getNode());
21527 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21531 if (Subtarget->hasSSE3() &&
21532 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21533 bool Lo = Mask.equals({0, 0, 2, 2});
21534 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21535 MVT ShuffleVT = MVT::v4f32;
21536 if (Depth == 1 && Root->getOpcode() == Shuffle)
21537 return false; // Nothing to do!
21538 Op = DAG.getBitcast(ShuffleVT, Input);
21539 DCI.AddToWorklist(Op.getNode());
21540 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21541 DCI.AddToWorklist(Op.getNode());
21542 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21546 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21547 bool Lo = Mask.equals({0, 0, 1, 1});
21548 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21549 MVT ShuffleVT = MVT::v4f32;
21550 if (Depth == 1 && Root->getOpcode() == Shuffle)
21551 return false; // Nothing to do!
21552 Op = DAG.getBitcast(ShuffleVT, Input);
21553 DCI.AddToWorklist(Op.getNode());
21554 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21555 DCI.AddToWorklist(Op.getNode());
21556 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21562 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21563 // variants as none of these have single-instruction variants that are
21564 // superior to the UNPCK formulation.
21565 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21566 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21567 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21568 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21570 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21571 bool Lo = Mask[0] == 0;
21572 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21573 if (Depth == 1 && Root->getOpcode() == Shuffle)
21574 return false; // Nothing to do!
21576 switch (Mask.size()) {
21578 ShuffleVT = MVT::v8i16;
21581 ShuffleVT = MVT::v16i8;
21584 llvm_unreachable("Impossible mask size!");
21586 Op = DAG.getBitcast(ShuffleVT, Input);
21587 DCI.AddToWorklist(Op.getNode());
21588 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21589 DCI.AddToWorklist(Op.getNode());
21590 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21595 // Don't try to re-form single instruction chains under any circumstances now
21596 // that we've done encoding canonicalization for them.
21600 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21601 // can replace them with a single PSHUFB instruction profitably. Intel's
21602 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21603 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21604 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21605 SmallVector<SDValue, 16> PSHUFBMask;
21606 int NumBytes = VT.getSizeInBits() / 8;
21607 int Ratio = NumBytes / Mask.size();
21608 for (int i = 0; i < NumBytes; ++i) {
21609 if (Mask[i / Ratio] == SM_SentinelUndef) {
21610 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21613 int M = Mask[i / Ratio] != SM_SentinelZero
21614 ? Ratio * Mask[i / Ratio] + i % Ratio
21616 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21618 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21619 Op = DAG.getBitcast(ByteVT, Input);
21620 DCI.AddToWorklist(Op.getNode());
21621 SDValue PSHUFBMaskOp =
21622 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21623 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21624 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21625 DCI.AddToWorklist(Op.getNode());
21626 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21631 // Failed to find any combines.
21635 /// \brief Fully generic combining of x86 shuffle instructions.
21637 /// This should be the last combine run over the x86 shuffle instructions. Once
21638 /// they have been fully optimized, this will recursively consider all chains
21639 /// of single-use shuffle instructions, build a generic model of the cumulative
21640 /// shuffle operation, and check for simpler instructions which implement this
21641 /// operation. We use this primarily for two purposes:
21643 /// 1) Collapse generic shuffles to specialized single instructions when
21644 /// equivalent. In most cases, this is just an encoding size win, but
21645 /// sometimes we will collapse multiple generic shuffles into a single
21646 /// special-purpose shuffle.
21647 /// 2) Look for sequences of shuffle instructions with 3 or more total
21648 /// instructions, and replace them with the slightly more expensive SSSE3
21649 /// PSHUFB instruction if available. We do this as the last combining step
21650 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21651 /// a suitable short sequence of other instructions. The PHUFB will either
21652 /// use a register or have to read from memory and so is slightly (but only
21653 /// slightly) more expensive than the other shuffle instructions.
21655 /// Because this is inherently a quadratic operation (for each shuffle in
21656 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21657 /// This should never be an issue in practice as the shuffle lowering doesn't
21658 /// produce sequences of more than 8 instructions.
21660 /// FIXME: We will currently miss some cases where the redundant shuffling
21661 /// would simplify under the threshold for PSHUFB formation because of
21662 /// combine-ordering. To fix this, we should do the redundant instruction
21663 /// combining in this recursive walk.
21664 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21665 ArrayRef<int> RootMask,
21666 int Depth, bool HasPSHUFB,
21668 TargetLowering::DAGCombinerInfo &DCI,
21669 const X86Subtarget *Subtarget) {
21670 // Bound the depth of our recursive combine because this is ultimately
21671 // quadratic in nature.
21675 // Directly rip through bitcasts to find the underlying operand.
21676 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21677 Op = Op.getOperand(0);
21679 MVT VT = Op.getSimpleValueType();
21680 if (!VT.isVector())
21681 return false; // Bail if we hit a non-vector.
21683 assert(Root.getSimpleValueType().isVector() &&
21684 "Shuffles operate on vector types!");
21685 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21686 "Can only combine shuffles of the same vector register size.");
21688 if (!isTargetShuffle(Op.getOpcode()))
21690 SmallVector<int, 16> OpMask;
21692 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21693 // We only can combine unary shuffles which we can decode the mask for.
21694 if (!HaveMask || !IsUnary)
21697 assert(VT.getVectorNumElements() == OpMask.size() &&
21698 "Different mask size from vector size!");
21699 assert(((RootMask.size() > OpMask.size() &&
21700 RootMask.size() % OpMask.size() == 0) ||
21701 (OpMask.size() > RootMask.size() &&
21702 OpMask.size() % RootMask.size() == 0) ||
21703 OpMask.size() == RootMask.size()) &&
21704 "The smaller number of elements must divide the larger.");
21705 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21706 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21707 assert(((RootRatio == 1 && OpRatio == 1) ||
21708 (RootRatio == 1) != (OpRatio == 1)) &&
21709 "Must not have a ratio for both incoming and op masks!");
21711 SmallVector<int, 16> Mask;
21712 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21714 // Merge this shuffle operation's mask into our accumulated mask. Note that
21715 // this shuffle's mask will be the first applied to the input, followed by the
21716 // root mask to get us all the way to the root value arrangement. The reason
21717 // for this order is that we are recursing up the operation chain.
21718 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21719 int RootIdx = i / RootRatio;
21720 if (RootMask[RootIdx] < 0) {
21721 // This is a zero or undef lane, we're done.
21722 Mask.push_back(RootMask[RootIdx]);
21726 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21727 int OpIdx = RootMaskedIdx / OpRatio;
21728 if (OpMask[OpIdx] < 0) {
21729 // The incoming lanes are zero or undef, it doesn't matter which ones we
21731 Mask.push_back(OpMask[OpIdx]);
21735 // Ok, we have non-zero lanes, map them through.
21736 Mask.push_back(OpMask[OpIdx] * OpRatio +
21737 RootMaskedIdx % OpRatio);
21740 // See if we can recurse into the operand to combine more things.
21741 switch (Op.getOpcode()) {
21742 case X86ISD::PSHUFB:
21744 case X86ISD::PSHUFD:
21745 case X86ISD::PSHUFHW:
21746 case X86ISD::PSHUFLW:
21747 if (Op.getOperand(0).hasOneUse() &&
21748 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21749 HasPSHUFB, DAG, DCI, Subtarget))
21753 case X86ISD::UNPCKL:
21754 case X86ISD::UNPCKH:
21755 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21756 // We can't check for single use, we have to check that this shuffle is the only user.
21757 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21758 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21759 HasPSHUFB, DAG, DCI, Subtarget))
21764 // Minor canonicalization of the accumulated shuffle mask to make it easier
21765 // to match below. All this does is detect masks with squential pairs of
21766 // elements, and shrink them to the half-width mask. It does this in a loop
21767 // so it will reduce the size of the mask to the minimal width mask which
21768 // performs an equivalent shuffle.
21769 SmallVector<int, 16> WidenedMask;
21770 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21771 Mask = std::move(WidenedMask);
21772 WidenedMask.clear();
21775 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21779 /// \brief Get the PSHUF-style mask from PSHUF node.
21781 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21782 /// PSHUF-style masks that can be reused with such instructions.
21783 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21784 MVT VT = N.getSimpleValueType();
21785 SmallVector<int, 4> Mask;
21787 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21791 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21792 // matter. Check that the upper masks are repeats and remove them.
21793 if (VT.getSizeInBits() > 128) {
21794 int LaneElts = 128 / VT.getScalarSizeInBits();
21796 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21797 for (int j = 0; j < LaneElts; ++j)
21798 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21799 "Mask doesn't repeat in high 128-bit lanes!");
21801 Mask.resize(LaneElts);
21804 switch (N.getOpcode()) {
21805 case X86ISD::PSHUFD:
21807 case X86ISD::PSHUFLW:
21810 case X86ISD::PSHUFHW:
21811 Mask.erase(Mask.begin(), Mask.begin() + 4);
21812 for (int &M : Mask)
21816 llvm_unreachable("No valid shuffle instruction found!");
21820 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21822 /// We walk up the chain and look for a combinable shuffle, skipping over
21823 /// shuffles that we could hoist this shuffle's transformation past without
21824 /// altering anything.
21826 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21828 TargetLowering::DAGCombinerInfo &DCI) {
21829 assert(N.getOpcode() == X86ISD::PSHUFD &&
21830 "Called with something other than an x86 128-bit half shuffle!");
21833 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21834 // of the shuffles in the chain so that we can form a fresh chain to replace
21836 SmallVector<SDValue, 8> Chain;
21837 SDValue V = N.getOperand(0);
21838 for (; V.hasOneUse(); V = V.getOperand(0)) {
21839 switch (V.getOpcode()) {
21841 return SDValue(); // Nothing combined!
21844 // Skip bitcasts as we always know the type for the target specific
21848 case X86ISD::PSHUFD:
21849 // Found another dword shuffle.
21852 case X86ISD::PSHUFLW:
21853 // Check that the low words (being shuffled) are the identity in the
21854 // dword shuffle, and the high words are self-contained.
21855 if (Mask[0] != 0 || Mask[1] != 1 ||
21856 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21859 Chain.push_back(V);
21862 case X86ISD::PSHUFHW:
21863 // Check that the high words (being shuffled) are the identity in the
21864 // dword shuffle, and the low words are self-contained.
21865 if (Mask[2] != 2 || Mask[3] != 3 ||
21866 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21869 Chain.push_back(V);
21872 case X86ISD::UNPCKL:
21873 case X86ISD::UNPCKH:
21874 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21875 // shuffle into a preceding word shuffle.
21876 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21877 V.getSimpleValueType().getScalarType() != MVT::i16)
21880 // Search for a half-shuffle which we can combine with.
21881 unsigned CombineOp =
21882 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21883 if (V.getOperand(0) != V.getOperand(1) ||
21884 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21886 Chain.push_back(V);
21887 V = V.getOperand(0);
21889 switch (V.getOpcode()) {
21891 return SDValue(); // Nothing to combine.
21893 case X86ISD::PSHUFLW:
21894 case X86ISD::PSHUFHW:
21895 if (V.getOpcode() == CombineOp)
21898 Chain.push_back(V);
21902 V = V.getOperand(0);
21906 } while (V.hasOneUse());
21909 // Break out of the loop if we break out of the switch.
21913 if (!V.hasOneUse())
21914 // We fell out of the loop without finding a viable combining instruction.
21917 // Merge this node's mask and our incoming mask.
21918 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21919 for (int &M : Mask)
21921 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21922 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21924 // Rebuild the chain around this new shuffle.
21925 while (!Chain.empty()) {
21926 SDValue W = Chain.pop_back_val();
21928 if (V.getValueType() != W.getOperand(0).getValueType())
21929 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21931 switch (W.getOpcode()) {
21933 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21935 case X86ISD::UNPCKL:
21936 case X86ISD::UNPCKH:
21937 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21940 case X86ISD::PSHUFD:
21941 case X86ISD::PSHUFLW:
21942 case X86ISD::PSHUFHW:
21943 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21947 if (V.getValueType() != N.getValueType())
21948 V = DAG.getBitcast(N.getValueType(), V);
21950 // Return the new chain to replace N.
21954 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21956 /// We walk up the chain, skipping shuffles of the other half and looking
21957 /// through shuffles which switch halves trying to find a shuffle of the same
21958 /// pair of dwords.
21959 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21961 TargetLowering::DAGCombinerInfo &DCI) {
21963 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21964 "Called with something other than an x86 128-bit half shuffle!");
21966 unsigned CombineOpcode = N.getOpcode();
21968 // Walk up a single-use chain looking for a combinable shuffle.
21969 SDValue V = N.getOperand(0);
21970 for (; V.hasOneUse(); V = V.getOperand(0)) {
21971 switch (V.getOpcode()) {
21973 return false; // Nothing combined!
21976 // Skip bitcasts as we always know the type for the target specific
21980 case X86ISD::PSHUFLW:
21981 case X86ISD::PSHUFHW:
21982 if (V.getOpcode() == CombineOpcode)
21985 // Other-half shuffles are no-ops.
21988 // Break out of the loop if we break out of the switch.
21992 if (!V.hasOneUse())
21993 // We fell out of the loop without finding a viable combining instruction.
21996 // Combine away the bottom node as its shuffle will be accumulated into
21997 // a preceding shuffle.
21998 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22000 // Record the old value.
22003 // Merge this node's mask and our incoming mask (adjusted to account for all
22004 // the pshufd instructions encountered).
22005 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22006 for (int &M : Mask)
22008 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22009 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22011 // Check that the shuffles didn't cancel each other out. If not, we need to
22012 // combine to the new one.
22014 // Replace the combinable shuffle with the combined one, updating all users
22015 // so that we re-evaluate the chain here.
22016 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22021 /// \brief Try to combine x86 target specific shuffles.
22022 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22023 TargetLowering::DAGCombinerInfo &DCI,
22024 const X86Subtarget *Subtarget) {
22026 MVT VT = N.getSimpleValueType();
22027 SmallVector<int, 4> Mask;
22029 switch (N.getOpcode()) {
22030 case X86ISD::PSHUFD:
22031 case X86ISD::PSHUFLW:
22032 case X86ISD::PSHUFHW:
22033 Mask = getPSHUFShuffleMask(N);
22034 assert(Mask.size() == 4);
22040 // Nuke no-op shuffles that show up after combining.
22041 if (isNoopShuffleMask(Mask))
22042 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22044 // Look for simplifications involving one or two shuffle instructions.
22045 SDValue V = N.getOperand(0);
22046 switch (N.getOpcode()) {
22049 case X86ISD::PSHUFLW:
22050 case X86ISD::PSHUFHW:
22051 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22053 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22054 return SDValue(); // We combined away this shuffle, so we're done.
22056 // See if this reduces to a PSHUFD which is no more expensive and can
22057 // combine with more operations. Note that it has to at least flip the
22058 // dwords as otherwise it would have been removed as a no-op.
22059 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22060 int DMask[] = {0, 1, 2, 3};
22061 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22062 DMask[DOffset + 0] = DOffset + 1;
22063 DMask[DOffset + 1] = DOffset + 0;
22064 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22065 V = DAG.getBitcast(DVT, V);
22066 DCI.AddToWorklist(V.getNode());
22067 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22068 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22069 DCI.AddToWorklist(V.getNode());
22070 return DAG.getBitcast(VT, V);
22073 // Look for shuffle patterns which can be implemented as a single unpack.
22074 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22075 // only works when we have a PSHUFD followed by two half-shuffles.
22076 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22077 (V.getOpcode() == X86ISD::PSHUFLW ||
22078 V.getOpcode() == X86ISD::PSHUFHW) &&
22079 V.getOpcode() != N.getOpcode() &&
22081 SDValue D = V.getOperand(0);
22082 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22083 D = D.getOperand(0);
22084 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22085 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22086 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22087 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22088 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22090 for (int i = 0; i < 4; ++i) {
22091 WordMask[i + NOffset] = Mask[i] + NOffset;
22092 WordMask[i + VOffset] = VMask[i] + VOffset;
22094 // Map the word mask through the DWord mask.
22096 for (int i = 0; i < 8; ++i)
22097 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22098 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22099 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22100 // We can replace all three shuffles with an unpack.
22101 V = DAG.getBitcast(VT, D.getOperand(0));
22102 DCI.AddToWorklist(V.getNode());
22103 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22112 case X86ISD::PSHUFD:
22113 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22122 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22124 /// We combine this directly on the abstract vector shuffle nodes so it is
22125 /// easier to generically match. We also insert dummy vector shuffle nodes for
22126 /// the operands which explicitly discard the lanes which are unused by this
22127 /// operation to try to flow through the rest of the combiner the fact that
22128 /// they're unused.
22129 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22131 EVT VT = N->getValueType(0);
22133 // We only handle target-independent shuffles.
22134 // FIXME: It would be easy and harmless to use the target shuffle mask
22135 // extraction tool to support more.
22136 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22139 auto *SVN = cast<ShuffleVectorSDNode>(N);
22140 ArrayRef<int> Mask = SVN->getMask();
22141 SDValue V1 = N->getOperand(0);
22142 SDValue V2 = N->getOperand(1);
22144 // We require the first shuffle operand to be the SUB node, and the second to
22145 // be the ADD node.
22146 // FIXME: We should support the commuted patterns.
22147 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22150 // If there are other uses of these operations we can't fold them.
22151 if (!V1->hasOneUse() || !V2->hasOneUse())
22154 // Ensure that both operations have the same operands. Note that we can
22155 // commute the FADD operands.
22156 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22157 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22158 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22161 // We're looking for blends between FADD and FSUB nodes. We insist on these
22162 // nodes being lined up in a specific expected pattern.
22163 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22164 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22165 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22168 // Only specific types are legal at this point, assert so we notice if and
22169 // when these change.
22170 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22171 VT == MVT::v4f64) &&
22172 "Unknown vector type encountered!");
22174 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22177 /// PerformShuffleCombine - Performs several different shuffle combines.
22178 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22179 TargetLowering::DAGCombinerInfo &DCI,
22180 const X86Subtarget *Subtarget) {
22182 SDValue N0 = N->getOperand(0);
22183 SDValue N1 = N->getOperand(1);
22184 EVT VT = N->getValueType(0);
22186 // Don't create instructions with illegal types after legalize types has run.
22187 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22188 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22191 // If we have legalized the vector types, look for blends of FADD and FSUB
22192 // nodes that we can fuse into an ADDSUB node.
22193 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22194 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22197 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22198 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22199 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22200 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22202 // During Type Legalization, when promoting illegal vector types,
22203 // the backend might introduce new shuffle dag nodes and bitcasts.
22205 // This code performs the following transformation:
22206 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22207 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22209 // We do this only if both the bitcast and the BINOP dag nodes have
22210 // one use. Also, perform this transformation only if the new binary
22211 // operation is legal. This is to avoid introducing dag nodes that
22212 // potentially need to be further expanded (or custom lowered) into a
22213 // less optimal sequence of dag nodes.
22214 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22215 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22216 N0.getOpcode() == ISD::BITCAST) {
22217 SDValue BC0 = N0.getOperand(0);
22218 EVT SVT = BC0.getValueType();
22219 unsigned Opcode = BC0.getOpcode();
22220 unsigned NumElts = VT.getVectorNumElements();
22222 if (BC0.hasOneUse() && SVT.isVector() &&
22223 SVT.getVectorNumElements() * 2 == NumElts &&
22224 TLI.isOperationLegal(Opcode, VT)) {
22225 bool CanFold = false;
22237 unsigned SVTNumElts = SVT.getVectorNumElements();
22238 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22239 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22240 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22241 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22242 CanFold = SVOp->getMaskElt(i) < 0;
22245 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22246 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22247 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22248 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22253 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22254 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22255 // consecutive, non-overlapping, and in the right order.
22256 SmallVector<SDValue, 16> Elts;
22257 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22258 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22260 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22263 if (isTargetShuffle(N->getOpcode())) {
22265 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22266 if (Shuffle.getNode())
22269 // Try recursively combining arbitrary sequences of x86 shuffle
22270 // instructions into higher-order shuffles. We do this after combining
22271 // specific PSHUF instruction sequences into their minimal form so that we
22272 // can evaluate how many specialized shuffle instructions are involved in
22273 // a particular chain.
22274 SmallVector<int, 1> NonceMask; // Just a placeholder.
22275 NonceMask.push_back(0);
22276 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22277 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22279 return SDValue(); // This routine will use CombineTo to replace N.
22285 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22286 /// specific shuffle of a load can be folded into a single element load.
22287 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22288 /// shuffles have been custom lowered so we need to handle those here.
22289 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22290 TargetLowering::DAGCombinerInfo &DCI) {
22291 if (DCI.isBeforeLegalizeOps())
22294 SDValue InVec = N->getOperand(0);
22295 SDValue EltNo = N->getOperand(1);
22297 if (!isa<ConstantSDNode>(EltNo))
22300 EVT OriginalVT = InVec.getValueType();
22302 if (InVec.getOpcode() == ISD::BITCAST) {
22303 // Don't duplicate a load with other uses.
22304 if (!InVec.hasOneUse())
22306 EVT BCVT = InVec.getOperand(0).getValueType();
22307 if (!BCVT.isVector() ||
22308 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22310 InVec = InVec.getOperand(0);
22313 EVT CurrentVT = InVec.getValueType();
22315 if (!isTargetShuffle(InVec.getOpcode()))
22318 // Don't duplicate a load with other uses.
22319 if (!InVec.hasOneUse())
22322 SmallVector<int, 16> ShuffleMask;
22324 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22325 ShuffleMask, UnaryShuffle))
22328 // Select the input vector, guarding against out of range extract vector.
22329 unsigned NumElems = CurrentVT.getVectorNumElements();
22330 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22331 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22332 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22333 : InVec.getOperand(1);
22335 // If inputs to shuffle are the same for both ops, then allow 2 uses
22336 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22337 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22339 if (LdNode.getOpcode() == ISD::BITCAST) {
22340 // Don't duplicate a load with other uses.
22341 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22344 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22345 LdNode = LdNode.getOperand(0);
22348 if (!ISD::isNormalLoad(LdNode.getNode()))
22351 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22353 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22356 EVT EltVT = N->getValueType(0);
22357 // If there's a bitcast before the shuffle, check if the load type and
22358 // alignment is valid.
22359 unsigned Align = LN0->getAlignment();
22360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22361 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22362 EltVT.getTypeForEVT(*DAG.getContext()));
22364 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22367 // All checks match so transform back to vector_shuffle so that DAG combiner
22368 // can finish the job
22371 // Create shuffle node taking into account the case that its a unary shuffle
22372 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22373 : InVec.getOperand(1);
22374 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22375 InVec.getOperand(0), Shuffle,
22377 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22378 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22382 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22383 /// special and don't usually play with other vector types, it's better to
22384 /// handle them early to be sure we emit efficient code by avoiding
22385 /// store-load conversions.
22386 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22387 if (N->getValueType(0) != MVT::x86mmx ||
22388 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22389 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22392 SDValue V = N->getOperand(0);
22393 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22394 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22395 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22396 N->getValueType(0), V.getOperand(0));
22401 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22402 /// generation and convert it from being a bunch of shuffles and extracts
22403 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22404 /// storing the value and loading scalars back, while for x64 we should
22405 /// use 64-bit extracts and shifts.
22406 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22407 TargetLowering::DAGCombinerInfo &DCI) {
22408 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22411 SDValue InputVector = N->getOperand(0);
22412 SDLoc dl(InputVector);
22413 // Detect mmx to i32 conversion through a v2i32 elt extract.
22414 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22415 N->getValueType(0) == MVT::i32 &&
22416 InputVector.getValueType() == MVT::v2i32) {
22418 // The bitcast source is a direct mmx result.
22419 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22420 if (MMXSrc.getValueType() == MVT::x86mmx)
22421 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22422 N->getValueType(0),
22423 InputVector.getNode()->getOperand(0));
22425 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22426 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22427 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22428 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22429 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22430 MMXSrcOp.getValueType() == MVT::v1i64 &&
22431 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22432 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22433 N->getValueType(0),
22434 MMXSrcOp.getOperand(0));
22437 EVT VT = N->getValueType(0);
22439 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22440 InputVector.getOpcode() == ISD::BITCAST &&
22441 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22442 uint64_t ExtractedElt =
22443 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22444 uint64_t InputValue =
22445 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22446 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22447 return DAG.getConstant(Res, dl, MVT::i1);
22449 // Only operate on vectors of 4 elements, where the alternative shuffling
22450 // gets to be more expensive.
22451 if (InputVector.getValueType() != MVT::v4i32)
22454 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22455 // single use which is a sign-extend or zero-extend, and all elements are
22457 SmallVector<SDNode *, 4> Uses;
22458 unsigned ExtractedElements = 0;
22459 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22460 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22461 if (UI.getUse().getResNo() != InputVector.getResNo())
22464 SDNode *Extract = *UI;
22465 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22468 if (Extract->getValueType(0) != MVT::i32)
22470 if (!Extract->hasOneUse())
22472 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22473 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22475 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22478 // Record which element was extracted.
22479 ExtractedElements |=
22480 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22482 Uses.push_back(Extract);
22485 // If not all the elements were used, this may not be worthwhile.
22486 if (ExtractedElements != 15)
22489 // Ok, we've now decided to do the transformation.
22490 // If 64-bit shifts are legal, use the extract-shift sequence,
22491 // otherwise bounce the vector off the cache.
22492 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22495 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22496 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22497 auto &DL = DAG.getDataLayout();
22498 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22499 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22500 DAG.getConstant(0, dl, VecIdxTy));
22501 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22502 DAG.getConstant(1, dl, VecIdxTy));
22504 SDValue ShAmt = DAG.getConstant(
22505 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22506 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22507 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22508 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22509 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22510 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22511 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22513 // Store the value to a temporary stack slot.
22514 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22515 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22516 MachinePointerInfo(), false, false, 0);
22518 EVT ElementType = InputVector.getValueType().getVectorElementType();
22519 unsigned EltSize = ElementType.getSizeInBits() / 8;
22521 // Replace each use (extract) with a load of the appropriate element.
22522 for (unsigned i = 0; i < 4; ++i) {
22523 uint64_t Offset = EltSize * i;
22524 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22525 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22527 SDValue ScalarAddr =
22528 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22530 // Load the scalar.
22531 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22532 ScalarAddr, MachinePointerInfo(),
22533 false, false, false, 0);
22538 // Replace the extracts
22539 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22540 UE = Uses.end(); UI != UE; ++UI) {
22541 SDNode *Extract = *UI;
22543 SDValue Idx = Extract->getOperand(1);
22544 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22545 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22548 // The replacement was made in place; don't return anything.
22553 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22554 const X86Subtarget *Subtarget) {
22556 SDValue Cond = N->getOperand(0);
22557 SDValue LHS = N->getOperand(1);
22558 SDValue RHS = N->getOperand(2);
22560 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22561 SDValue CondSrc = Cond->getOperand(0);
22562 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22563 Cond = CondSrc->getOperand(0);
22566 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22569 // A vselect where all conditions and data are constants can be optimized into
22570 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22571 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22572 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22575 unsigned MaskValue = 0;
22576 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22579 MVT VT = N->getSimpleValueType(0);
22580 unsigned NumElems = VT.getVectorNumElements();
22581 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22582 for (unsigned i = 0; i < NumElems; ++i) {
22583 // Be sure we emit undef where we can.
22584 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22585 ShuffleMask[i] = -1;
22587 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22591 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22593 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22596 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22598 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22599 TargetLowering::DAGCombinerInfo &DCI,
22600 const X86Subtarget *Subtarget) {
22602 SDValue Cond = N->getOperand(0);
22603 // Get the LHS/RHS of the select.
22604 SDValue LHS = N->getOperand(1);
22605 SDValue RHS = N->getOperand(2);
22606 EVT VT = LHS.getValueType();
22607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22609 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22610 // instructions match the semantics of the common C idiom x<y?x:y but not
22611 // x<=y?x:y, because of how they handle negative zero (which can be
22612 // ignored in unsafe-math mode).
22613 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22614 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22615 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22616 (Subtarget->hasSSE2() ||
22617 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22618 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22620 unsigned Opcode = 0;
22621 // Check for x CC y ? x : y.
22622 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22623 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22627 // Converting this to a min would handle NaNs incorrectly, and swapping
22628 // the operands would cause it to handle comparisons between positive
22629 // and negative zero incorrectly.
22630 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22631 if (!DAG.getTarget().Options.UnsafeFPMath &&
22632 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22634 std::swap(LHS, RHS);
22636 Opcode = X86ISD::FMIN;
22639 // Converting this to a min would handle comparisons between positive
22640 // and negative zero incorrectly.
22641 if (!DAG.getTarget().Options.UnsafeFPMath &&
22642 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22644 Opcode = X86ISD::FMIN;
22647 // Converting this to a min would handle both negative zeros and NaNs
22648 // incorrectly, but we can swap the operands to fix both.
22649 std::swap(LHS, RHS);
22653 Opcode = X86ISD::FMIN;
22657 // Converting this to a max would handle comparisons between positive
22658 // and negative zero incorrectly.
22659 if (!DAG.getTarget().Options.UnsafeFPMath &&
22660 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22662 Opcode = X86ISD::FMAX;
22665 // Converting this to a max would handle NaNs incorrectly, and swapping
22666 // the operands would cause it to handle comparisons between positive
22667 // and negative zero incorrectly.
22668 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22669 if (!DAG.getTarget().Options.UnsafeFPMath &&
22670 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22672 std::swap(LHS, RHS);
22674 Opcode = X86ISD::FMAX;
22677 // Converting this to a max would handle both negative zeros and NaNs
22678 // incorrectly, but we can swap the operands to fix both.
22679 std::swap(LHS, RHS);
22683 Opcode = X86ISD::FMAX;
22686 // Check for x CC y ? y : x -- a min/max with reversed arms.
22687 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22688 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22692 // Converting this to a min would handle comparisons between positive
22693 // and negative zero incorrectly, and swapping the operands would
22694 // cause it to handle NaNs incorrectly.
22695 if (!DAG.getTarget().Options.UnsafeFPMath &&
22696 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22697 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22699 std::swap(LHS, RHS);
22701 Opcode = X86ISD::FMIN;
22704 // Converting this to a min would handle NaNs incorrectly.
22705 if (!DAG.getTarget().Options.UnsafeFPMath &&
22706 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22708 Opcode = X86ISD::FMIN;
22711 // Converting this to a min would handle both negative zeros and NaNs
22712 // incorrectly, but we can swap the operands to fix both.
22713 std::swap(LHS, RHS);
22717 Opcode = X86ISD::FMIN;
22721 // Converting this to a max would handle NaNs incorrectly.
22722 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22724 Opcode = X86ISD::FMAX;
22727 // Converting this to a max would handle comparisons between positive
22728 // and negative zero incorrectly, and swapping the operands would
22729 // cause it to handle NaNs incorrectly.
22730 if (!DAG.getTarget().Options.UnsafeFPMath &&
22731 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22732 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22734 std::swap(LHS, RHS);
22736 Opcode = X86ISD::FMAX;
22739 // Converting this to a max would handle both negative zeros and NaNs
22740 // incorrectly, but we can swap the operands to fix both.
22741 std::swap(LHS, RHS);
22745 Opcode = X86ISD::FMAX;
22751 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22754 EVT CondVT = Cond.getValueType();
22755 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22756 CondVT.getVectorElementType() == MVT::i1) {
22757 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22758 // lowering on KNL. In this case we convert it to
22759 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22760 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22761 // Since SKX these selects have a proper lowering.
22762 EVT OpVT = LHS.getValueType();
22763 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22764 (OpVT.getVectorElementType() == MVT::i8 ||
22765 OpVT.getVectorElementType() == MVT::i16) &&
22766 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22767 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22768 DCI.AddToWorklist(Cond.getNode());
22769 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22772 // If this is a select between two integer constants, try to do some
22774 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22775 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22776 // Don't do this for crazy integer types.
22777 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22778 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22779 // so that TrueC (the true value) is larger than FalseC.
22780 bool NeedsCondInvert = false;
22782 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22783 // Efficiently invertible.
22784 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22785 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22786 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22787 NeedsCondInvert = true;
22788 std::swap(TrueC, FalseC);
22791 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22792 if (FalseC->getAPIntValue() == 0 &&
22793 TrueC->getAPIntValue().isPowerOf2()) {
22794 if (NeedsCondInvert) // Invert the condition if needed.
22795 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22796 DAG.getConstant(1, DL, Cond.getValueType()));
22798 // Zero extend the condition if needed.
22799 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22801 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22802 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22803 DAG.getConstant(ShAmt, DL, MVT::i8));
22806 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22807 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22808 if (NeedsCondInvert) // Invert the condition if needed.
22809 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22810 DAG.getConstant(1, DL, Cond.getValueType()));
22812 // Zero extend the condition if needed.
22813 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22814 FalseC->getValueType(0), Cond);
22815 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22816 SDValue(FalseC, 0));
22819 // Optimize cases that will turn into an LEA instruction. This requires
22820 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22821 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22822 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22823 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22825 bool isFastMultiplier = false;
22827 switch ((unsigned char)Diff) {
22829 case 1: // result = add base, cond
22830 case 2: // result = lea base( , cond*2)
22831 case 3: // result = lea base(cond, cond*2)
22832 case 4: // result = lea base( , cond*4)
22833 case 5: // result = lea base(cond, cond*4)
22834 case 8: // result = lea base( , cond*8)
22835 case 9: // result = lea base(cond, cond*8)
22836 isFastMultiplier = true;
22841 if (isFastMultiplier) {
22842 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22843 if (NeedsCondInvert) // Invert the condition if needed.
22844 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22845 DAG.getConstant(1, DL, Cond.getValueType()));
22847 // Zero extend the condition if needed.
22848 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22850 // Scale the condition by the difference.
22852 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22853 DAG.getConstant(Diff, DL,
22854 Cond.getValueType()));
22856 // Add the base if non-zero.
22857 if (FalseC->getAPIntValue() != 0)
22858 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22859 SDValue(FalseC, 0));
22866 // Canonicalize max and min:
22867 // (x > y) ? x : y -> (x >= y) ? x : y
22868 // (x < y) ? x : y -> (x <= y) ? x : y
22869 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22870 // the need for an extra compare
22871 // against zero. e.g.
22872 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22874 // testl %edi, %edi
22876 // cmovgl %edi, %eax
22880 // cmovsl %eax, %edi
22881 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22882 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22883 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22884 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22889 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22890 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22891 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22892 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22897 // Early exit check
22898 if (!TLI.isTypeLegal(VT))
22901 // Match VSELECTs into subs with unsigned saturation.
22902 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22903 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22904 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22905 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22906 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22908 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22909 // left side invert the predicate to simplify logic below.
22911 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22913 CC = ISD::getSetCCInverse(CC, true);
22914 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22918 if (Other.getNode() && Other->getNumOperands() == 2 &&
22919 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22920 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22921 SDValue CondRHS = Cond->getOperand(1);
22923 // Look for a general sub with unsigned saturation first.
22924 // x >= y ? x-y : 0 --> subus x, y
22925 // x > y ? x-y : 0 --> subus x, y
22926 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22927 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22928 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22930 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22931 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22932 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22933 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22934 // If the RHS is a constant we have to reverse the const
22935 // canonicalization.
22936 // x > C-1 ? x+-C : 0 --> subus x, C
22937 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22938 CondRHSConst->getAPIntValue() ==
22939 (-OpRHSConst->getAPIntValue() - 1))
22940 return DAG.getNode(
22941 X86ISD::SUBUS, DL, VT, OpLHS,
22942 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22944 // Another special case: If C was a sign bit, the sub has been
22945 // canonicalized into a xor.
22946 // FIXME: Would it be better to use computeKnownBits to determine
22947 // whether it's safe to decanonicalize the xor?
22948 // x s< 0 ? x^C : 0 --> subus x, C
22949 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22950 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22951 OpRHSConst->getAPIntValue().isSignBit())
22952 // Note that we have to rebuild the RHS constant here to ensure we
22953 // don't rely on particular values of undef lanes.
22954 return DAG.getNode(
22955 X86ISD::SUBUS, DL, VT, OpLHS,
22956 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22961 // Simplify vector selection if condition value type matches vselect
22963 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22964 assert(Cond.getValueType().isVector() &&
22965 "vector select expects a vector selector!");
22967 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22968 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22970 // Try invert the condition if true value is not all 1s and false value
22972 if (!TValIsAllOnes && !FValIsAllZeros &&
22973 // Check if the selector will be produced by CMPP*/PCMP*
22974 Cond.getOpcode() == ISD::SETCC &&
22975 // Check if SETCC has already been promoted
22976 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22978 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22979 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22981 if (TValIsAllZeros || FValIsAllOnes) {
22982 SDValue CC = Cond.getOperand(2);
22983 ISD::CondCode NewCC =
22984 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22985 Cond.getOperand(0).getValueType().isInteger());
22986 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22987 std::swap(LHS, RHS);
22988 TValIsAllOnes = FValIsAllOnes;
22989 FValIsAllZeros = TValIsAllZeros;
22993 if (TValIsAllOnes || FValIsAllZeros) {
22996 if (TValIsAllOnes && FValIsAllZeros)
22998 else if (TValIsAllOnes)
23000 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23001 else if (FValIsAllZeros)
23002 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23003 DAG.getBitcast(CondVT, LHS));
23005 return DAG.getBitcast(VT, Ret);
23009 // We should generate an X86ISD::BLENDI from a vselect if its argument
23010 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23011 // constants. This specific pattern gets generated when we split a
23012 // selector for a 512 bit vector in a machine without AVX512 (but with
23013 // 256-bit vectors), during legalization:
23015 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23017 // Iff we find this pattern and the build_vectors are built from
23018 // constants, we translate the vselect into a shuffle_vector that we
23019 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23020 if ((N->getOpcode() == ISD::VSELECT ||
23021 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23022 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23023 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23024 if (Shuffle.getNode())
23028 // If this is a *dynamic* select (non-constant condition) and we can match
23029 // this node with one of the variable blend instructions, restructure the
23030 // condition so that the blends can use the high bit of each element and use
23031 // SimplifyDemandedBits to simplify the condition operand.
23032 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23033 !DCI.isBeforeLegalize() &&
23034 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23035 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23037 // Don't optimize vector selects that map to mask-registers.
23041 // We can only handle the cases where VSELECT is directly legal on the
23042 // subtarget. We custom lower VSELECT nodes with constant conditions and
23043 // this makes it hard to see whether a dynamic VSELECT will correctly
23044 // lower, so we both check the operation's status and explicitly handle the
23045 // cases where a *dynamic* blend will fail even though a constant-condition
23046 // blend could be custom lowered.
23047 // FIXME: We should find a better way to handle this class of problems.
23048 // Potentially, we should combine constant-condition vselect nodes
23049 // pre-legalization into shuffles and not mark as many types as custom
23051 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23053 // FIXME: We don't support i16-element blends currently. We could and
23054 // should support them by making *all* the bits in the condition be set
23055 // rather than just the high bit and using an i8-element blend.
23056 if (VT.getScalarType() == MVT::i16)
23058 // Dynamic blending was only available from SSE4.1 onward.
23059 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23061 // Byte blends are only available in AVX2
23062 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23063 !Subtarget->hasAVX2())
23066 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23067 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23069 APInt KnownZero, KnownOne;
23070 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23071 DCI.isBeforeLegalizeOps());
23072 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23073 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23075 // If we changed the computation somewhere in the DAG, this change
23076 // will affect all users of Cond.
23077 // Make sure it is fine and update all the nodes so that we do not
23078 // use the generic VSELECT anymore. Otherwise, we may perform
23079 // wrong optimizations as we messed up with the actual expectation
23080 // for the vector boolean values.
23081 if (Cond != TLO.Old) {
23082 // Check all uses of that condition operand to check whether it will be
23083 // consumed by non-BLEND instructions, which may depend on all bits are
23085 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23087 if (I->getOpcode() != ISD::VSELECT)
23088 // TODO: Add other opcodes eventually lowered into BLEND.
23091 // Update all the users of the condition, before committing the change,
23092 // so that the VSELECT optimizations that expect the correct vector
23093 // boolean value will not be triggered.
23094 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23096 DAG.ReplaceAllUsesOfValueWith(
23098 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23099 Cond, I->getOperand(1), I->getOperand(2)));
23100 DCI.CommitTargetLoweringOpt(TLO);
23103 // At this point, only Cond is changed. Change the condition
23104 // just for N to keep the opportunity to optimize all other
23105 // users their own way.
23106 DAG.ReplaceAllUsesOfValueWith(
23108 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23109 TLO.New, N->getOperand(1), N->getOperand(2)));
23117 // Check whether a boolean test is testing a boolean value generated by
23118 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23121 // Simplify the following patterns:
23122 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23123 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23124 // to (Op EFLAGS Cond)
23126 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23127 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23128 // to (Op EFLAGS !Cond)
23130 // where Op could be BRCOND or CMOV.
23132 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23133 // Quit if not CMP and SUB with its value result used.
23134 if (Cmp.getOpcode() != X86ISD::CMP &&
23135 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23138 // Quit if not used as a boolean value.
23139 if (CC != X86::COND_E && CC != X86::COND_NE)
23142 // Check CMP operands. One of them should be 0 or 1 and the other should be
23143 // an SetCC or extended from it.
23144 SDValue Op1 = Cmp.getOperand(0);
23145 SDValue Op2 = Cmp.getOperand(1);
23148 const ConstantSDNode* C = nullptr;
23149 bool needOppositeCond = (CC == X86::COND_E);
23150 bool checkAgainstTrue = false; // Is it a comparison against 1?
23152 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23154 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23156 else // Quit if all operands are not constants.
23159 if (C->getZExtValue() == 1) {
23160 needOppositeCond = !needOppositeCond;
23161 checkAgainstTrue = true;
23162 } else if (C->getZExtValue() != 0)
23163 // Quit if the constant is neither 0 or 1.
23166 bool truncatedToBoolWithAnd = false;
23167 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23168 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23169 SetCC.getOpcode() == ISD::TRUNCATE ||
23170 SetCC.getOpcode() == ISD::AND) {
23171 if (SetCC.getOpcode() == ISD::AND) {
23173 ConstantSDNode *CS;
23174 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23175 CS->getZExtValue() == 1)
23177 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23178 CS->getZExtValue() == 1)
23182 SetCC = SetCC.getOperand(OpIdx);
23183 truncatedToBoolWithAnd = true;
23185 SetCC = SetCC.getOperand(0);
23188 switch (SetCC.getOpcode()) {
23189 case X86ISD::SETCC_CARRY:
23190 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23191 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23192 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23193 // truncated to i1 using 'and'.
23194 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23196 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23197 "Invalid use of SETCC_CARRY!");
23199 case X86ISD::SETCC:
23200 // Set the condition code or opposite one if necessary.
23201 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23202 if (needOppositeCond)
23203 CC = X86::GetOppositeBranchCondition(CC);
23204 return SetCC.getOperand(1);
23205 case X86ISD::CMOV: {
23206 // Check whether false/true value has canonical one, i.e. 0 or 1.
23207 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23208 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23209 // Quit if true value is not a constant.
23212 // Quit if false value is not a constant.
23214 SDValue Op = SetCC.getOperand(0);
23215 // Skip 'zext' or 'trunc' node.
23216 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23217 Op.getOpcode() == ISD::TRUNCATE)
23218 Op = Op.getOperand(0);
23219 // A special case for rdrand/rdseed, where 0 is set if false cond is
23221 if ((Op.getOpcode() != X86ISD::RDRAND &&
23222 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23225 // Quit if false value is not the constant 0 or 1.
23226 bool FValIsFalse = true;
23227 if (FVal && FVal->getZExtValue() != 0) {
23228 if (FVal->getZExtValue() != 1)
23230 // If FVal is 1, opposite cond is needed.
23231 needOppositeCond = !needOppositeCond;
23232 FValIsFalse = false;
23234 // Quit if TVal is not the constant opposite of FVal.
23235 if (FValIsFalse && TVal->getZExtValue() != 1)
23237 if (!FValIsFalse && TVal->getZExtValue() != 0)
23239 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23240 if (needOppositeCond)
23241 CC = X86::GetOppositeBranchCondition(CC);
23242 return SetCC.getOperand(3);
23249 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23251 /// (X86or (X86setcc) (X86setcc))
23252 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23253 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23254 X86::CondCode &CC1, SDValue &Flags,
23256 if (Cond->getOpcode() == X86ISD::CMP) {
23257 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23258 if (!CondOp1C || !CondOp1C->isNullValue())
23261 Cond = Cond->getOperand(0);
23266 SDValue SetCC0, SetCC1;
23267 switch (Cond->getOpcode()) {
23268 default: return false;
23275 SetCC0 = Cond->getOperand(0);
23276 SetCC1 = Cond->getOperand(1);
23280 // Make sure we have SETCC nodes, using the same flags value.
23281 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23282 SetCC1.getOpcode() != X86ISD::SETCC ||
23283 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23286 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23287 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23288 Flags = SetCC0->getOperand(1);
23292 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23293 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23294 TargetLowering::DAGCombinerInfo &DCI,
23295 const X86Subtarget *Subtarget) {
23298 // If the flag operand isn't dead, don't touch this CMOV.
23299 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23302 SDValue FalseOp = N->getOperand(0);
23303 SDValue TrueOp = N->getOperand(1);
23304 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23305 SDValue Cond = N->getOperand(3);
23307 if (CC == X86::COND_E || CC == X86::COND_NE) {
23308 switch (Cond.getOpcode()) {
23312 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23313 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23314 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23320 Flags = checkBoolTestSetCCCombine(Cond, CC);
23321 if (Flags.getNode() &&
23322 // Extra check as FCMOV only supports a subset of X86 cond.
23323 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23324 SDValue Ops[] = { FalseOp, TrueOp,
23325 DAG.getConstant(CC, DL, MVT::i8), Flags };
23326 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23329 // If this is a select between two integer constants, try to do some
23330 // optimizations. Note that the operands are ordered the opposite of SELECT
23332 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23333 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23334 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23335 // larger than FalseC (the false value).
23336 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23337 CC = X86::GetOppositeBranchCondition(CC);
23338 std::swap(TrueC, FalseC);
23339 std::swap(TrueOp, FalseOp);
23342 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23343 // This is efficient for any integer data type (including i8/i16) and
23345 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23346 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23347 DAG.getConstant(CC, DL, MVT::i8), Cond);
23349 // Zero extend the condition if needed.
23350 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23352 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23353 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23354 DAG.getConstant(ShAmt, DL, MVT::i8));
23355 if (N->getNumValues() == 2) // Dead flag value?
23356 return DCI.CombineTo(N, Cond, SDValue());
23360 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23361 // for any integer data type, including i8/i16.
23362 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23363 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23364 DAG.getConstant(CC, DL, MVT::i8), Cond);
23366 // Zero extend the condition if needed.
23367 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23368 FalseC->getValueType(0), Cond);
23369 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23370 SDValue(FalseC, 0));
23372 if (N->getNumValues() == 2) // Dead flag value?
23373 return DCI.CombineTo(N, Cond, SDValue());
23377 // Optimize cases that will turn into an LEA instruction. This requires
23378 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23379 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23380 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23381 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23383 bool isFastMultiplier = false;
23385 switch ((unsigned char)Diff) {
23387 case 1: // result = add base, cond
23388 case 2: // result = lea base( , cond*2)
23389 case 3: // result = lea base(cond, cond*2)
23390 case 4: // result = lea base( , cond*4)
23391 case 5: // result = lea base(cond, cond*4)
23392 case 8: // result = lea base( , cond*8)
23393 case 9: // result = lea base(cond, cond*8)
23394 isFastMultiplier = true;
23399 if (isFastMultiplier) {
23400 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23401 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23402 DAG.getConstant(CC, DL, MVT::i8), Cond);
23403 // Zero extend the condition if needed.
23404 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23406 // Scale the condition by the difference.
23408 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23409 DAG.getConstant(Diff, DL, Cond.getValueType()));
23411 // Add the base if non-zero.
23412 if (FalseC->getAPIntValue() != 0)
23413 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23414 SDValue(FalseC, 0));
23415 if (N->getNumValues() == 2) // Dead flag value?
23416 return DCI.CombineTo(N, Cond, SDValue());
23423 // Handle these cases:
23424 // (select (x != c), e, c) -> select (x != c), e, x),
23425 // (select (x == c), c, e) -> select (x == c), x, e)
23426 // where the c is an integer constant, and the "select" is the combination
23427 // of CMOV and CMP.
23429 // The rationale for this change is that the conditional-move from a constant
23430 // needs two instructions, however, conditional-move from a register needs
23431 // only one instruction.
23433 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23434 // some instruction-combining opportunities. This opt needs to be
23435 // postponed as late as possible.
23437 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23438 // the DCI.xxxx conditions are provided to postpone the optimization as
23439 // late as possible.
23441 ConstantSDNode *CmpAgainst = nullptr;
23442 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23443 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23444 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23446 if (CC == X86::COND_NE &&
23447 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23448 CC = X86::GetOppositeBranchCondition(CC);
23449 std::swap(TrueOp, FalseOp);
23452 if (CC == X86::COND_E &&
23453 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23454 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23455 DAG.getConstant(CC, DL, MVT::i8), Cond };
23456 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23461 // Fold and/or of setcc's to double CMOV:
23462 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23463 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23465 // This combine lets us generate:
23466 // cmovcc1 (jcc1 if we don't have CMOV)
23472 // cmovne (jne if we don't have CMOV)
23473 // When we can't use the CMOV instruction, it might increase branch
23475 // When we can use CMOV, or when there is no mispredict, this improves
23476 // throughput and reduces register pressure.
23478 if (CC == X86::COND_NE) {
23480 X86::CondCode CC0, CC1;
23482 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23484 std::swap(FalseOp, TrueOp);
23485 CC0 = X86::GetOppositeBranchCondition(CC0);
23486 CC1 = X86::GetOppositeBranchCondition(CC1);
23489 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23491 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23492 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23493 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23494 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23502 /// PerformMulCombine - Optimize a single multiply with constant into two
23503 /// in order to implement it with two cheaper instructions, e.g.
23504 /// LEA + SHL, LEA + LEA.
23505 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23506 TargetLowering::DAGCombinerInfo &DCI) {
23507 // An imul is usually smaller than the alternative sequence.
23508 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23511 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23514 EVT VT = N->getValueType(0);
23515 if (VT != MVT::i64 && VT != MVT::i32)
23518 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23521 uint64_t MulAmt = C->getZExtValue();
23522 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23525 uint64_t MulAmt1 = 0;
23526 uint64_t MulAmt2 = 0;
23527 if ((MulAmt % 9) == 0) {
23529 MulAmt2 = MulAmt / 9;
23530 } else if ((MulAmt % 5) == 0) {
23532 MulAmt2 = MulAmt / 5;
23533 } else if ((MulAmt % 3) == 0) {
23535 MulAmt2 = MulAmt / 3;
23538 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23541 if (isPowerOf2_64(MulAmt2) &&
23542 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23543 // If second multiplifer is pow2, issue it first. We want the multiply by
23544 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23546 std::swap(MulAmt1, MulAmt2);
23549 if (isPowerOf2_64(MulAmt1))
23550 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23551 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23553 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23554 DAG.getConstant(MulAmt1, DL, VT));
23556 if (isPowerOf2_64(MulAmt2))
23557 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23558 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23560 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23561 DAG.getConstant(MulAmt2, DL, VT));
23563 // Do not add new nodes to DAG combiner worklist.
23564 DCI.CombineTo(N, NewMul, false);
23569 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23570 SDValue N0 = N->getOperand(0);
23571 SDValue N1 = N->getOperand(1);
23572 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23573 EVT VT = N0.getValueType();
23575 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23576 // since the result of setcc_c is all zero's or all ones.
23577 if (VT.isInteger() && !VT.isVector() &&
23578 N1C && N0.getOpcode() == ISD::AND &&
23579 N0.getOperand(1).getOpcode() == ISD::Constant) {
23580 SDValue N00 = N0.getOperand(0);
23581 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23582 APInt ShAmt = N1C->getAPIntValue();
23583 Mask = Mask.shl(ShAmt);
23584 bool MaskOK = false;
23585 // We can handle cases concerning bit-widening nodes containing setcc_c if
23586 // we carefully interrogate the mask to make sure we are semantics
23588 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23589 // of the underlying setcc_c operation if the setcc_c was zero extended.
23590 // Consider the following example:
23591 // zext(setcc_c) -> i32 0x0000FFFF
23592 // c1 -> i32 0x0000FFFF
23593 // c2 -> i32 0x00000001
23594 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23595 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
23596 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23598 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23599 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23601 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23602 N00.getOpcode() == ISD::ANY_EXTEND) &&
23603 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23604 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23606 if (MaskOK && Mask != 0) {
23608 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23612 // Hardware support for vector shifts is sparse which makes us scalarize the
23613 // vector operations in many cases. Also, on sandybridge ADD is faster than
23615 // (shl V, 1) -> add V,V
23616 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23617 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23618 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23619 // We shift all of the values by one. In many cases we do not have
23620 // hardware support for this operation. This is better expressed as an ADD
23622 if (N1SplatC->getAPIntValue() == 1)
23623 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23629 /// \brief Returns a vector of 0s if the node in input is a vector logical
23630 /// shift by a constant amount which is known to be bigger than or equal
23631 /// to the vector element size in bits.
23632 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23633 const X86Subtarget *Subtarget) {
23634 EVT VT = N->getValueType(0);
23636 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23637 (!Subtarget->hasInt256() ||
23638 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23641 SDValue Amt = N->getOperand(1);
23643 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23644 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23645 APInt ShiftAmt = AmtSplat->getAPIntValue();
23646 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23648 // SSE2/AVX2 logical shifts always return a vector of 0s
23649 // if the shift amount is bigger than or equal to
23650 // the element size. The constant shift amount will be
23651 // encoded as a 8-bit immediate.
23652 if (ShiftAmt.trunc(8).uge(MaxAmount))
23653 return getZeroVector(VT, Subtarget, DAG, DL);
23659 /// PerformShiftCombine - Combine shifts.
23660 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23661 TargetLowering::DAGCombinerInfo &DCI,
23662 const X86Subtarget *Subtarget) {
23663 if (N->getOpcode() == ISD::SHL)
23664 if (SDValue V = PerformSHLCombine(N, DAG))
23667 // Try to fold this logical shift into a zero vector.
23668 if (N->getOpcode() != ISD::SRA)
23669 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23675 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23676 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23677 // and friends. Likewise for OR -> CMPNEQSS.
23678 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23679 TargetLowering::DAGCombinerInfo &DCI,
23680 const X86Subtarget *Subtarget) {
23683 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23684 // we're requiring SSE2 for both.
23685 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23686 SDValue N0 = N->getOperand(0);
23687 SDValue N1 = N->getOperand(1);
23688 SDValue CMP0 = N0->getOperand(1);
23689 SDValue CMP1 = N1->getOperand(1);
23692 // The SETCCs should both refer to the same CMP.
23693 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23696 SDValue CMP00 = CMP0->getOperand(0);
23697 SDValue CMP01 = CMP0->getOperand(1);
23698 EVT VT = CMP00.getValueType();
23700 if (VT == MVT::f32 || VT == MVT::f64) {
23701 bool ExpectingFlags = false;
23702 // Check for any users that want flags:
23703 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23704 !ExpectingFlags && UI != UE; ++UI)
23705 switch (UI->getOpcode()) {
23710 ExpectingFlags = true;
23712 case ISD::CopyToReg:
23713 case ISD::SIGN_EXTEND:
23714 case ISD::ZERO_EXTEND:
23715 case ISD::ANY_EXTEND:
23719 if (!ExpectingFlags) {
23720 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23721 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23723 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23724 X86::CondCode tmp = cc0;
23729 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23730 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23731 // FIXME: need symbolic constants for these magic numbers.
23732 // See X86ATTInstPrinter.cpp:printSSECC().
23733 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23734 if (Subtarget->hasAVX512()) {
23735 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23737 DAG.getConstant(x86cc, DL, MVT::i8));
23738 if (N->getValueType(0) != MVT::i1)
23739 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23743 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23744 CMP00.getValueType(), CMP00, CMP01,
23745 DAG.getConstant(x86cc, DL,
23748 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23749 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23751 if (is64BitFP && !Subtarget->is64Bit()) {
23752 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23753 // 64-bit integer, since that's not a legal type. Since
23754 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23755 // bits, but can do this little dance to extract the lowest 32 bits
23756 // and work with those going forward.
23757 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23759 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23760 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23761 Vector32, DAG.getIntPtrConstant(0, DL));
23765 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23766 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23767 DAG.getConstant(1, DL, IntVT));
23768 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23770 return OneBitOfTruth;
23778 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23779 /// so it can be folded inside ANDNP.
23780 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23781 EVT VT = N->getValueType(0);
23783 // Match direct AllOnes for 128 and 256-bit vectors
23784 if (ISD::isBuildVectorAllOnes(N))
23787 // Look through a bit convert.
23788 if (N->getOpcode() == ISD::BITCAST)
23789 N = N->getOperand(0).getNode();
23791 // Sometimes the operand may come from a insert_subvector building a 256-bit
23793 if (VT.is256BitVector() &&
23794 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23795 SDValue V1 = N->getOperand(0);
23796 SDValue V2 = N->getOperand(1);
23798 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23799 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23800 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23801 ISD::isBuildVectorAllOnes(V2.getNode()))
23808 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23809 // register. In most cases we actually compare or select YMM-sized registers
23810 // and mixing the two types creates horrible code. This method optimizes
23811 // some of the transition sequences.
23812 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23813 TargetLowering::DAGCombinerInfo &DCI,
23814 const X86Subtarget *Subtarget) {
23815 EVT VT = N->getValueType(0);
23816 if (!VT.is256BitVector())
23819 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23820 N->getOpcode() == ISD::ZERO_EXTEND ||
23821 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23823 SDValue Narrow = N->getOperand(0);
23824 EVT NarrowVT = Narrow->getValueType(0);
23825 if (!NarrowVT.is128BitVector())
23828 if (Narrow->getOpcode() != ISD::XOR &&
23829 Narrow->getOpcode() != ISD::AND &&
23830 Narrow->getOpcode() != ISD::OR)
23833 SDValue N0 = Narrow->getOperand(0);
23834 SDValue N1 = Narrow->getOperand(1);
23837 // The Left side has to be a trunc.
23838 if (N0.getOpcode() != ISD::TRUNCATE)
23841 // The type of the truncated inputs.
23842 EVT WideVT = N0->getOperand(0)->getValueType(0);
23846 // The right side has to be a 'trunc' or a constant vector.
23847 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23848 ConstantSDNode *RHSConstSplat = nullptr;
23849 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23850 RHSConstSplat = RHSBV->getConstantSplatNode();
23851 if (!RHSTrunc && !RHSConstSplat)
23854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23856 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23859 // Set N0 and N1 to hold the inputs to the new wide operation.
23860 N0 = N0->getOperand(0);
23861 if (RHSConstSplat) {
23862 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23863 SDValue(RHSConstSplat, 0));
23864 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23865 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23866 } else if (RHSTrunc) {
23867 N1 = N1->getOperand(0);
23870 // Generate the wide operation.
23871 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23872 unsigned Opcode = N->getOpcode();
23874 case ISD::ANY_EXTEND:
23876 case ISD::ZERO_EXTEND: {
23877 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23878 APInt Mask = APInt::getAllOnesValue(InBits);
23879 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23880 return DAG.getNode(ISD::AND, DL, VT,
23881 Op, DAG.getConstant(Mask, DL, VT));
23883 case ISD::SIGN_EXTEND:
23884 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23885 Op, DAG.getValueType(NarrowVT));
23887 llvm_unreachable("Unexpected opcode");
23891 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23892 TargetLowering::DAGCombinerInfo &DCI,
23893 const X86Subtarget *Subtarget) {
23894 SDValue N0 = N->getOperand(0);
23895 SDValue N1 = N->getOperand(1);
23898 // A vector zext_in_reg may be represented as a shuffle,
23899 // feeding into a bitcast (this represents anyext) feeding into
23900 // an and with a mask.
23901 // We'd like to try to combine that into a shuffle with zero
23902 // plus a bitcast, removing the and.
23903 if (N0.getOpcode() != ISD::BITCAST ||
23904 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23907 // The other side of the AND should be a splat of 2^C, where C
23908 // is the number of bits in the source type.
23909 if (N1.getOpcode() == ISD::BITCAST)
23910 N1 = N1.getOperand(0);
23911 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23913 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23915 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23916 EVT SrcType = Shuffle->getValueType(0);
23918 // We expect a single-source shuffle
23919 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23922 unsigned SrcSize = SrcType.getScalarSizeInBits();
23924 APInt SplatValue, SplatUndef;
23925 unsigned SplatBitSize;
23927 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23928 SplatBitSize, HasAnyUndefs))
23931 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23932 // Make sure the splat matches the mask we expect
23933 if (SplatBitSize > ResSize ||
23934 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23937 // Make sure the input and output size make sense
23938 if (SrcSize >= ResSize || ResSize % SrcSize)
23941 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23942 // The number of u's between each two values depends on the ratio between
23943 // the source and dest type.
23944 unsigned ZextRatio = ResSize / SrcSize;
23945 bool IsZext = true;
23946 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23947 if (i % ZextRatio) {
23948 if (Shuffle->getMaskElt(i) > 0) {
23954 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23955 // Expected element number
23965 // Ok, perform the transformation - replace the shuffle with
23966 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23967 // (instead of undef) where the k elements come from the zero vector.
23968 SmallVector<int, 8> Mask;
23969 unsigned NumElems = SrcType.getVectorNumElements();
23970 for (unsigned i = 0; i < NumElems; ++i)
23972 Mask.push_back(NumElems);
23974 Mask.push_back(i / ZextRatio);
23976 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23977 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23978 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23981 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23982 TargetLowering::DAGCombinerInfo &DCI,
23983 const X86Subtarget *Subtarget) {
23984 if (DCI.isBeforeLegalizeOps())
23987 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23990 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23993 EVT VT = N->getValueType(0);
23994 SDValue N0 = N->getOperand(0);
23995 SDValue N1 = N->getOperand(1);
23998 // Create BEXTR instructions
23999 // BEXTR is ((X >> imm) & (2**size-1))
24000 if (VT == MVT::i32 || VT == MVT::i64) {
24001 // Check for BEXTR.
24002 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24003 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24004 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24005 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24006 if (MaskNode && ShiftNode) {
24007 uint64_t Mask = MaskNode->getZExtValue();
24008 uint64_t Shift = ShiftNode->getZExtValue();
24009 if (isMask_64(Mask)) {
24010 uint64_t MaskSize = countPopulation(Mask);
24011 if (Shift + MaskSize <= VT.getSizeInBits())
24012 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24013 DAG.getConstant(Shift | (MaskSize << 8), DL,
24022 // Want to form ANDNP nodes:
24023 // 1) In the hopes of then easily combining them with OR and AND nodes
24024 // to form PBLEND/PSIGN.
24025 // 2) To match ANDN packed intrinsics
24026 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24029 // Check LHS for vnot
24030 if (N0.getOpcode() == ISD::XOR &&
24031 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24032 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24033 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24035 // Check RHS for vnot
24036 if (N1.getOpcode() == ISD::XOR &&
24037 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24038 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24039 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24044 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24045 TargetLowering::DAGCombinerInfo &DCI,
24046 const X86Subtarget *Subtarget) {
24047 if (DCI.isBeforeLegalizeOps())
24050 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24053 SDValue N0 = N->getOperand(0);
24054 SDValue N1 = N->getOperand(1);
24055 EVT VT = N->getValueType(0);
24057 // look for psign/blend
24058 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24059 if (!Subtarget->hasSSSE3() ||
24060 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24063 // Canonicalize pandn to RHS
24064 if (N0.getOpcode() == X86ISD::ANDNP)
24066 // or (and (m, y), (pandn m, x))
24067 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24068 SDValue Mask = N1.getOperand(0);
24069 SDValue X = N1.getOperand(1);
24071 if (N0.getOperand(0) == Mask)
24072 Y = N0.getOperand(1);
24073 if (N0.getOperand(1) == Mask)
24074 Y = N0.getOperand(0);
24076 // Check to see if the mask appeared in both the AND and ANDNP and
24080 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24081 // Look through mask bitcast.
24082 if (Mask.getOpcode() == ISD::BITCAST)
24083 Mask = Mask.getOperand(0);
24084 if (X.getOpcode() == ISD::BITCAST)
24085 X = X.getOperand(0);
24086 if (Y.getOpcode() == ISD::BITCAST)
24087 Y = Y.getOperand(0);
24089 EVT MaskVT = Mask.getValueType();
24091 // Validate that the Mask operand is a vector sra node.
24092 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24093 // there is no psrai.b
24094 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24095 unsigned SraAmt = ~0;
24096 if (Mask.getOpcode() == ISD::SRA) {
24097 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24098 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24099 SraAmt = AmtConst->getZExtValue();
24100 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24101 SDValue SraC = Mask.getOperand(1);
24102 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24104 if ((SraAmt + 1) != EltBits)
24109 // Now we know we at least have a plendvb with the mask val. See if
24110 // we can form a psignb/w/d.
24111 // psign = x.type == y.type == mask.type && y = sub(0, x);
24112 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24113 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24114 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24115 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24116 "Unsupported VT for PSIGN");
24117 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24118 return DAG.getBitcast(VT, Mask);
24120 // PBLENDVB only available on SSE 4.1
24121 if (!Subtarget->hasSSE41())
24124 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24126 X = DAG.getBitcast(BlendVT, X);
24127 Y = DAG.getBitcast(BlendVT, Y);
24128 Mask = DAG.getBitcast(BlendVT, Mask);
24129 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24130 return DAG.getBitcast(VT, Mask);
24134 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24137 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24138 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24140 // SHLD/SHRD instructions have lower register pressure, but on some
24141 // platforms they have higher latency than the equivalent
24142 // series of shifts/or that would otherwise be generated.
24143 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24144 // have higher latencies and we are not optimizing for size.
24145 if (!OptForSize && Subtarget->isSHLDSlow())
24148 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24150 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24152 if (!N0.hasOneUse() || !N1.hasOneUse())
24155 SDValue ShAmt0 = N0.getOperand(1);
24156 if (ShAmt0.getValueType() != MVT::i8)
24158 SDValue ShAmt1 = N1.getOperand(1);
24159 if (ShAmt1.getValueType() != MVT::i8)
24161 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24162 ShAmt0 = ShAmt0.getOperand(0);
24163 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24164 ShAmt1 = ShAmt1.getOperand(0);
24167 unsigned Opc = X86ISD::SHLD;
24168 SDValue Op0 = N0.getOperand(0);
24169 SDValue Op1 = N1.getOperand(0);
24170 if (ShAmt0.getOpcode() == ISD::SUB) {
24171 Opc = X86ISD::SHRD;
24172 std::swap(Op0, Op1);
24173 std::swap(ShAmt0, ShAmt1);
24176 unsigned Bits = VT.getSizeInBits();
24177 if (ShAmt1.getOpcode() == ISD::SUB) {
24178 SDValue Sum = ShAmt1.getOperand(0);
24179 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24180 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24181 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24182 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24183 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24184 return DAG.getNode(Opc, DL, VT,
24186 DAG.getNode(ISD::TRUNCATE, DL,
24189 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24190 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24192 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24193 return DAG.getNode(Opc, DL, VT,
24194 N0.getOperand(0), N1.getOperand(0),
24195 DAG.getNode(ISD::TRUNCATE, DL,
24202 // Generate NEG and CMOV for integer abs.
24203 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24204 EVT VT = N->getValueType(0);
24206 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24207 // 8-bit integer abs to NEG and CMOV.
24208 if (VT.isInteger() && VT.getSizeInBits() == 8)
24211 SDValue N0 = N->getOperand(0);
24212 SDValue N1 = N->getOperand(1);
24215 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24216 // and change it to SUB and CMOV.
24217 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24218 N0.getOpcode() == ISD::ADD &&
24219 N0.getOperand(1) == N1 &&
24220 N1.getOpcode() == ISD::SRA &&
24221 N1.getOperand(0) == N0.getOperand(0))
24222 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24223 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24224 // Generate SUB & CMOV.
24225 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24226 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24228 SDValue Ops[] = { N0.getOperand(0), Neg,
24229 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24230 SDValue(Neg.getNode(), 1) };
24231 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24236 // Try to turn tests against the signbit in the form of:
24237 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24240 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24241 // This is only worth doing if the output type is i8.
24242 if (N->getValueType(0) != MVT::i8)
24245 SDValue N0 = N->getOperand(0);
24246 SDValue N1 = N->getOperand(1);
24248 // We should be performing an xor against a truncated shift.
24249 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24252 // Make sure we are performing an xor against one.
24253 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24256 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24257 SDValue Shift = N0.getOperand(0);
24258 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24261 // Make sure we are truncating from one of i16, i32 or i64.
24262 EVT ShiftTy = Shift.getValueType();
24263 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24266 // Make sure the shift amount extracts the sign bit.
24267 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24268 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24271 // Create a greater-than comparison against -1.
24272 // N.B. Using SETGE against 0 works but we want a canonical looking
24273 // comparison, using SETGT matches up with what TranslateX86CC.
24275 SDValue ShiftOp = Shift.getOperand(0);
24276 EVT ShiftOpTy = ShiftOp.getValueType();
24277 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24278 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24282 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24283 TargetLowering::DAGCombinerInfo &DCI,
24284 const X86Subtarget *Subtarget) {
24285 if (DCI.isBeforeLegalizeOps())
24288 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24291 if (Subtarget->hasCMov())
24292 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24298 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24299 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24300 TargetLowering::DAGCombinerInfo &DCI,
24301 const X86Subtarget *Subtarget) {
24302 LoadSDNode *Ld = cast<LoadSDNode>(N);
24303 EVT RegVT = Ld->getValueType(0);
24304 EVT MemVT = Ld->getMemoryVT();
24306 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24308 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24309 // into two 16-byte operations.
24310 ISD::LoadExtType Ext = Ld->getExtensionType();
24312 unsigned AddressSpace = Ld->getAddressSpace();
24313 unsigned Alignment = Ld->getAlignment();
24314 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24315 Ext == ISD::NON_EXTLOAD &&
24316 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24317 AddressSpace, Alignment, &Fast) && !Fast) {
24318 unsigned NumElems = RegVT.getVectorNumElements();
24322 SDValue Ptr = Ld->getBasePtr();
24323 SDValue Increment =
24324 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24326 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24328 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24329 Ld->getPointerInfo(), Ld->isVolatile(),
24330 Ld->isNonTemporal(), Ld->isInvariant(),
24332 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24333 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24334 Ld->getPointerInfo(), Ld->isVolatile(),
24335 Ld->isNonTemporal(), Ld->isInvariant(),
24336 std::min(16U, Alignment));
24337 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24339 Load2.getValue(1));
24341 SDValue NewVec = DAG.getUNDEF(RegVT);
24342 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24343 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24344 return DCI.CombineTo(N, NewVec, TF, true);
24350 /// PerformMLOADCombine - Resolve extending loads
24351 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24352 TargetLowering::DAGCombinerInfo &DCI,
24353 const X86Subtarget *Subtarget) {
24354 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24355 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24358 EVT VT = Mld->getValueType(0);
24359 unsigned NumElems = VT.getVectorNumElements();
24360 EVT LdVT = Mld->getMemoryVT();
24363 assert(LdVT != VT && "Cannot extend to the same type");
24364 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24365 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24366 // From, To sizes and ElemCount must be pow of two
24367 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24368 "Unexpected size for extending masked load");
24370 unsigned SizeRatio = ToSz / FromSz;
24371 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24373 // Create a type on which we perform the shuffle
24374 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24375 LdVT.getScalarType(), NumElems*SizeRatio);
24376 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24378 // Convert Src0 value
24379 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24380 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24381 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24382 for (unsigned i = 0; i != NumElems; ++i)
24383 ShuffleVec[i] = i * SizeRatio;
24385 // Can't shuffle using an illegal type.
24386 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24387 && "WideVecVT should be legal");
24388 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24389 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24391 // Prepare the new mask
24393 SDValue Mask = Mld->getMask();
24394 if (Mask.getValueType() == VT) {
24395 // Mask and original value have the same type
24396 NewMask = DAG.getBitcast(WideVecVT, Mask);
24397 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24398 for (unsigned i = 0; i != NumElems; ++i)
24399 ShuffleVec[i] = i * SizeRatio;
24400 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24401 ShuffleVec[i] = NumElems*SizeRatio;
24402 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24403 DAG.getConstant(0, dl, WideVecVT),
24407 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24408 unsigned WidenNumElts = NumElems*SizeRatio;
24409 unsigned MaskNumElts = VT.getVectorNumElements();
24410 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24413 unsigned NumConcat = WidenNumElts / MaskNumElts;
24414 SmallVector<SDValue, 16> Ops(NumConcat);
24415 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24417 for (unsigned i = 1; i != NumConcat; ++i)
24420 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24423 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24424 Mld->getBasePtr(), NewMask, WideSrc0,
24425 Mld->getMemoryVT(), Mld->getMemOperand(),
24427 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24428 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24431 /// PerformMSTORECombine - Resolve truncating stores
24432 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24433 const X86Subtarget *Subtarget) {
24434 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24435 if (!Mst->isTruncatingStore())
24438 EVT VT = Mst->getValue().getValueType();
24439 unsigned NumElems = VT.getVectorNumElements();
24440 EVT StVT = Mst->getMemoryVT();
24443 assert(StVT != VT && "Cannot truncate to the same type");
24444 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24445 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24447 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24449 // The truncating store is legal in some cases. For example
24450 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24451 // are designated for truncate store.
24452 // In this case we don't need any further transformations.
24453 if (TLI.isTruncStoreLegal(VT, StVT))
24456 // From, To sizes and ElemCount must be pow of two
24457 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24458 "Unexpected size for truncating masked store");
24459 // We are going to use the original vector elt for storing.
24460 // Accumulated smaller vector elements must be a multiple of the store size.
24461 assert (((NumElems * FromSz) % ToSz) == 0 &&
24462 "Unexpected ratio for truncating masked store");
24464 unsigned SizeRatio = FromSz / ToSz;
24465 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24467 // Create a type on which we perform the shuffle
24468 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24469 StVT.getScalarType(), NumElems*SizeRatio);
24471 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24473 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24474 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24475 for (unsigned i = 0; i != NumElems; ++i)
24476 ShuffleVec[i] = i * SizeRatio;
24478 // Can't shuffle using an illegal type.
24479 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24480 && "WideVecVT should be legal");
24482 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24483 DAG.getUNDEF(WideVecVT),
24487 SDValue Mask = Mst->getMask();
24488 if (Mask.getValueType() == VT) {
24489 // Mask and original value have the same type
24490 NewMask = DAG.getBitcast(WideVecVT, Mask);
24491 for (unsigned i = 0; i != NumElems; ++i)
24492 ShuffleVec[i] = i * SizeRatio;
24493 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24494 ShuffleVec[i] = NumElems*SizeRatio;
24495 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24496 DAG.getConstant(0, dl, WideVecVT),
24500 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24501 unsigned WidenNumElts = NumElems*SizeRatio;
24502 unsigned MaskNumElts = VT.getVectorNumElements();
24503 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24506 unsigned NumConcat = WidenNumElts / MaskNumElts;
24507 SmallVector<SDValue, 16> Ops(NumConcat);
24508 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24510 for (unsigned i = 1; i != NumConcat; ++i)
24513 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24516 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24517 NewMask, StVT, Mst->getMemOperand(), false);
24519 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24520 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24521 const X86Subtarget *Subtarget) {
24522 StoreSDNode *St = cast<StoreSDNode>(N);
24523 EVT VT = St->getValue().getValueType();
24524 EVT StVT = St->getMemoryVT();
24526 SDValue StoredVal = St->getOperand(1);
24527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24529 // If we are saving a concatenation of two XMM registers and 32-byte stores
24530 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24532 unsigned AddressSpace = St->getAddressSpace();
24533 unsigned Alignment = St->getAlignment();
24534 if (VT.is256BitVector() && StVT == VT &&
24535 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24536 AddressSpace, Alignment, &Fast) && !Fast) {
24537 unsigned NumElems = VT.getVectorNumElements();
24541 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24542 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24545 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24546 SDValue Ptr0 = St->getBasePtr();
24547 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24549 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24550 St->getPointerInfo(), St->isVolatile(),
24551 St->isNonTemporal(), Alignment);
24552 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24553 St->getPointerInfo(), St->isVolatile(),
24554 St->isNonTemporal(),
24555 std::min(16U, Alignment));
24556 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24559 // Optimize trunc store (of multiple scalars) to shuffle and store.
24560 // First, pack all of the elements in one place. Next, store to memory
24561 // in fewer chunks.
24562 if (St->isTruncatingStore() && VT.isVector()) {
24563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24564 unsigned NumElems = VT.getVectorNumElements();
24565 assert(StVT != VT && "Cannot truncate to the same type");
24566 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24567 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24569 // The truncating store is legal in some cases. For example
24570 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24571 // are designated for truncate store.
24572 // In this case we don't need any further transformations.
24573 if (TLI.isTruncStoreLegal(VT, StVT))
24576 // From, To sizes and ElemCount must be pow of two
24577 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24578 // We are going to use the original vector elt for storing.
24579 // Accumulated smaller vector elements must be a multiple of the store size.
24580 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24582 unsigned SizeRatio = FromSz / ToSz;
24584 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24586 // Create a type on which we perform the shuffle
24587 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24588 StVT.getScalarType(), NumElems*SizeRatio);
24590 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24592 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24593 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24594 for (unsigned i = 0; i != NumElems; ++i)
24595 ShuffleVec[i] = i * SizeRatio;
24597 // Can't shuffle using an illegal type.
24598 if (!TLI.isTypeLegal(WideVecVT))
24601 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24602 DAG.getUNDEF(WideVecVT),
24604 // At this point all of the data is stored at the bottom of the
24605 // register. We now need to save it to mem.
24607 // Find the largest store unit
24608 MVT StoreType = MVT::i8;
24609 for (MVT Tp : MVT::integer_valuetypes()) {
24610 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24614 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24615 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24616 (64 <= NumElems * ToSz))
24617 StoreType = MVT::f64;
24619 // Bitcast the original vector into a vector of store-size units
24620 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24621 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24622 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24623 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24624 SmallVector<SDValue, 8> Chains;
24625 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24626 TLI.getPointerTy(DAG.getDataLayout()));
24627 SDValue Ptr = St->getBasePtr();
24629 // Perform one or more big stores into memory.
24630 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24631 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24632 StoreType, ShuffWide,
24633 DAG.getIntPtrConstant(i, dl));
24634 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24635 St->getPointerInfo(), St->isVolatile(),
24636 St->isNonTemporal(), St->getAlignment());
24637 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24638 Chains.push_back(Ch);
24641 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24644 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24645 // the FP state in cases where an emms may be missing.
24646 // A preferable solution to the general problem is to figure out the right
24647 // places to insert EMMS. This qualifies as a quick hack.
24649 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24650 if (VT.getSizeInBits() != 64)
24653 const Function *F = DAG.getMachineFunction().getFunction();
24654 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24656 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24657 if ((VT.isVector() ||
24658 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24659 isa<LoadSDNode>(St->getValue()) &&
24660 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24661 St->getChain().hasOneUse() && !St->isVolatile()) {
24662 SDNode* LdVal = St->getValue().getNode();
24663 LoadSDNode *Ld = nullptr;
24664 int TokenFactorIndex = -1;
24665 SmallVector<SDValue, 8> Ops;
24666 SDNode* ChainVal = St->getChain().getNode();
24667 // Must be a store of a load. We currently handle two cases: the load
24668 // is a direct child, and it's under an intervening TokenFactor. It is
24669 // possible to dig deeper under nested TokenFactors.
24670 if (ChainVal == LdVal)
24671 Ld = cast<LoadSDNode>(St->getChain());
24672 else if (St->getValue().hasOneUse() &&
24673 ChainVal->getOpcode() == ISD::TokenFactor) {
24674 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24675 if (ChainVal->getOperand(i).getNode() == LdVal) {
24676 TokenFactorIndex = i;
24677 Ld = cast<LoadSDNode>(St->getValue());
24679 Ops.push_back(ChainVal->getOperand(i));
24683 if (!Ld || !ISD::isNormalLoad(Ld))
24686 // If this is not the MMX case, i.e. we are just turning i64 load/store
24687 // into f64 load/store, avoid the transformation if there are multiple
24688 // uses of the loaded value.
24689 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24694 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24695 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24697 if (Subtarget->is64Bit() || F64IsLegal) {
24698 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24699 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24700 Ld->getPointerInfo(), Ld->isVolatile(),
24701 Ld->isNonTemporal(), Ld->isInvariant(),
24702 Ld->getAlignment());
24703 SDValue NewChain = NewLd.getValue(1);
24704 if (TokenFactorIndex != -1) {
24705 Ops.push_back(NewChain);
24706 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24708 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24709 St->getPointerInfo(),
24710 St->isVolatile(), St->isNonTemporal(),
24711 St->getAlignment());
24714 // Otherwise, lower to two pairs of 32-bit loads / stores.
24715 SDValue LoAddr = Ld->getBasePtr();
24716 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24717 DAG.getConstant(4, LdDL, MVT::i32));
24719 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24720 Ld->getPointerInfo(),
24721 Ld->isVolatile(), Ld->isNonTemporal(),
24722 Ld->isInvariant(), Ld->getAlignment());
24723 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24724 Ld->getPointerInfo().getWithOffset(4),
24725 Ld->isVolatile(), Ld->isNonTemporal(),
24727 MinAlign(Ld->getAlignment(), 4));
24729 SDValue NewChain = LoLd.getValue(1);
24730 if (TokenFactorIndex != -1) {
24731 Ops.push_back(LoLd);
24732 Ops.push_back(HiLd);
24733 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24736 LoAddr = St->getBasePtr();
24737 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24738 DAG.getConstant(4, StDL, MVT::i32));
24740 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24741 St->getPointerInfo(),
24742 St->isVolatile(), St->isNonTemporal(),
24743 St->getAlignment());
24744 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24745 St->getPointerInfo().getWithOffset(4),
24747 St->isNonTemporal(),
24748 MinAlign(St->getAlignment(), 4));
24749 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24752 // This is similar to the above case, but here we handle a scalar 64-bit
24753 // integer store that is extracted from a vector on a 32-bit target.
24754 // If we have SSE2, then we can treat it like a floating-point double
24755 // to get past legalization. The execution dependencies fixup pass will
24756 // choose the optimal machine instruction for the store if this really is
24757 // an integer or v2f32 rather than an f64.
24758 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24759 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24760 SDValue OldExtract = St->getOperand(1);
24761 SDValue ExtOp0 = OldExtract.getOperand(0);
24762 unsigned VecSize = ExtOp0.getValueSizeInBits();
24763 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24764 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24765 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24766 BitCast, OldExtract.getOperand(1));
24767 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24768 St->getPointerInfo(), St->isVolatile(),
24769 St->isNonTemporal(), St->getAlignment());
24775 /// Return 'true' if this vector operation is "horizontal"
24776 /// and return the operands for the horizontal operation in LHS and RHS. A
24777 /// horizontal operation performs the binary operation on successive elements
24778 /// of its first operand, then on successive elements of its second operand,
24779 /// returning the resulting values in a vector. For example, if
24780 /// A = < float a0, float a1, float a2, float a3 >
24782 /// B = < float b0, float b1, float b2, float b3 >
24783 /// then the result of doing a horizontal operation on A and B is
24784 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24785 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24786 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24787 /// set to A, RHS to B, and the routine returns 'true'.
24788 /// Note that the binary operation should have the property that if one of the
24789 /// operands is UNDEF then the result is UNDEF.
24790 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24791 // Look for the following pattern: if
24792 // A = < float a0, float a1, float a2, float a3 >
24793 // B = < float b0, float b1, float b2, float b3 >
24795 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24796 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24797 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24798 // which is A horizontal-op B.
24800 // At least one of the operands should be a vector shuffle.
24801 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24802 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24805 MVT VT = LHS.getSimpleValueType();
24807 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24808 "Unsupported vector type for horizontal add/sub");
24810 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24811 // operate independently on 128-bit lanes.
24812 unsigned NumElts = VT.getVectorNumElements();
24813 unsigned NumLanes = VT.getSizeInBits()/128;
24814 unsigned NumLaneElts = NumElts / NumLanes;
24815 assert((NumLaneElts % 2 == 0) &&
24816 "Vector type should have an even number of elements in each lane");
24817 unsigned HalfLaneElts = NumLaneElts/2;
24819 // View LHS in the form
24820 // LHS = VECTOR_SHUFFLE A, B, LMask
24821 // If LHS is not a shuffle then pretend it is the shuffle
24822 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24823 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24826 SmallVector<int, 16> LMask(NumElts);
24827 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24828 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24829 A = LHS.getOperand(0);
24830 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24831 B = LHS.getOperand(1);
24832 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24833 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24835 if (LHS.getOpcode() != ISD::UNDEF)
24837 for (unsigned i = 0; i != NumElts; ++i)
24841 // Likewise, view RHS in the form
24842 // RHS = VECTOR_SHUFFLE C, D, RMask
24844 SmallVector<int, 16> RMask(NumElts);
24845 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24846 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24847 C = RHS.getOperand(0);
24848 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24849 D = RHS.getOperand(1);
24850 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24851 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24853 if (RHS.getOpcode() != ISD::UNDEF)
24855 for (unsigned i = 0; i != NumElts; ++i)
24859 // Check that the shuffles are both shuffling the same vectors.
24860 if (!(A == C && B == D) && !(A == D && B == C))
24863 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24864 if (!A.getNode() && !B.getNode())
24867 // If A and B occur in reverse order in RHS, then "swap" them (which means
24868 // rewriting the mask).
24870 ShuffleVectorSDNode::commuteMask(RMask);
24872 // At this point LHS and RHS are equivalent to
24873 // LHS = VECTOR_SHUFFLE A, B, LMask
24874 // RHS = VECTOR_SHUFFLE A, B, RMask
24875 // Check that the masks correspond to performing a horizontal operation.
24876 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24877 for (unsigned i = 0; i != NumLaneElts; ++i) {
24878 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24880 // Ignore any UNDEF components.
24881 if (LIdx < 0 || RIdx < 0 ||
24882 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24883 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24886 // Check that successive elements are being operated on. If not, this is
24887 // not a horizontal operation.
24888 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24889 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24890 if (!(LIdx == Index && RIdx == Index + 1) &&
24891 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24896 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24897 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24901 /// Do target-specific dag combines on floating point adds.
24902 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24903 const X86Subtarget *Subtarget) {
24904 EVT VT = N->getValueType(0);
24905 SDValue LHS = N->getOperand(0);
24906 SDValue RHS = N->getOperand(1);
24908 // Try to synthesize horizontal adds from adds of shuffles.
24909 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24910 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24911 isHorizontalBinOp(LHS, RHS, true))
24912 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24916 /// Do target-specific dag combines on floating point subs.
24917 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24918 const X86Subtarget *Subtarget) {
24919 EVT VT = N->getValueType(0);
24920 SDValue LHS = N->getOperand(0);
24921 SDValue RHS = N->getOperand(1);
24923 // Try to synthesize horizontal subs from subs of shuffles.
24924 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24925 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24926 isHorizontalBinOp(LHS, RHS, false))
24927 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24931 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24932 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24933 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24935 // F[X]OR(0.0, x) -> x
24936 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24937 if (C->getValueAPF().isPosZero())
24938 return N->getOperand(1);
24940 // F[X]OR(x, 0.0) -> x
24941 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24942 if (C->getValueAPF().isPosZero())
24943 return N->getOperand(0);
24947 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24948 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24949 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24951 // Only perform optimizations if UnsafeMath is used.
24952 if (!DAG.getTarget().Options.UnsafeFPMath)
24955 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24956 // into FMINC and FMAXC, which are Commutative operations.
24957 unsigned NewOp = 0;
24958 switch (N->getOpcode()) {
24959 default: llvm_unreachable("unknown opcode");
24960 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24961 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24964 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24965 N->getOperand(0), N->getOperand(1));
24968 /// Do target-specific dag combines on X86ISD::FAND nodes.
24969 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24970 // FAND(0.0, x) -> 0.0
24971 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24972 if (C->getValueAPF().isPosZero())
24973 return N->getOperand(0);
24975 // FAND(x, 0.0) -> 0.0
24976 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24977 if (C->getValueAPF().isPosZero())
24978 return N->getOperand(1);
24983 /// Do target-specific dag combines on X86ISD::FANDN nodes
24984 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24985 // FANDN(0.0, x) -> x
24986 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24987 if (C->getValueAPF().isPosZero())
24988 return N->getOperand(1);
24990 // FANDN(x, 0.0) -> 0.0
24991 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24992 if (C->getValueAPF().isPosZero())
24993 return N->getOperand(1);
24998 static SDValue PerformBTCombine(SDNode *N,
25000 TargetLowering::DAGCombinerInfo &DCI) {
25001 // BT ignores high bits in the bit index operand.
25002 SDValue Op1 = N->getOperand(1);
25003 if (Op1.hasOneUse()) {
25004 unsigned BitWidth = Op1.getValueSizeInBits();
25005 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25006 APInt KnownZero, KnownOne;
25007 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25008 !DCI.isBeforeLegalizeOps());
25009 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25010 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25011 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25012 DCI.CommitTargetLoweringOpt(TLO);
25017 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25018 SDValue Op = N->getOperand(0);
25019 if (Op.getOpcode() == ISD::BITCAST)
25020 Op = Op.getOperand(0);
25021 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25022 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25023 VT.getVectorElementType().getSizeInBits() ==
25024 OpVT.getVectorElementType().getSizeInBits()) {
25025 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25030 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25031 const X86Subtarget *Subtarget) {
25032 EVT VT = N->getValueType(0);
25033 if (!VT.isVector())
25036 SDValue N0 = N->getOperand(0);
25037 SDValue N1 = N->getOperand(1);
25038 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25041 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25042 // both SSE and AVX2 since there is no sign-extended shift right
25043 // operation on a vector with 64-bit elements.
25044 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25045 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25046 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25047 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25048 SDValue N00 = N0.getOperand(0);
25050 // EXTLOAD has a better solution on AVX2,
25051 // it may be replaced with X86ISD::VSEXT node.
25052 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25053 if (!ISD::isNormalLoad(N00.getNode()))
25056 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25057 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25059 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25065 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25066 TargetLowering::DAGCombinerInfo &DCI,
25067 const X86Subtarget *Subtarget) {
25068 SDValue N0 = N->getOperand(0);
25069 EVT VT = N->getValueType(0);
25070 EVT SVT = VT.getScalarType();
25071 EVT InVT = N0.getValueType();
25072 EVT InSVT = InVT.getScalarType();
25075 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25076 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25077 // This exposes the sext to the sdivrem lowering, so that it directly extends
25078 // from AH (which we otherwise need to do contortions to access).
25079 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25080 InVT == MVT::i8 && VT == MVT::i32) {
25081 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25082 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25083 N0.getOperand(0), N0.getOperand(1));
25084 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25085 return R.getValue(1);
25088 if (!DCI.isBeforeLegalizeOps()) {
25089 if (InVT == MVT::i1) {
25090 SDValue Zero = DAG.getConstant(0, DL, VT);
25092 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25093 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25098 if (VT.isVector() && Subtarget->hasSSE2()) {
25099 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25100 EVT InVT = N.getValueType();
25101 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25102 Size / InVT.getScalarSizeInBits());
25103 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25104 DAG.getUNDEF(InVT));
25106 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25109 // If target-size is less than 128-bits, extend to a type that would extend
25110 // to 128 bits, extend that and extract the original target vector.
25111 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25112 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25113 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25114 unsigned Scale = 128 / VT.getSizeInBits();
25116 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25117 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25118 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25119 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25120 DAG.getIntPtrConstant(0, DL));
25123 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25124 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25125 if (VT.getSizeInBits() == 128 &&
25126 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25127 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25128 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25129 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25132 // On pre-AVX2 targets, split into 128-bit nodes of
25133 // ISD::SIGN_EXTEND_VECTOR_INREG.
25134 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25135 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25136 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25137 unsigned NumVecs = VT.getSizeInBits() / 128;
25138 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25139 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25140 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25142 SmallVector<SDValue, 8> Opnds;
25143 for (unsigned i = 0, Offset = 0; i != NumVecs;
25144 ++i, Offset += NumSubElts) {
25145 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25146 DAG.getIntPtrConstant(Offset, DL));
25147 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25148 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25149 Opnds.push_back(SrcVec);
25151 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25155 if (!Subtarget->hasFp256())
25158 if (VT.isVector() && VT.getSizeInBits() == 256)
25159 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25165 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25166 const X86Subtarget* Subtarget) {
25168 EVT VT = N->getValueType(0);
25170 // Let legalize expand this if it isn't a legal type yet.
25171 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25174 EVT ScalarVT = VT.getScalarType();
25175 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25176 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25177 !Subtarget->hasAVX512()))
25180 SDValue A = N->getOperand(0);
25181 SDValue B = N->getOperand(1);
25182 SDValue C = N->getOperand(2);
25184 bool NegA = (A.getOpcode() == ISD::FNEG);
25185 bool NegB = (B.getOpcode() == ISD::FNEG);
25186 bool NegC = (C.getOpcode() == ISD::FNEG);
25188 // Negative multiplication when NegA xor NegB
25189 bool NegMul = (NegA != NegB);
25191 A = A.getOperand(0);
25193 B = B.getOperand(0);
25195 C = C.getOperand(0);
25199 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25201 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25203 return DAG.getNode(Opcode, dl, VT, A, B, C);
25206 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25207 TargetLowering::DAGCombinerInfo &DCI,
25208 const X86Subtarget *Subtarget) {
25209 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25210 // (and (i32 x86isd::setcc_carry), 1)
25211 // This eliminates the zext. This transformation is necessary because
25212 // ISD::SETCC is always legalized to i8.
25214 SDValue N0 = N->getOperand(0);
25215 EVT VT = N->getValueType(0);
25217 if (N0.getOpcode() == ISD::AND &&
25219 N0.getOperand(0).hasOneUse()) {
25220 SDValue N00 = N0.getOperand(0);
25221 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25222 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25223 if (!C || C->getZExtValue() != 1)
25225 return DAG.getNode(ISD::AND, dl, VT,
25226 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25227 N00.getOperand(0), N00.getOperand(1)),
25228 DAG.getConstant(1, dl, VT));
25232 if (N0.getOpcode() == ISD::TRUNCATE &&
25234 N0.getOperand(0).hasOneUse()) {
25235 SDValue N00 = N0.getOperand(0);
25236 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25237 return DAG.getNode(ISD::AND, dl, VT,
25238 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25239 N00.getOperand(0), N00.getOperand(1)),
25240 DAG.getConstant(1, dl, VT));
25244 if (VT.is256BitVector())
25245 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25248 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25249 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25250 // This exposes the zext to the udivrem lowering, so that it directly extends
25251 // from AH (which we otherwise need to do contortions to access).
25252 if (N0.getOpcode() == ISD::UDIVREM &&
25253 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25254 (VT == MVT::i32 || VT == MVT::i64)) {
25255 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25256 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25257 N0.getOperand(0), N0.getOperand(1));
25258 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25259 return R.getValue(1);
25265 // Optimize x == -y --> x+y == 0
25266 // x != -y --> x+y != 0
25267 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25268 const X86Subtarget* Subtarget) {
25269 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25270 SDValue LHS = N->getOperand(0);
25271 SDValue RHS = N->getOperand(1);
25272 EVT VT = N->getValueType(0);
25275 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25277 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25278 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25279 LHS.getOperand(1));
25280 return DAG.getSetCC(DL, N->getValueType(0), addV,
25281 DAG.getConstant(0, DL, addV.getValueType()), CC);
25283 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25284 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25285 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25286 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25287 RHS.getOperand(1));
25288 return DAG.getSetCC(DL, N->getValueType(0), addV,
25289 DAG.getConstant(0, DL, addV.getValueType()), CC);
25292 if (VT.getScalarType() == MVT::i1 &&
25293 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25295 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25296 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25297 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25299 if (!IsSEXT0 || !IsVZero1) {
25300 // Swap the operands and update the condition code.
25301 std::swap(LHS, RHS);
25302 CC = ISD::getSetCCSwappedOperands(CC);
25304 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25305 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25306 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25309 if (IsSEXT0 && IsVZero1) {
25310 assert(VT == LHS.getOperand(0).getValueType() &&
25311 "Uexpected operand type");
25312 if (CC == ISD::SETGT)
25313 return DAG.getConstant(0, DL, VT);
25314 if (CC == ISD::SETLE)
25315 return DAG.getConstant(1, DL, VT);
25316 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25317 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25319 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25320 "Unexpected condition code!");
25321 return LHS.getOperand(0);
25328 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25329 SelectionDAG &DAG) {
25331 MVT VT = Load->getSimpleValueType(0);
25332 MVT EVT = VT.getVectorElementType();
25333 SDValue Addr = Load->getOperand(1);
25334 SDValue NewAddr = DAG.getNode(
25335 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25336 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25337 Addr.getSimpleValueType()));
25340 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25341 DAG.getMachineFunction().getMachineMemOperand(
25342 Load->getMemOperand(), 0, EVT.getStoreSize()));
25346 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25347 const X86Subtarget *Subtarget) {
25349 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25350 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25351 "X86insertps is only defined for v4x32");
25353 SDValue Ld = N->getOperand(1);
25354 if (MayFoldLoad(Ld)) {
25355 // Extract the countS bits from the immediate so we can get the proper
25356 // address when narrowing the vector load to a specific element.
25357 // When the second source op is a memory address, insertps doesn't use
25358 // countS and just gets an f32 from that address.
25359 unsigned DestIndex =
25360 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25362 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25364 // Create this as a scalar to vector to match the instruction pattern.
25365 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25366 // countS bits are ignored when loading from memory on insertps, which
25367 // means we don't need to explicitly set them to 0.
25368 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25369 LoadScalarToVector, N->getOperand(2));
25374 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25375 SDValue V0 = N->getOperand(0);
25376 SDValue V1 = N->getOperand(1);
25378 EVT VT = N->getValueType(0);
25380 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25381 // operands and changing the mask to 1. This saves us a bunch of
25382 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25383 // x86InstrInfo knows how to commute this back after instruction selection
25384 // if it would help register allocation.
25386 // TODO: If optimizing for size or a processor that doesn't suffer from
25387 // partial register update stalls, this should be transformed into a MOVSD
25388 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25390 if (VT == MVT::v2f64)
25391 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25392 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25393 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25394 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25400 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25401 // as "sbb reg,reg", since it can be extended without zext and produces
25402 // an all-ones bit which is more useful than 0/1 in some cases.
25403 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25406 return DAG.getNode(ISD::AND, DL, VT,
25407 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25408 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25410 DAG.getConstant(1, DL, VT));
25411 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25412 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25413 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25414 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25418 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25419 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25420 TargetLowering::DAGCombinerInfo &DCI,
25421 const X86Subtarget *Subtarget) {
25423 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25424 SDValue EFLAGS = N->getOperand(1);
25426 if (CC == X86::COND_A) {
25427 // Try to convert COND_A into COND_B in an attempt to facilitate
25428 // materializing "setb reg".
25430 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25431 // cannot take an immediate as its first operand.
25433 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25434 EFLAGS.getValueType().isInteger() &&
25435 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25436 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25437 EFLAGS.getNode()->getVTList(),
25438 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25439 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25440 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25444 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25445 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25447 if (CC == X86::COND_B)
25448 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25450 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25451 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25452 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25458 // Optimize branch condition evaluation.
25460 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25461 TargetLowering::DAGCombinerInfo &DCI,
25462 const X86Subtarget *Subtarget) {
25464 SDValue Chain = N->getOperand(0);
25465 SDValue Dest = N->getOperand(1);
25466 SDValue EFLAGS = N->getOperand(3);
25467 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25469 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25470 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25471 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25478 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25479 SelectionDAG &DAG) {
25480 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25481 // optimize away operation when it's from a constant.
25483 // The general transformation is:
25484 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25485 // AND(VECTOR_CMP(x,y), constant2)
25486 // constant2 = UNARYOP(constant)
25488 // Early exit if this isn't a vector operation, the operand of the
25489 // unary operation isn't a bitwise AND, or if the sizes of the operations
25490 // aren't the same.
25491 EVT VT = N->getValueType(0);
25492 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25493 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25494 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25497 // Now check that the other operand of the AND is a constant. We could
25498 // make the transformation for non-constant splats as well, but it's unclear
25499 // that would be a benefit as it would not eliminate any operations, just
25500 // perform one more step in scalar code before moving to the vector unit.
25501 if (BuildVectorSDNode *BV =
25502 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25503 // Bail out if the vector isn't a constant.
25504 if (!BV->isConstant())
25507 // Everything checks out. Build up the new and improved node.
25509 EVT IntVT = BV->getValueType(0);
25510 // Create a new constant of the appropriate type for the transformed
25512 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25513 // The AND node needs bitcasts to/from an integer vector type around it.
25514 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25515 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25516 N->getOperand(0)->getOperand(0), MaskConst);
25517 SDValue Res = DAG.getBitcast(VT, NewAnd);
25524 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25525 const X86Subtarget *Subtarget) {
25526 SDValue Op0 = N->getOperand(0);
25527 EVT VT = N->getValueType(0);
25528 EVT InVT = Op0.getValueType();
25529 EVT InSVT = InVT.getScalarType();
25530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25532 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25533 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25534 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25536 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25537 InVT.getVectorNumElements());
25538 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25540 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25541 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25543 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25549 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25550 const X86Subtarget *Subtarget) {
25551 // First try to optimize away the conversion entirely when it's
25552 // conditionally from a constant. Vectors only.
25553 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25556 // Now move on to more general possibilities.
25557 SDValue Op0 = N->getOperand(0);
25558 EVT VT = N->getValueType(0);
25559 EVT InVT = Op0.getValueType();
25560 EVT InSVT = InVT.getScalarType();
25562 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25563 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25564 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25566 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25567 InVT.getVectorNumElements());
25568 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25569 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25572 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25573 // a 32-bit target where SSE doesn't support i64->FP operations.
25574 if (Op0.getOpcode() == ISD::LOAD) {
25575 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25576 EVT LdVT = Ld->getValueType(0);
25578 // This transformation is not supported if the result type is f16
25579 if (VT == MVT::f16)
25582 if (!Ld->isVolatile() && !VT.isVector() &&
25583 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25584 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25585 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25586 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25587 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25594 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25595 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25596 X86TargetLowering::DAGCombinerInfo &DCI) {
25597 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25598 // the result is either zero or one (depending on the input carry bit).
25599 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25600 if (X86::isZeroNode(N->getOperand(0)) &&
25601 X86::isZeroNode(N->getOperand(1)) &&
25602 // We don't have a good way to replace an EFLAGS use, so only do this when
25604 SDValue(N, 1).use_empty()) {
25606 EVT VT = N->getValueType(0);
25607 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25608 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25609 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25610 DAG.getConstant(X86::COND_B, DL,
25613 DAG.getConstant(1, DL, VT));
25614 return DCI.CombineTo(N, Res1, CarryOut);
25620 // fold (add Y, (sete X, 0)) -> adc 0, Y
25621 // (add Y, (setne X, 0)) -> sbb -1, Y
25622 // (sub (sete X, 0), Y) -> sbb 0, Y
25623 // (sub (setne X, 0), Y) -> adc -1, Y
25624 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25627 // Look through ZExts.
25628 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25629 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25632 SDValue SetCC = Ext.getOperand(0);
25633 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25636 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25637 if (CC != X86::COND_E && CC != X86::COND_NE)
25640 SDValue Cmp = SetCC.getOperand(1);
25641 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25642 !X86::isZeroNode(Cmp.getOperand(1)) ||
25643 !Cmp.getOperand(0).getValueType().isInteger())
25646 SDValue CmpOp0 = Cmp.getOperand(0);
25647 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25648 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25650 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25651 if (CC == X86::COND_NE)
25652 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25653 DL, OtherVal.getValueType(), OtherVal,
25654 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25656 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25657 DL, OtherVal.getValueType(), OtherVal,
25658 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25661 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25662 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25663 const X86Subtarget *Subtarget) {
25664 EVT VT = N->getValueType(0);
25665 SDValue Op0 = N->getOperand(0);
25666 SDValue Op1 = N->getOperand(1);
25668 // Try to synthesize horizontal adds from adds of shuffles.
25669 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25670 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25671 isHorizontalBinOp(Op0, Op1, true))
25672 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25674 return OptimizeConditionalInDecrement(N, DAG);
25677 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25678 const X86Subtarget *Subtarget) {
25679 SDValue Op0 = N->getOperand(0);
25680 SDValue Op1 = N->getOperand(1);
25682 // X86 can't encode an immediate LHS of a sub. See if we can push the
25683 // negation into a preceding instruction.
25684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25685 // If the RHS of the sub is a XOR with one use and a constant, invert the
25686 // immediate. Then add one to the LHS of the sub so we can turn
25687 // X-Y -> X+~Y+1, saving one register.
25688 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25689 isa<ConstantSDNode>(Op1.getOperand(1))) {
25690 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25691 EVT VT = Op0.getValueType();
25692 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25694 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25695 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25696 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25700 // Try to synthesize horizontal adds from adds of shuffles.
25701 EVT VT = N->getValueType(0);
25702 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25703 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25704 isHorizontalBinOp(Op0, Op1, true))
25705 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25707 return OptimizeConditionalInDecrement(N, DAG);
25710 /// performVZEXTCombine - Performs build vector combines
25711 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25712 TargetLowering::DAGCombinerInfo &DCI,
25713 const X86Subtarget *Subtarget) {
25715 MVT VT = N->getSimpleValueType(0);
25716 SDValue Op = N->getOperand(0);
25717 MVT OpVT = Op.getSimpleValueType();
25718 MVT OpEltVT = OpVT.getVectorElementType();
25719 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25721 // (vzext (bitcast (vzext (x)) -> (vzext x)
25723 while (V.getOpcode() == ISD::BITCAST)
25724 V = V.getOperand(0);
25726 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25727 MVT InnerVT = V.getSimpleValueType();
25728 MVT InnerEltVT = InnerVT.getVectorElementType();
25730 // If the element sizes match exactly, we can just do one larger vzext. This
25731 // is always an exact type match as vzext operates on integer types.
25732 if (OpEltVT == InnerEltVT) {
25733 assert(OpVT == InnerVT && "Types must match for vzext!");
25734 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25737 // The only other way we can combine them is if only a single element of the
25738 // inner vzext is used in the input to the outer vzext.
25739 if (InnerEltVT.getSizeInBits() < InputBits)
25742 // In this case, the inner vzext is completely dead because we're going to
25743 // only look at bits inside of the low element. Just do the outer vzext on
25744 // a bitcast of the input to the inner.
25745 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25748 // Check if we can bypass extracting and re-inserting an element of an input
25749 // vector. Essentially:
25750 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25751 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25752 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25753 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25754 SDValue ExtractedV = V.getOperand(0);
25755 SDValue OrigV = ExtractedV.getOperand(0);
25756 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25757 if (ExtractIdx->getZExtValue() == 0) {
25758 MVT OrigVT = OrigV.getSimpleValueType();
25759 // Extract a subvector if necessary...
25760 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25761 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25762 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25763 OrigVT.getVectorNumElements() / Ratio);
25764 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25765 DAG.getIntPtrConstant(0, DL));
25767 Op = DAG.getBitcast(OpVT, OrigV);
25768 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25775 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25776 DAGCombinerInfo &DCI) const {
25777 SelectionDAG &DAG = DCI.DAG;
25778 switch (N->getOpcode()) {
25780 case ISD::EXTRACT_VECTOR_ELT:
25781 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25784 case X86ISD::SHRUNKBLEND:
25785 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25786 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25787 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25788 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25789 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25790 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25791 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25794 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25795 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25796 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25797 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25798 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25799 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25800 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25801 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25802 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25803 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25804 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25805 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25807 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25809 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25810 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25811 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25812 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25813 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25814 case ISD::ANY_EXTEND:
25815 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25816 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25817 case ISD::SIGN_EXTEND_INREG:
25818 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25819 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25820 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25821 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25822 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25823 case X86ISD::SHUFP: // Handle all target specific shuffles
25824 case X86ISD::PALIGNR:
25825 case X86ISD::UNPCKH:
25826 case X86ISD::UNPCKL:
25827 case X86ISD::MOVHLPS:
25828 case X86ISD::MOVLHPS:
25829 case X86ISD::PSHUFB:
25830 case X86ISD::PSHUFD:
25831 case X86ISD::PSHUFHW:
25832 case X86ISD::PSHUFLW:
25833 case X86ISD::MOVSS:
25834 case X86ISD::MOVSD:
25835 case X86ISD::VPERMILPI:
25836 case X86ISD::VPERM2X128:
25837 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25838 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25839 case X86ISD::INSERTPS: {
25840 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25841 return PerformINSERTPSCombine(N, DAG, Subtarget);
25844 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25850 /// isTypeDesirableForOp - Return true if the target has native support for
25851 /// the specified value type and it is 'desirable' to use the type for the
25852 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25853 /// instruction encodings are longer and some i16 instructions are slow.
25854 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25855 if (!isTypeLegal(VT))
25857 if (VT != MVT::i16)
25864 case ISD::SIGN_EXTEND:
25865 case ISD::ZERO_EXTEND:
25866 case ISD::ANY_EXTEND:
25879 /// IsDesirableToPromoteOp - This method query the target whether it is
25880 /// beneficial for dag combiner to promote the specified node. If true, it
25881 /// should return the desired promotion type by reference.
25882 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25883 EVT VT = Op.getValueType();
25884 if (VT != MVT::i16)
25887 bool Promote = false;
25888 bool Commute = false;
25889 switch (Op.getOpcode()) {
25892 LoadSDNode *LD = cast<LoadSDNode>(Op);
25893 // If the non-extending load has a single use and it's not live out, then it
25894 // might be folded.
25895 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25896 Op.hasOneUse()*/) {
25897 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25898 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25899 // The only case where we'd want to promote LOAD (rather then it being
25900 // promoted as an operand is when it's only use is liveout.
25901 if (UI->getOpcode() != ISD::CopyToReg)
25908 case ISD::SIGN_EXTEND:
25909 case ISD::ZERO_EXTEND:
25910 case ISD::ANY_EXTEND:
25915 SDValue N0 = Op.getOperand(0);
25916 // Look out for (store (shl (load), x)).
25917 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25930 SDValue N0 = Op.getOperand(0);
25931 SDValue N1 = Op.getOperand(1);
25932 if (!Commute && MayFoldLoad(N1))
25934 // Avoid disabling potential load folding opportunities.
25935 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25937 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25947 //===----------------------------------------------------------------------===//
25948 // X86 Inline Assembly Support
25949 //===----------------------------------------------------------------------===//
25951 // Helper to match a string separated by whitespace.
25952 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25953 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25955 for (StringRef Piece : Pieces) {
25956 if (!S.startswith(Piece)) // Check if the piece matches.
25959 S = S.substr(Piece.size());
25960 StringRef::size_type Pos = S.find_first_not_of(" \t");
25961 if (Pos == 0) // We matched a prefix.
25970 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25972 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25973 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25974 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25975 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25977 if (AsmPieces.size() == 3)
25979 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25986 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25987 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25989 std::string AsmStr = IA->getAsmString();
25991 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25992 if (!Ty || Ty->getBitWidth() % 16 != 0)
25995 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25996 SmallVector<StringRef, 4> AsmPieces;
25997 SplitString(AsmStr, AsmPieces, ";\n");
25999 switch (AsmPieces.size()) {
26000 default: return false;
26002 // FIXME: this should verify that we are targeting a 486 or better. If not,
26003 // we will turn this bswap into something that will be lowered to logical
26004 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26005 // lower so don't worry about this.
26007 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26008 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26009 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26010 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26011 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26012 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26013 // No need to check constraints, nothing other than the equivalent of
26014 // "=r,0" would be valid here.
26015 return IntrinsicLowering::LowerToByteSwap(CI);
26018 // rorw $$8, ${0:w} --> llvm.bswap.i16
26019 if (CI->getType()->isIntegerTy(16) &&
26020 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26021 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26022 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26024 StringRef ConstraintsStr = IA->getConstraintString();
26025 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26026 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26027 if (clobbersFlagRegisters(AsmPieces))
26028 return IntrinsicLowering::LowerToByteSwap(CI);
26032 if (CI->getType()->isIntegerTy(32) &&
26033 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26034 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26035 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26036 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26038 StringRef ConstraintsStr = IA->getConstraintString();
26039 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26040 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26041 if (clobbersFlagRegisters(AsmPieces))
26042 return IntrinsicLowering::LowerToByteSwap(CI);
26045 if (CI->getType()->isIntegerTy(64)) {
26046 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26047 if (Constraints.size() >= 2 &&
26048 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26049 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26050 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26051 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26052 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26053 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26054 return IntrinsicLowering::LowerToByteSwap(CI);
26062 /// getConstraintType - Given a constraint letter, return the type of
26063 /// constraint it is for this target.
26064 X86TargetLowering::ConstraintType
26065 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26066 if (Constraint.size() == 1) {
26067 switch (Constraint[0]) {
26078 return C_RegisterClass;
26102 return TargetLowering::getConstraintType(Constraint);
26105 /// Examine constraint type and operand type and determine a weight value.
26106 /// This object must already have been set up with the operand type
26107 /// and the current alternative constraint selected.
26108 TargetLowering::ConstraintWeight
26109 X86TargetLowering::getSingleConstraintMatchWeight(
26110 AsmOperandInfo &info, const char *constraint) const {
26111 ConstraintWeight weight = CW_Invalid;
26112 Value *CallOperandVal = info.CallOperandVal;
26113 // If we don't have a value, we can't do a match,
26114 // but allow it at the lowest weight.
26115 if (!CallOperandVal)
26117 Type *type = CallOperandVal->getType();
26118 // Look at the constraint type.
26119 switch (*constraint) {
26121 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26132 if (CallOperandVal->getType()->isIntegerTy())
26133 weight = CW_SpecificReg;
26138 if (type->isFloatingPointTy())
26139 weight = CW_SpecificReg;
26142 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26143 weight = CW_SpecificReg;
26147 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26148 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26149 weight = CW_Register;
26152 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26153 if (C->getZExtValue() <= 31)
26154 weight = CW_Constant;
26158 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26159 if (C->getZExtValue() <= 63)
26160 weight = CW_Constant;
26164 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26165 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26166 weight = CW_Constant;
26170 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26171 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26172 weight = CW_Constant;
26176 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26177 if (C->getZExtValue() <= 3)
26178 weight = CW_Constant;
26182 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26183 if (C->getZExtValue() <= 0xff)
26184 weight = CW_Constant;
26189 if (isa<ConstantFP>(CallOperandVal)) {
26190 weight = CW_Constant;
26194 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26195 if ((C->getSExtValue() >= -0x80000000LL) &&
26196 (C->getSExtValue() <= 0x7fffffffLL))
26197 weight = CW_Constant;
26201 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26202 if (C->getZExtValue() <= 0xffffffff)
26203 weight = CW_Constant;
26210 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26211 /// with another that has more specific requirements based on the type of the
26212 /// corresponding operand.
26213 const char *X86TargetLowering::
26214 LowerXConstraint(EVT ConstraintVT) const {
26215 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26216 // 'f' like normal targets.
26217 if (ConstraintVT.isFloatingPoint()) {
26218 if (Subtarget->hasSSE2())
26220 if (Subtarget->hasSSE1())
26224 return TargetLowering::LowerXConstraint(ConstraintVT);
26227 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26228 /// vector. If it is invalid, don't add anything to Ops.
26229 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26230 std::string &Constraint,
26231 std::vector<SDValue>&Ops,
26232 SelectionDAG &DAG) const {
26235 // Only support length 1 constraints for now.
26236 if (Constraint.length() > 1) return;
26238 char ConstraintLetter = Constraint[0];
26239 switch (ConstraintLetter) {
26242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26243 if (C->getZExtValue() <= 31) {
26244 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26245 Op.getValueType());
26251 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26252 if (C->getZExtValue() <= 63) {
26253 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26254 Op.getValueType());
26260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26261 if (isInt<8>(C->getSExtValue())) {
26262 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26263 Op.getValueType());
26269 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26270 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26271 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26272 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26273 Op.getValueType());
26279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26280 if (C->getZExtValue() <= 3) {
26281 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26282 Op.getValueType());
26288 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26289 if (C->getZExtValue() <= 255) {
26290 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26291 Op.getValueType());
26297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26298 if (C->getZExtValue() <= 127) {
26299 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26300 Op.getValueType());
26306 // 32-bit signed value
26307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26308 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26309 C->getSExtValue())) {
26310 // Widen to 64 bits here to get it sign extended.
26311 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26314 // FIXME gcc accepts some relocatable values here too, but only in certain
26315 // memory models; it's complicated.
26320 // 32-bit unsigned value
26321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26322 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26323 C->getZExtValue())) {
26324 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26325 Op.getValueType());
26329 // FIXME gcc accepts some relocatable values here too, but only in certain
26330 // memory models; it's complicated.
26334 // Literal immediates are always ok.
26335 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26336 // Widen to 64 bits here to get it sign extended.
26337 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26341 // In any sort of PIC mode addresses need to be computed at runtime by
26342 // adding in a register or some sort of table lookup. These can't
26343 // be used as immediates.
26344 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26347 // If we are in non-pic codegen mode, we allow the address of a global (with
26348 // an optional displacement) to be used with 'i'.
26349 GlobalAddressSDNode *GA = nullptr;
26350 int64_t Offset = 0;
26352 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26354 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26355 Offset += GA->getOffset();
26357 } else if (Op.getOpcode() == ISD::ADD) {
26358 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26359 Offset += C->getZExtValue();
26360 Op = Op.getOperand(0);
26363 } else if (Op.getOpcode() == ISD::SUB) {
26364 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26365 Offset += -C->getZExtValue();
26366 Op = Op.getOperand(0);
26371 // Otherwise, this isn't something we can handle, reject it.
26375 const GlobalValue *GV = GA->getGlobal();
26376 // If we require an extra load to get this address, as in PIC mode, we
26377 // can't accept it.
26378 if (isGlobalStubReference(
26379 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26382 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26383 GA->getValueType(0), Offset);
26388 if (Result.getNode()) {
26389 Ops.push_back(Result);
26392 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26395 std::pair<unsigned, const TargetRegisterClass *>
26396 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26397 StringRef Constraint,
26399 // First, see if this is a constraint that directly corresponds to an LLVM
26401 if (Constraint.size() == 1) {
26402 // GCC Constraint Letters
26403 switch (Constraint[0]) {
26405 // TODO: Slight differences here in allocation order and leaving
26406 // RIP in the class. Do they matter any more here than they do
26407 // in the normal allocation?
26408 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26409 if (Subtarget->is64Bit()) {
26410 if (VT == MVT::i32 || VT == MVT::f32)
26411 return std::make_pair(0U, &X86::GR32RegClass);
26412 if (VT == MVT::i16)
26413 return std::make_pair(0U, &X86::GR16RegClass);
26414 if (VT == MVT::i8 || VT == MVT::i1)
26415 return std::make_pair(0U, &X86::GR8RegClass);
26416 if (VT == MVT::i64 || VT == MVT::f64)
26417 return std::make_pair(0U, &X86::GR64RegClass);
26420 // 32-bit fallthrough
26421 case 'Q': // Q_REGS
26422 if (VT == MVT::i32 || VT == MVT::f32)
26423 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26424 if (VT == MVT::i16)
26425 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26426 if (VT == MVT::i8 || VT == MVT::i1)
26427 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26428 if (VT == MVT::i64)
26429 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26431 case 'r': // GENERAL_REGS
26432 case 'l': // INDEX_REGS
26433 if (VT == MVT::i8 || VT == MVT::i1)
26434 return std::make_pair(0U, &X86::GR8RegClass);
26435 if (VT == MVT::i16)
26436 return std::make_pair(0U, &X86::GR16RegClass);
26437 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26438 return std::make_pair(0U, &X86::GR32RegClass);
26439 return std::make_pair(0U, &X86::GR64RegClass);
26440 case 'R': // LEGACY_REGS
26441 if (VT == MVT::i8 || VT == MVT::i1)
26442 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26443 if (VT == MVT::i16)
26444 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26445 if (VT == MVT::i32 || !Subtarget->is64Bit())
26446 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26447 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26448 case 'f': // FP Stack registers.
26449 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26450 // value to the correct fpstack register class.
26451 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26452 return std::make_pair(0U, &X86::RFP32RegClass);
26453 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26454 return std::make_pair(0U, &X86::RFP64RegClass);
26455 return std::make_pair(0U, &X86::RFP80RegClass);
26456 case 'y': // MMX_REGS if MMX allowed.
26457 if (!Subtarget->hasMMX()) break;
26458 return std::make_pair(0U, &X86::VR64RegClass);
26459 case 'Y': // SSE_REGS if SSE2 allowed
26460 if (!Subtarget->hasSSE2()) break;
26462 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26463 if (!Subtarget->hasSSE1()) break;
26465 switch (VT.SimpleTy) {
26467 // Scalar SSE types.
26470 return std::make_pair(0U, &X86::FR32RegClass);
26473 return std::make_pair(0U, &X86::FR64RegClass);
26481 return std::make_pair(0U, &X86::VR128RegClass);
26489 return std::make_pair(0U, &X86::VR256RegClass);
26494 return std::make_pair(0U, &X86::VR512RegClass);
26500 // Use the default implementation in TargetLowering to convert the register
26501 // constraint into a member of a register class.
26502 std::pair<unsigned, const TargetRegisterClass*> Res;
26503 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26505 // Not found as a standard register?
26507 // Map st(0) -> st(7) -> ST0
26508 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26509 tolower(Constraint[1]) == 's' &&
26510 tolower(Constraint[2]) == 't' &&
26511 Constraint[3] == '(' &&
26512 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26513 Constraint[5] == ')' &&
26514 Constraint[6] == '}') {
26516 Res.first = X86::FP0+Constraint[4]-'0';
26517 Res.second = &X86::RFP80RegClass;
26521 // GCC allows "st(0)" to be called just plain "st".
26522 if (StringRef("{st}").equals_lower(Constraint)) {
26523 Res.first = X86::FP0;
26524 Res.second = &X86::RFP80RegClass;
26529 if (StringRef("{flags}").equals_lower(Constraint)) {
26530 Res.first = X86::EFLAGS;
26531 Res.second = &X86::CCRRegClass;
26535 // 'A' means EAX + EDX.
26536 if (Constraint == "A") {
26537 Res.first = X86::EAX;
26538 Res.second = &X86::GR32_ADRegClass;
26544 // Otherwise, check to see if this is a register class of the wrong value
26545 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26546 // turn into {ax},{dx}.
26547 // MVT::Other is used to specify clobber names.
26548 if (Res.second->hasType(VT) || VT == MVT::Other)
26549 return Res; // Correct type already, nothing to do.
26551 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26552 // return "eax". This should even work for things like getting 64bit integer
26553 // registers when given an f64 type.
26554 const TargetRegisterClass *Class = Res.second;
26555 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26556 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26557 unsigned Size = VT.getSizeInBits();
26558 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26559 : Size == 16 ? MVT::i16
26560 : Size == 32 ? MVT::i32
26561 : Size == 64 ? MVT::i64
26563 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26565 Res.first = DestReg;
26566 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26567 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26568 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26569 : &X86::GR64RegClass;
26570 assert(Res.second->contains(Res.first) && "Register in register class");
26572 // No register found/type mismatch.
26574 Res.second = nullptr;
26576 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26577 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26578 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26579 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26580 Class == &X86::VR512RegClass) {
26581 // Handle references to XMM physical registers that got mapped into the
26582 // wrong class. This can happen with constraints like {xmm0} where the
26583 // target independent register mapper will just pick the first match it can
26584 // find, ignoring the required type.
26586 if (VT == MVT::f32 || VT == MVT::i32)
26587 Res.second = &X86::FR32RegClass;
26588 else if (VT == MVT::f64 || VT == MVT::i64)
26589 Res.second = &X86::FR64RegClass;
26590 else if (X86::VR128RegClass.hasType(VT))
26591 Res.second = &X86::VR128RegClass;
26592 else if (X86::VR256RegClass.hasType(VT))
26593 Res.second = &X86::VR256RegClass;
26594 else if (X86::VR512RegClass.hasType(VT))
26595 Res.second = &X86::VR512RegClass;
26597 // Type mismatch and not a clobber: Return an error;
26599 Res.second = nullptr;
26606 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26607 const AddrMode &AM, Type *Ty,
26608 unsigned AS) const {
26609 // Scaling factors are not free at all.
26610 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26611 // will take 2 allocations in the out of order engine instead of 1
26612 // for plain addressing mode, i.e. inst (reg1).
26614 // vaddps (%rsi,%drx), %ymm0, %ymm1
26615 // Requires two allocations (one for the load, one for the computation)
26617 // vaddps (%rsi), %ymm0, %ymm1
26618 // Requires just 1 allocation, i.e., freeing allocations for other operations
26619 // and having less micro operations to execute.
26621 // For some X86 architectures, this is even worse because for instance for
26622 // stores, the complex addressing mode forces the instruction to use the
26623 // "load" ports instead of the dedicated "store" port.
26624 // E.g., on Haswell:
26625 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26626 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26627 if (isLegalAddressingMode(DL, AM, Ty, AS))
26628 // Scale represents reg2 * scale, thus account for 1
26629 // as soon as we use a second register.
26630 return AM.Scale != 0;
26634 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26635 // Integer division on x86 is expensive. However, when aggressively optimizing
26636 // for code size, we prefer to use a div instruction, as it is usually smaller
26637 // than the alternative sequence.
26638 // The exception to this is vector division. Since x86 doesn't have vector
26639 // integer division, leaving the division as-is is a loss even in terms of
26640 // size, because it will have to be scalarized, while the alternative code
26641 // sequence can be performed in vector form.
26642 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26643 Attribute::MinSize);
26644 return OptSize && !VT.isVector();