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 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75 const X86Subtarget &STI)
76 : TargetLowering(TM), Subtarget(&STI) {
77 X86ScalarSSEf64 = Subtarget->hasSSE2();
78 X86ScalarSSEf32 = Subtarget->hasSSE1();
79 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
81 // Set up the TargetLowering object.
82 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
84 // X86 is weird. It always uses i8 for shift amounts and setcc results.
85 setBooleanContents(ZeroOrOneBooleanContent);
86 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
89 // For 64-bit, since we have so many registers, use the ILP scheduler.
90 // For 32-bit, use the register pressure specific scheduling.
91 // For Atom, always use ILP scheduling.
92 if (Subtarget->isAtom())
93 setSchedulingPreference(Sched::ILP);
94 else if (Subtarget->is64Bit())
95 setSchedulingPreference(Sched::ILP);
97 setSchedulingPreference(Sched::RegPressure);
98 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
101 // Bypass expensive divides on Atom when compiling with O2.
102 if (TM.getOptLevel() >= CodeGenOpt::Default) {
103 if (Subtarget->hasSlowDivide32())
104 addBypassSlowDiv(32, 8);
105 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106 addBypassSlowDiv(64, 16);
109 if (Subtarget->isTargetKnownWindowsMSVC()) {
110 // Setup Windows compiler runtime calls.
111 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113 setLibcallName(RTLIB::SREM_I64, "_allrem");
114 setLibcallName(RTLIB::UREM_I64, "_aullrem");
115 setLibcallName(RTLIB::MUL_I64, "_allmul");
116 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
122 // The _ftol2 runtime function has an unusual calling conv, which
123 // is modeled by a special pseudo-instruction.
124 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
130 if (Subtarget->isTargetDarwin()) {
131 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132 setUseUnderscoreSetJmp(false);
133 setUseUnderscoreLongJmp(false);
134 } else if (Subtarget->isTargetWindowsGNU()) {
135 // MS runtime is weird: it exports _setjmp, but longjmp!
136 setUseUnderscoreSetJmp(true);
137 setUseUnderscoreLongJmp(false);
139 setUseUnderscoreSetJmp(true);
140 setUseUnderscoreLongJmp(true);
143 // Set up the register classes.
144 addRegisterClass(MVT::i8, &X86::GR8RegClass);
145 addRegisterClass(MVT::i16, &X86::GR16RegClass);
146 addRegisterClass(MVT::i32, &X86::GR32RegClass);
147 if (Subtarget->is64Bit())
148 addRegisterClass(MVT::i64, &X86::GR64RegClass);
150 for (MVT VT : MVT::integer_valuetypes())
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
153 // We don't accept any truncstore of integer registers.
154 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
161 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 // SETOEQ and SETUNE require checking two conditions.
164 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
171 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
173 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
174 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
177 if (Subtarget->is64Bit()) {
178 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 } else if (!Subtarget->useSoftFloat()) {
181 // We have an algorithm for SSE2->double, and we turn this into a
182 // 64-bit FILD followed by conditional FADD for other targets.
183 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
184 // We have an algorithm for SSE2, and we turn this into a 64-bit
185 // FILD for other targets.
186 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
189 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
191 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
192 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
194 if (!Subtarget->useSoftFloat()) {
195 // SSE has no i16 to fp conversion, only i32
196 if (X86ScalarSSEf32) {
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
198 // f32 and f64 cases are Legal, f80 case is not
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
206 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
216 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
219 if (X86ScalarSSEf32) {
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
221 // f32 and f64 cases are Legal, f80 case is not
222 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
237 } else if (!Subtarget->useSoftFloat()) {
238 // Since AVX is a superset of SSE3, only check for SSE here.
239 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240 // Expand FP_TO_UINT into a select.
241 // FIXME: We would like to use a Custom expander here eventually to do
242 // the optimal thing for SSE vs. the default expansion in the legalizer.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
245 // With SSE3 we can use fisttpll to convert to a signed i64; without
246 // SSE, we're stuck with a fistpll.
247 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
250 if (isTargetFTOL()) {
251 // Use the _ftol2 runtime function, which has a pseudo-instruction
252 // to handle its weird calling convention.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
256 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257 if (!X86ScalarSSEf64) {
258 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
259 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
260 if (Subtarget->is64Bit()) {
261 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
262 // Without SSE, i64->f64 goes through memory.
263 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
267 // Scalar integer divide and remainder are lowered to use operations that
268 // produce two results, to match the available instructions. This exposes
269 // the two-result form to trivial CSE, which is able to combine x/y and x%y
270 // into a single instruction.
272 // Scalar integer multiply-high is also lowered to use two-result
273 // operations, to match the available instructions. However, plain multiply
274 // (low) operations are left as Legal, as there are single-result
275 // instructions for this in x86. Using the two-result multiply instructions
276 // when both high and low results are needed must be arranged by dagcombine.
277 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
279 setOperationAction(ISD::MULHS, VT, Expand);
280 setOperationAction(ISD::MULHU, VT, Expand);
281 setOperationAction(ISD::SDIV, VT, Expand);
282 setOperationAction(ISD::UDIV, VT, Expand);
283 setOperationAction(ISD::SREM, VT, Expand);
284 setOperationAction(ISD::UREM, VT, Expand);
286 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287 setOperationAction(ISD::ADDC, VT, Custom);
288 setOperationAction(ISD::ADDE, VT, Custom);
289 setOperationAction(ISD::SUBC, VT, Custom);
290 setOperationAction(ISD::SUBE, VT, Custom);
293 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
294 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
295 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
296 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
297 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
298 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
299 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
300 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
309 if (Subtarget->is64Bit())
310 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
312 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
314 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
315 setOperationAction(ISD::FREM , MVT::f32 , Expand);
316 setOperationAction(ISD::FREM , MVT::f64 , Expand);
317 setOperationAction(ISD::FREM , MVT::f80 , Expand);
318 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
320 // Promote the i8 variants and force them on up to i32 which has a shorter
322 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
323 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
325 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
326 if (Subtarget->hasBMI()) {
327 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
328 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
329 if (Subtarget->is64Bit())
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
332 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
333 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
334 if (Subtarget->is64Bit())
335 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
338 if (Subtarget->hasLZCNT()) {
339 // When promoting the i8 variants, force them to i32 for a shorter
341 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
342 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
343 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
344 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
350 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
351 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
352 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
353 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
355 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
356 if (Subtarget->is64Bit()) {
357 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
362 // Special handling for half-precision floating point conversions.
363 // If we don't have F16C support, then lower half float conversions
364 // into library calls.
365 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
370 // There's never any support for operations beyond MVT::f32.
371 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
376 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
383 if (Subtarget->hasPOPCNT()) {
384 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
386 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
387 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
388 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
393 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
395 if (!Subtarget->hasMOVBE())
396 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
398 // These should be promoted to a larger select which is supported.
399 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
400 // X86 wants to expand cmov itself.
401 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
402 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
403 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
404 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
405 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
406 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
407 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
408 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
409 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
410 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
411 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
412 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
413 if (Subtarget->is64Bit()) {
414 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
417 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
418 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420 // support continuation, user-level threading, and etc.. As a result, no
421 // other SjLj exception interfaces are implemented and please don't build
422 // your own exception handling based on them.
423 // LLVM/Clang supports zero-cost DWARF exception handling.
424 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
428 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
429 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
430 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
431 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
435 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
436 if (Subtarget->is64Bit()) {
437 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
438 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
439 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
440 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
443 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
447 if (Subtarget->is64Bit()) {
448 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
449 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
450 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
453 if (Subtarget->hasSSE1())
454 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
456 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
458 // Expand certain atomics
459 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
461 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466 if (Subtarget->hasCmpxchg16b()) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
470 // FIXME - use subtarget debug flags
471 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
476 if (Subtarget->is64Bit()) {
477 setExceptionPointerRegister(X86::RAX);
478 setExceptionSelectorRegister(X86::RDX);
480 setExceptionPointerRegister(X86::EAX);
481 setExceptionSelectorRegister(X86::EDX);
483 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
486 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
489 setOperationAction(ISD::TRAP, MVT::Other, Legal);
490 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
492 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493 setOperationAction(ISD::VASTART , MVT::Other, Custom);
494 setOperationAction(ISD::VAEND , MVT::Other, Expand);
495 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496 // TargetInfo::X86_64ABIBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Custom);
498 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
500 // TargetInfo::CharPtrBuiltinVaList
501 setOperationAction(ISD::VAARG , MVT::Other, Expand);
502 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
505 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
506 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
508 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
510 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
514 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515 // f32 and f64 use SSE.
516 // Set up the FP register classes.
517 addRegisterClass(MVT::f32, &X86::FR32RegClass);
518 addRegisterClass(MVT::f64, &X86::FR64RegClass);
520 // Use ANDPD to simulate FABS.
521 setOperationAction(ISD::FABS , MVT::f64, Custom);
522 setOperationAction(ISD::FABS , MVT::f32, Custom);
524 // Use XORP to simulate FNEG.
525 setOperationAction(ISD::FNEG , MVT::f64, Custom);
526 setOperationAction(ISD::FNEG , MVT::f32, Custom);
528 // Use ANDPD and ORPD to simulate FCOPYSIGN.
529 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532 // Lower this to FGETSIGNx86 plus an AND.
533 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
536 // We don't support sin/cos/fmod
537 setOperationAction(ISD::FSIN , MVT::f64, Expand);
538 setOperationAction(ISD::FCOS , MVT::f64, Expand);
539 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540 setOperationAction(ISD::FSIN , MVT::f32, Expand);
541 setOperationAction(ISD::FCOS , MVT::f32, Expand);
542 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
544 // Expand FP immediates into loads from the stack, except for the special
546 addLegalFPImmediate(APFloat(+0.0)); // xorpd
547 addLegalFPImmediate(APFloat(+0.0f)); // xorps
548 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549 // Use SSE for f32, x87 for f64.
550 // Set up the FP register classes.
551 addRegisterClass(MVT::f32, &X86::FR32RegClass);
552 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554 // Use ANDPS to simulate FABS.
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f32, Custom);
560 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
562 // Use ANDPS and ORPS to simulate FCOPYSIGN.
563 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566 // We don't support sin/cos/fmod
567 setOperationAction(ISD::FSIN , MVT::f32, Expand);
568 setOperationAction(ISD::FCOS , MVT::f32, Expand);
569 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571 // Special cases we handle for FP constants.
572 addLegalFPImmediate(APFloat(+0.0f)); // xorps
573 addLegalFPImmediate(APFloat(+0.0)); // FLD0
574 addLegalFPImmediate(APFloat(+1.0)); // FLD1
575 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578 if (!TM.Options.UnsafeFPMath) {
579 setOperationAction(ISD::FSIN , MVT::f64, Expand);
580 setOperationAction(ISD::FCOS , MVT::f64, Expand);
581 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583 } else if (!Subtarget->useSoftFloat()) {
584 // f32 and f64 in x87.
585 // Set up the FP register classes.
586 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
590 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
591 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
594 if (!TM.Options.UnsafeFPMath) {
595 setOperationAction(ISD::FSIN , MVT::f64, Expand);
596 setOperationAction(ISD::FSIN , MVT::f32, Expand);
597 setOperationAction(ISD::FCOS , MVT::f64, Expand);
598 setOperationAction(ISD::FCOS , MVT::f32, Expand);
599 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
602 addLegalFPImmediate(APFloat(+0.0)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
612 // We don't support FMA.
613 setOperationAction(ISD::FMA, MVT::f64, Expand);
614 setOperationAction(ISD::FMA, MVT::f32, Expand);
616 // Long double always uses X87.
617 if (!Subtarget->useSoftFloat()) {
618 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
622 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623 addLegalFPImmediate(TmpFlt); // FLD0
625 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
628 APFloat TmpFlt2(+1.0);
629 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
631 addLegalFPImmediate(TmpFlt2); // FLD1
632 TmpFlt2.changeSign();
633 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
636 if (!TM.Options.UnsafeFPMath) {
637 setOperationAction(ISD::FSIN , MVT::f80, Expand);
638 setOperationAction(ISD::FCOS , MVT::f80, Expand);
639 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
642 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
644 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645 setOperationAction(ISD::FRINT, MVT::f80, Expand);
646 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647 setOperationAction(ISD::FMA, MVT::f80, Expand);
650 // Always use a library call for pow.
651 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
652 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
653 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
655 setOperationAction(ISD::FLOG, MVT::f80, Expand);
656 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658 setOperationAction(ISD::FEXP, MVT::f80, Expand);
659 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
663 // First set operation action for all vector types to either promote
664 // (for widening) or expand (for scalarization). Then we will selectively
665 // turn on ones that can be effectively codegen'd.
666 for (MVT VT : MVT::vector_valuetypes()) {
667 setOperationAction(ISD::ADD , VT, Expand);
668 setOperationAction(ISD::SUB , VT, Expand);
669 setOperationAction(ISD::FADD, VT, Expand);
670 setOperationAction(ISD::FNEG, VT, Expand);
671 setOperationAction(ISD::FSUB, VT, Expand);
672 setOperationAction(ISD::MUL , VT, Expand);
673 setOperationAction(ISD::FMUL, VT, Expand);
674 setOperationAction(ISD::SDIV, VT, Expand);
675 setOperationAction(ISD::UDIV, VT, Expand);
676 setOperationAction(ISD::FDIV, VT, Expand);
677 setOperationAction(ISD::SREM, VT, Expand);
678 setOperationAction(ISD::UREM, VT, Expand);
679 setOperationAction(ISD::LOAD, VT, Expand);
680 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685 setOperationAction(ISD::FABS, VT, Expand);
686 setOperationAction(ISD::FSIN, VT, Expand);
687 setOperationAction(ISD::FSINCOS, VT, Expand);
688 setOperationAction(ISD::FCOS, VT, Expand);
689 setOperationAction(ISD::FSINCOS, VT, Expand);
690 setOperationAction(ISD::FREM, VT, Expand);
691 setOperationAction(ISD::FMA, VT, Expand);
692 setOperationAction(ISD::FPOWI, VT, Expand);
693 setOperationAction(ISD::FSQRT, VT, Expand);
694 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695 setOperationAction(ISD::FFLOOR, VT, Expand);
696 setOperationAction(ISD::FCEIL, VT, Expand);
697 setOperationAction(ISD::FTRUNC, VT, Expand);
698 setOperationAction(ISD::FRINT, VT, Expand);
699 setOperationAction(ISD::FNEARBYINT, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHS, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHU, VT, Expand);
704 setOperationAction(ISD::SDIVREM, VT, Expand);
705 setOperationAction(ISD::UDIVREM, VT, Expand);
706 setOperationAction(ISD::FPOW, VT, Expand);
707 setOperationAction(ISD::CTPOP, VT, Expand);
708 setOperationAction(ISD::CTTZ, VT, Expand);
709 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710 setOperationAction(ISD::CTLZ, VT, Expand);
711 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712 setOperationAction(ISD::SHL, VT, Expand);
713 setOperationAction(ISD::SRA, VT, Expand);
714 setOperationAction(ISD::SRL, VT, Expand);
715 setOperationAction(ISD::ROTL, VT, Expand);
716 setOperationAction(ISD::ROTR, VT, Expand);
717 setOperationAction(ISD::BSWAP, VT, Expand);
718 setOperationAction(ISD::SETCC, VT, Expand);
719 setOperationAction(ISD::FLOG, VT, Expand);
720 setOperationAction(ISD::FLOG2, VT, Expand);
721 setOperationAction(ISD::FLOG10, VT, Expand);
722 setOperationAction(ISD::FEXP, VT, Expand);
723 setOperationAction(ISD::FEXP2, VT, Expand);
724 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729 setOperationAction(ISD::TRUNCATE, VT, Expand);
730 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733 setOperationAction(ISD::VSELECT, VT, Expand);
734 setOperationAction(ISD::SELECT_CC, VT, Expand);
735 for (MVT InnerVT : MVT::vector_valuetypes()) {
736 setTruncStoreAction(InnerVT, VT, Expand);
738 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
741 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742 // types, we have to deal with them whether we ask for Expansion or not.
743 // Setting Expand causes its own optimisation problems though, so leave
745 if (VT.getVectorElementType() == MVT::i1)
746 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749 // split/scalarized right now.
750 if (VT.getVectorElementType() == MVT::f16)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
755 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756 // with -msoft-float, disable use of MMX as well.
757 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759 // No operations on x86mmx supported, everything uses intrinsics.
762 // MMX-sized vectors (other than x86mmx) are expected to be expanded
763 // into smaller operations.
764 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765 setOperationAction(ISD::MULHS, MMXTy, Expand);
766 setOperationAction(ISD::AND, MMXTy, Expand);
767 setOperationAction(ISD::OR, MMXTy, Expand);
768 setOperationAction(ISD::XOR, MMXTy, Expand);
769 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
770 setOperationAction(ISD::SELECT, MMXTy, Expand);
771 setOperationAction(ISD::BITCAST, MMXTy, Expand);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
775 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
778 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
779 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
780 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
781 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
782 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
783 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
784 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
785 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
786 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
787 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
788 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
791 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
794 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
797 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798 // registers cannot be used even for integer operations.
799 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
804 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
805 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
806 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
807 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
808 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
809 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
810 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
811 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
812 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
813 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
814 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
815 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
816 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
818 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
820 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
826 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
828 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
829 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
830 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
831 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
833 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
834 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851 MVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
860 setOperationAction(ISD::VSELECT, VT, Custom);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
864 // We support custom legalizing of sext and anyext loads for specific
865 // memory vector types which we can load as a scalar (or sequence of
866 // scalars) and extend in-register to a legal 128-bit vector type. For sext
867 // loads these must work with a single scalar load.
868 for (MVT VT : MVT::integer_vector_valuetypes()) {
869 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
881 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
883 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
884 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
885 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
889 if (Subtarget->is64Bit()) {
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
894 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
898 // Do not attempt to promote non-128-bit vectors
899 if (!VT.is128BitVector())
902 setOperationAction(ISD::AND, VT, Promote);
903 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
904 setOperationAction(ISD::OR, VT, Promote);
905 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
906 setOperationAction(ISD::XOR, VT, Promote);
907 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
908 setOperationAction(ISD::LOAD, VT, Promote);
909 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
910 setOperationAction(ISD::SELECT, VT, Promote);
911 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914 // Custom lower v2i64 and v2f64 selects.
915 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
916 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
917 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
918 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
920 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
921 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
923 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
925 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
926 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
927 // As there is no 64-bit GPR available, we need build a special custom
928 // sequence to convert from v2i32 to v2f32.
929 if (!Subtarget->is64Bit())
930 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
932 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
933 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
935 for (MVT VT : MVT::fp_vector_valuetypes())
936 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
938 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
939 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
940 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
943 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
946 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
947 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
948 setOperationAction(ISD::FRINT, RoundedTy, Legal);
949 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
952 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
956 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
957 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
958 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
959 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
961 // FIXME: Do we need to handle scalar-to-vector here?
962 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
964 // We directly match byte blends in the backend as they match the VSELECT
966 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
968 // SSE41 brings specific instructions for doing vector sign extend even in
969 // cases where we don't have SRA.
970 for (MVT VT : MVT::integer_vector_valuetypes()) {
971 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
979 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
980 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
986 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
991 // i8 and i16 vectors are custom because the source register and source
992 // source memory operand types are not the same width. f32 vectors are
993 // custom since the immediate controlling the insert encodes additional
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1005 // FIXME: these should be Legal, but that's only for the case where
1006 // the index is constant. For now custom expand to deal with that.
1007 if (Subtarget->is64Bit()) {
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1009 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1013 if (Subtarget->hasSSE2()) {
1014 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1019 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1021 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1022 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1024 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1027 // In the customized shift lowering, the legal cases in AVX2 will be
1029 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1030 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1033 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1035 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1036 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1039 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1043 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1047 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1049 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1051 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1061 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1062 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1064 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1075 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1077 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078 // even though v8i16 is a legal type.
1079 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1080 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1081 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1083 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1084 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1085 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1087 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1088 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1090 for (MVT VT : MVT::fp_vector_valuetypes())
1091 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1093 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1094 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1096 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1097 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1102 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1103 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1104 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1105 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1107 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1108 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1109 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1111 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1112 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1113 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1114 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1115 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1116 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1117 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1118 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1119 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1120 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1121 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1122 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1124 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1125 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1126 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1127 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1129 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1132 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1133 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1134 setOperationAction(ISD::FMA, MVT::f32, Legal);
1135 setOperationAction(ISD::FMA, MVT::f64, Legal);
1138 if (Subtarget->hasInt256()) {
1139 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1140 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1141 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1142 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1144 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1145 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1146 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1147 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1149 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1150 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1151 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1152 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1154 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1155 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1156 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1157 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1159 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1160 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1161 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1162 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1163 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1164 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1165 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1167 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1168 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1169 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1170 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1172 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173 // when we have a 256bit-wide blend with immediate.
1174 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1176 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1179 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1180 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1181 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1182 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1186 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1187 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1188 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1189 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1191 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1192 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1193 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1194 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1196 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1197 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1198 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1199 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1201 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1202 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1203 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1204 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1207 // In the customized shift lowering, the legal cases in AVX2 will be
1209 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1210 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1212 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1213 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1216 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1218 // Custom lower several nodes for 256-bit types.
1219 for (MVT VT : MVT::vector_valuetypes()) {
1220 if (VT.getScalarSizeInBits() >= 32) {
1221 setOperationAction(ISD::MLOAD, VT, Legal);
1222 setOperationAction(ISD::MSTORE, VT, Legal);
1224 // Extract subvector is special because the value type
1225 // (result) is 128-bit but the source is 256-bit wide.
1226 if (VT.is128BitVector()) {
1227 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1229 // Do not attempt to custom lower other non-256-bit vectors
1230 if (!VT.is256BitVector())
1233 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1234 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1235 setOperationAction(ISD::VSELECT, VT, Custom);
1236 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1237 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1239 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1240 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1243 if (Subtarget->hasInt256())
1244 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1247 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249 MVT VT = (MVT::SimpleValueType)i;
1251 // Do not attempt to promote non-256-bit vectors
1252 if (!VT.is256BitVector())
1255 setOperationAction(ISD::AND, VT, Promote);
1256 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1257 setOperationAction(ISD::OR, VT, Promote);
1258 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1259 setOperationAction(ISD::XOR, VT, Promote);
1260 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1261 setOperationAction(ISD::LOAD, VT, Promote);
1262 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1263 setOperationAction(ISD::SELECT, VT, Promote);
1264 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1268 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1272 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1274 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1275 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1276 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1278 for (MVT VT : MVT::fp_vector_valuetypes())
1279 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1289 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1290 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1291 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1292 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1294 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1295 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1296 setOperationAction(ISD::XOR, MVT::i1, Legal);
1297 setOperationAction(ISD::OR, MVT::i1, Legal);
1298 setOperationAction(ISD::AND, MVT::i1, Legal);
1299 setOperationAction(ISD::SUB, MVT::i1, Custom);
1300 setOperationAction(ISD::ADD, MVT::i1, Custom);
1301 setOperationAction(ISD::MUL, MVT::i1, Custom);
1302 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1303 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1304 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1305 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1306 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1308 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1310 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1311 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1312 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1313 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1315 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1317 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1319 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1320 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1321 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1322 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1324 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1326 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1327 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1328 if (Subtarget->is64Bit()) {
1329 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1331 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1332 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1337 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1339 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1340 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1341 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1342 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1344 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1345 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1346 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1347 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1348 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1349 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1351 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1352 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1353 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1354 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1355 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1356 if (Subtarget->hasVLX()){
1357 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1358 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1359 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1360 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1361 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1363 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1364 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1365 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1366 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1367 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1369 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1371 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1372 if (Subtarget->hasDQI()) {
1373 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1378 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1379 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1380 if (Subtarget->hasVLX()) {
1381 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1382 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1385 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1386 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1387 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1388 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1391 if (Subtarget->hasVLX()) {
1392 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1394 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1396 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1398 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1399 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1401 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1402 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1403 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1404 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1407 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1409 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1412 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1413 if (Subtarget->hasDQI()) {
1414 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1415 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1417 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1423 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1424 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1425 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1426 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1428 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1429 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1430 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1431 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1432 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1434 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1435 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1437 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1439 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1440 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1441 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1442 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1443 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1444 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1446 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1447 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1448 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1449 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1451 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1452 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1453 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1454 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1455 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1456 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1457 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1458 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1460 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1463 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1464 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1466 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1469 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1471 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1472 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1474 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1477 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1478 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1481 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1482 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1484 if (Subtarget->hasCDI()) {
1485 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1486 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1488 if (Subtarget->hasDQI()) {
1489 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1490 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1491 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1493 // Custom lower several nodes.
1494 for (MVT VT : MVT::vector_valuetypes()) {
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1497 setOperationAction(ISD::AND, VT, Legal);
1498 setOperationAction(ISD::OR, VT, Legal);
1499 setOperationAction(ISD::XOR, VT, Legal);
1501 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1502 setOperationAction(ISD::MGATHER, VT, Custom);
1503 setOperationAction(ISD::MSCATTER, VT, Custom);
1505 // Extract subvector is special because the value type
1506 // (result) is 256/128-bit but the source is 512-bit wide.
1507 if (VT.is128BitVector() || VT.is256BitVector()) {
1508 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1510 if (VT.getVectorElementType() == MVT::i1)
1511 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1513 // Do not attempt to custom lower other non-512-bit vectors
1514 if (!VT.is512BitVector())
1517 if (EltSize >= 32) {
1518 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1519 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1520 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1521 setOperationAction(ISD::VSELECT, VT, Legal);
1522 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1523 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1524 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1525 setOperationAction(ISD::MLOAD, VT, Legal);
1526 setOperationAction(ISD::MSTORE, VT, Legal);
1529 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1530 MVT VT = (MVT::SimpleValueType)i;
1532 // Do not attempt to promote non-512-bit vectors.
1533 if (!VT.is512BitVector())
1536 setOperationAction(ISD::SELECT, VT, Promote);
1537 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1541 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1542 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1543 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1545 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1546 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1548 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1549 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1550 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1551 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1552 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1553 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1554 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1555 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1556 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1557 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1558 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1559 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1560 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1561 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1562 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1563 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1564 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1565 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1566 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1567 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1568 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1569 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1570 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1571 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1572 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1573 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1574 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1575 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1576 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1577 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1579 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1581 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1582 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1583 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1584 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1585 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1586 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1588 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1589 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1590 if (Subtarget->hasVLX())
1591 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1593 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1594 const MVT VT = (MVT::SimpleValueType)i;
1596 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1598 // Do not attempt to promote non-512-bit vectors.
1599 if (!VT.is512BitVector())
1603 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1604 setOperationAction(ISD::VSELECT, VT, Legal);
1609 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1610 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1611 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1613 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1614 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1615 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1616 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1617 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1618 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1619 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1620 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1621 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1622 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1624 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1625 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1626 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1627 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1628 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1629 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1630 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1631 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1633 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1634 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1635 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1636 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1637 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1638 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1639 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1640 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1643 // We want to custom lower some of our intrinsics.
1644 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1645 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1646 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1647 if (!Subtarget->is64Bit())
1648 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1650 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1651 // handle type legalization for these operations here.
1653 // FIXME: We really should do custom legalization for addition and
1654 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1655 // than generic legalization for 64-bit multiplication-with-overflow, though.
1656 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1657 // Add/Sub/Mul with overflow operations are custom lowered.
1659 setOperationAction(ISD::SADDO, VT, Custom);
1660 setOperationAction(ISD::UADDO, VT, Custom);
1661 setOperationAction(ISD::SSUBO, VT, Custom);
1662 setOperationAction(ISD::USUBO, VT, Custom);
1663 setOperationAction(ISD::SMULO, VT, Custom);
1664 setOperationAction(ISD::UMULO, VT, Custom);
1668 if (!Subtarget->is64Bit()) {
1669 // These libcalls are not available in 32-bit.
1670 setLibcallName(RTLIB::SHL_I128, nullptr);
1671 setLibcallName(RTLIB::SRL_I128, nullptr);
1672 setLibcallName(RTLIB::SRA_I128, nullptr);
1675 // Combine sin / cos into one node or libcall if possible.
1676 if (Subtarget->hasSinCos()) {
1677 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1678 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1679 if (Subtarget->isTargetDarwin()) {
1680 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1681 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1682 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1683 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1687 if (Subtarget->isTargetWin64()) {
1688 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1689 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1690 setOperationAction(ISD::SREM, MVT::i128, Custom);
1691 setOperationAction(ISD::UREM, MVT::i128, Custom);
1692 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1693 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1696 // We have target-specific dag combine patterns for the following nodes:
1697 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1698 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1699 setTargetDAGCombine(ISD::BITCAST);
1700 setTargetDAGCombine(ISD::VSELECT);
1701 setTargetDAGCombine(ISD::SELECT);
1702 setTargetDAGCombine(ISD::SHL);
1703 setTargetDAGCombine(ISD::SRA);
1704 setTargetDAGCombine(ISD::SRL);
1705 setTargetDAGCombine(ISD::OR);
1706 setTargetDAGCombine(ISD::AND);
1707 setTargetDAGCombine(ISD::ADD);
1708 setTargetDAGCombine(ISD::FADD);
1709 setTargetDAGCombine(ISD::FSUB);
1710 setTargetDAGCombine(ISD::FMA);
1711 setTargetDAGCombine(ISD::SUB);
1712 setTargetDAGCombine(ISD::LOAD);
1713 setTargetDAGCombine(ISD::MLOAD);
1714 setTargetDAGCombine(ISD::STORE);
1715 setTargetDAGCombine(ISD::MSTORE);
1716 setTargetDAGCombine(ISD::ZERO_EXTEND);
1717 setTargetDAGCombine(ISD::ANY_EXTEND);
1718 setTargetDAGCombine(ISD::SIGN_EXTEND);
1719 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1720 setTargetDAGCombine(ISD::SINT_TO_FP);
1721 setTargetDAGCombine(ISD::UINT_TO_FP);
1722 setTargetDAGCombine(ISD::SETCC);
1723 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1724 setTargetDAGCombine(ISD::BUILD_VECTOR);
1725 setTargetDAGCombine(ISD::MUL);
1726 setTargetDAGCombine(ISD::XOR);
1728 computeRegisterProperties(Subtarget->getRegisterInfo());
1730 // On Darwin, -Os means optimize for size without hurting performance,
1731 // do not reduce the limit.
1732 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1733 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1734 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1735 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1736 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1737 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1738 setPrefLoopAlignment(4); // 2^4 bytes.
1740 // Predictable cmov don't hurt on atom because it's in-order.
1741 PredictableSelectIsExpensive = !Subtarget->isAtom();
1742 EnableExtLdPromotion = true;
1743 setPrefFunctionAlignment(4); // 2^4 bytes.
1745 verifyIntrinsicTables();
1748 // This has so far only been implemented for 64-bit MachO.
1749 bool X86TargetLowering::useLoadStackGuardNode() const {
1750 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1753 TargetLoweringBase::LegalizeTypeAction
1754 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1755 if (ExperimentalVectorWideningLegalization &&
1756 VT.getVectorNumElements() != 1 &&
1757 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1758 return TypeWidenVector;
1760 return TargetLoweringBase::getPreferredVectorAction(VT);
1763 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1766 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1768 const unsigned NumElts = VT.getVectorNumElements();
1769 const EVT EltVT = VT.getVectorElementType();
1770 if (VT.is512BitVector()) {
1771 if (Subtarget->hasAVX512())
1772 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1773 EltVT == MVT::f32 || EltVT == MVT::f64)
1775 case 8: return MVT::v8i1;
1776 case 16: return MVT::v16i1;
1778 if (Subtarget->hasBWI())
1779 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1781 case 32: return MVT::v32i1;
1782 case 64: return MVT::v64i1;
1786 if (VT.is256BitVector() || VT.is128BitVector()) {
1787 if (Subtarget->hasVLX())
1788 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1789 EltVT == MVT::f32 || EltVT == MVT::f64)
1791 case 2: return MVT::v2i1;
1792 case 4: return MVT::v4i1;
1793 case 8: return MVT::v8i1;
1795 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1796 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1798 case 8: return MVT::v8i1;
1799 case 16: return MVT::v16i1;
1800 case 32: return MVT::v32i1;
1804 return VT.changeVectorElementTypeToInteger();
1807 /// Helper for getByValTypeAlignment to determine
1808 /// the desired ByVal argument alignment.
1809 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1812 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1813 if (VTy->getBitWidth() == 128)
1815 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1816 unsigned EltAlign = 0;
1817 getMaxByValAlign(ATy->getElementType(), EltAlign);
1818 if (EltAlign > MaxAlign)
1819 MaxAlign = EltAlign;
1820 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1821 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1822 unsigned EltAlign = 0;
1823 getMaxByValAlign(STy->getElementType(i), EltAlign);
1824 if (EltAlign > MaxAlign)
1825 MaxAlign = EltAlign;
1832 /// Return the desired alignment for ByVal aggregate
1833 /// function arguments in the caller parameter area. For X86, aggregates
1834 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1835 /// are at 4-byte boundaries.
1836 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1837 const DataLayout &DL) const {
1838 if (Subtarget->is64Bit()) {
1839 // Max of 8 and alignment of type.
1840 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1847 if (Subtarget->hasSSE1())
1848 getMaxByValAlign(Ty, Align);
1852 /// Returns the target specific optimal type for load
1853 /// and store operations as a result of memset, memcpy, and memmove
1854 /// lowering. If DstAlign is zero that means it's safe to destination
1855 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1856 /// means there isn't a need to check it against alignment requirement,
1857 /// probably because the source does not need to be loaded. If 'IsMemset' is
1858 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1859 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1860 /// source is constant so it does not need to be loaded.
1861 /// It returns EVT::Other if the type should be determined using generic
1862 /// target-independent logic.
1864 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1865 unsigned DstAlign, unsigned SrcAlign,
1866 bool IsMemset, bool ZeroMemset,
1868 MachineFunction &MF) const {
1869 const Function *F = MF.getFunction();
1870 if ((!IsMemset || ZeroMemset) &&
1871 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1873 (Subtarget->isUnalignedMemAccessFast() ||
1874 ((DstAlign == 0 || DstAlign >= 16) &&
1875 (SrcAlign == 0 || SrcAlign >= 16)))) {
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 if (Subtarget->is64Bit() && Size >= 8)
1899 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1901 return X86ScalarSSEf32;
1902 else if (VT == MVT::f64)
1903 return X86ScalarSSEf64;
1908 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1913 *Fast = Subtarget->isUnalignedMemAccessFast();
1917 /// Return the entry encoding for a jump table in the
1918 /// current function. The returned value is a member of the
1919 /// MachineJumpTableInfo::JTEntryKind enum.
1920 unsigned X86TargetLowering::getJumpTableEncoding() const {
1921 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1923 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1924 Subtarget->isPICStyleGOT())
1925 return MachineJumpTableInfo::EK_Custom32;
1927 // Otherwise, use the normal jump table encoding heuristics.
1928 return TargetLowering::getJumpTableEncoding();
1931 bool X86TargetLowering::useSoftFloat() const {
1932 return Subtarget->useSoftFloat();
1936 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1937 const MachineBasicBlock *MBB,
1938 unsigned uid,MCContext &Ctx) const{
1939 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1940 Subtarget->isPICStyleGOT());
1941 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1943 return MCSymbolRefExpr::create(MBB->getSymbol(),
1944 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1947 /// Returns relocation base for the given PIC jumptable.
1948 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1949 SelectionDAG &DAG) const {
1950 if (!Subtarget->is64Bit())
1951 // This doesn't have SDLoc associated with it, but is not really the
1952 // same as a Register.
1953 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1954 getPointerTy(DAG.getDataLayout()));
1958 /// This returns the relocation base for the given PIC jumptable,
1959 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1960 const MCExpr *X86TargetLowering::
1961 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1962 MCContext &Ctx) const {
1963 // X86-64 uses RIP relative addressing based on the jump table label.
1964 if (Subtarget->isPICStyleRIPRel())
1965 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1967 // Otherwise, the reference is relative to the PIC base.
1968 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1971 std::pair<const TargetRegisterClass *, uint8_t>
1972 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1974 const TargetRegisterClass *RRC = nullptr;
1976 switch (VT.SimpleTy) {
1978 return TargetLowering::findRepresentativeClass(TRI, VT);
1979 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1980 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1983 RRC = &X86::VR64RegClass;
1985 case MVT::f32: case MVT::f64:
1986 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1987 case MVT::v4f32: case MVT::v2f64:
1988 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1990 RRC = &X86::VR128RegClass;
1993 return std::make_pair(RRC, Cost);
1996 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1997 unsigned &Offset) const {
1998 if (!Subtarget->isTargetLinux())
2001 if (Subtarget->is64Bit()) {
2002 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2004 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2016 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2017 unsigned DestAS) const {
2018 assert(SrcAS != DestAS && "Expected different address spaces!");
2020 return SrcAS < 256 && DestAS < 256;
2023 //===----------------------------------------------------------------------===//
2024 // Return Value Calling Convention Implementation
2025 //===----------------------------------------------------------------------===//
2027 #include "X86GenCallingConv.inc"
2030 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2031 MachineFunction &MF, bool isVarArg,
2032 const SmallVectorImpl<ISD::OutputArg> &Outs,
2033 LLVMContext &Context) const {
2034 SmallVector<CCValAssign, 16> RVLocs;
2035 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2036 return CCInfo.CheckReturn(Outs, RetCC_X86);
2039 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2040 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2045 X86TargetLowering::LowerReturn(SDValue Chain,
2046 CallingConv::ID CallConv, bool isVarArg,
2047 const SmallVectorImpl<ISD::OutputArg> &Outs,
2048 const SmallVectorImpl<SDValue> &OutVals,
2049 SDLoc dl, SelectionDAG &DAG) const {
2050 MachineFunction &MF = DAG.getMachineFunction();
2051 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2053 SmallVector<CCValAssign, 16> RVLocs;
2054 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2055 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2058 SmallVector<SDValue, 6> RetOps;
2059 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2060 // Operand #1 = Bytes To Pop
2061 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2064 // Copy the result values into the output registers.
2065 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2066 CCValAssign &VA = RVLocs[i];
2067 assert(VA.isRegLoc() && "Can only return in registers!");
2068 SDValue ValToCopy = OutVals[i];
2069 EVT ValVT = ValToCopy.getValueType();
2071 // Promote values to the appropriate types.
2072 if (VA.getLocInfo() == CCValAssign::SExt)
2073 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074 else if (VA.getLocInfo() == CCValAssign::ZExt)
2075 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076 else if (VA.getLocInfo() == CCValAssign::AExt) {
2077 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2078 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2080 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2082 else if (VA.getLocInfo() == CCValAssign::BCvt)
2083 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2085 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2086 "Unexpected FP-extend for return value.");
2088 // If this is x86-64, and we disabled SSE, we can't return FP values,
2089 // or SSE or MMX vectors.
2090 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2091 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2092 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2093 report_fatal_error("SSE register return with SSE disabled");
2095 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2096 // llvm-gcc has never done it right and no one has noticed, so this
2097 // should be OK for now.
2098 if (ValVT == MVT::f64 &&
2099 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2100 report_fatal_error("SSE2 register return with SSE2 disabled");
2102 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2103 // the RET instruction and handled by the FP Stackifier.
2104 if (VA.getLocReg() == X86::FP0 ||
2105 VA.getLocReg() == X86::FP1) {
2106 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2107 // change the value to the FP stack register class.
2108 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2109 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2110 RetOps.push_back(ValToCopy);
2111 // Don't emit a copytoreg.
2115 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2116 // which is returned in RAX / RDX.
2117 if (Subtarget->is64Bit()) {
2118 if (ValVT == MVT::x86mmx) {
2119 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2120 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2121 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2123 // If we don't have SSE2 available, convert to v4f32 so the generated
2124 // register is legal.
2125 if (!Subtarget->hasSSE2())
2126 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2131 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2132 Flag = Chain.getValue(1);
2133 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2136 // All x86 ABIs require that for returning structs by value we copy
2137 // the sret argument into %rax/%eax (depending on ABI) for the return.
2138 // We saved the argument into a virtual register in the entry block,
2139 // so now we copy the value out and into %rax/%eax.
2141 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2142 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2143 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2144 // either case FuncInfo->setSRetReturnReg() will have been called.
2145 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2146 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2147 getPointerTy(MF.getDataLayout()));
2150 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2151 X86::RAX : X86::EAX;
2152 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2153 Flag = Chain.getValue(1);
2155 // RAX/EAX now acts like a return value.
2157 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2160 RetOps[0] = Chain; // Update chain.
2162 // Add the flag if we have it.
2164 RetOps.push_back(Flag);
2166 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2169 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2170 if (N->getNumValues() != 1)
2172 if (!N->hasNUsesOfValue(1, 0))
2175 SDValue TCChain = Chain;
2176 SDNode *Copy = *N->use_begin();
2177 if (Copy->getOpcode() == ISD::CopyToReg) {
2178 // If the copy has a glue operand, we conservatively assume it isn't safe to
2179 // perform a tail call.
2180 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2182 TCChain = Copy->getOperand(0);
2183 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2186 bool HasRet = false;
2187 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2189 if (UI->getOpcode() != X86ISD::RET_FLAG)
2191 // If we are returning more than one value, we can definitely
2192 // not make a tail call see PR19530
2193 if (UI->getNumOperands() > 4)
2195 if (UI->getNumOperands() == 4 &&
2196 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2209 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2210 ISD::NodeType ExtendKind) const {
2212 // TODO: Is this also valid on 32-bit?
2213 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2214 ReturnMVT = MVT::i8;
2216 ReturnMVT = MVT::i32;
2218 EVT MinVT = getRegisterType(Context, ReturnMVT);
2219 return VT.bitsLT(MinVT) ? MinVT : VT;
2222 /// Lower the result values of a call into the
2223 /// appropriate copies out of appropriate physical registers.
2226 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2227 CallingConv::ID CallConv, bool isVarArg,
2228 const SmallVectorImpl<ISD::InputArg> &Ins,
2229 SDLoc dl, SelectionDAG &DAG,
2230 SmallVectorImpl<SDValue> &InVals) const {
2232 // Assign locations to each value returned by this call.
2233 SmallVector<CCValAssign, 16> RVLocs;
2234 bool Is64Bit = Subtarget->is64Bit();
2235 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2237 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2239 // Copy all of the result registers out of their specified physreg.
2240 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2241 CCValAssign &VA = RVLocs[i];
2242 EVT CopyVT = VA.getLocVT();
2244 // If this is x86-64, and we disabled SSE, we can't return FP values
2245 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2246 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2247 report_fatal_error("SSE register return with SSE disabled");
2250 // If we prefer to use the value in xmm registers, copy it out as f80 and
2251 // use a truncate to move it from fp stack reg to xmm reg.
2252 bool RoundAfterCopy = false;
2253 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2254 isScalarFPTypeInSSEReg(VA.getValVT())) {
2256 RoundAfterCopy = (CopyVT != VA.getLocVT());
2259 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2260 CopyVT, InFlag).getValue(1);
2261 SDValue Val = Chain.getValue(0);
2264 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2265 // This truncation won't change the value.
2266 DAG.getIntPtrConstant(1, dl));
2268 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2269 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2271 InFlag = Chain.getValue(2);
2272 InVals.push_back(Val);
2278 //===----------------------------------------------------------------------===//
2279 // C & StdCall & Fast Calling Convention implementation
2280 //===----------------------------------------------------------------------===//
2281 // StdCall calling convention seems to be standard for many Windows' API
2282 // routines and around. It differs from C calling convention just a little:
2283 // callee should clean up the stack, not caller. Symbols should be also
2284 // decorated in some fancy way :) It doesn't support any vector arguments.
2285 // For info on fast calling convention see Fast Calling Convention (tail call)
2286 // implementation LowerX86_32FastCCCallTo.
2288 /// CallIsStructReturn - Determines whether a call uses struct return
2290 enum StructReturnType {
2295 static StructReturnType
2296 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2298 return NotStructReturn;
2300 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2301 if (!Flags.isSRet())
2302 return NotStructReturn;
2303 if (Flags.isInReg())
2304 return RegStructReturn;
2305 return StackStructReturn;
2308 /// Determines whether a function uses struct return semantics.
2309 static StructReturnType
2310 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2312 return NotStructReturn;
2314 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2315 if (!Flags.isSRet())
2316 return NotStructReturn;
2317 if (Flags.isInReg())
2318 return RegStructReturn;
2319 return StackStructReturn;
2322 /// Make a copy of an aggregate at address specified by "Src" to address
2323 /// "Dst" with size and alignment information specified by the specific
2324 /// parameter attribute. The copy will be passed as a byval function parameter.
2326 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2327 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2329 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2331 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2332 /*isVolatile*/false, /*AlwaysInline=*/true,
2333 /*isTailCall*/false,
2334 MachinePointerInfo(), MachinePointerInfo());
2337 /// Return true if the calling convention is one that
2338 /// supports tail call optimization.
2339 static bool IsTailCallConvention(CallingConv::ID CC) {
2340 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2341 CC == CallingConv::HiPE);
2344 /// \brief Return true if the calling convention is a C calling convention.
2345 static bool IsCCallConvention(CallingConv::ID CC) {
2346 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2347 CC == CallingConv::X86_64_SysV);
2350 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2352 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2353 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2357 CallingConv::ID CalleeCC = CS.getCallingConv();
2358 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2364 /// Return true if the function is being made into
2365 /// a tailcall target by changing its ABI.
2366 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2367 bool GuaranteedTailCallOpt) {
2368 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2372 X86TargetLowering::LowerMemArgument(SDValue Chain,
2373 CallingConv::ID CallConv,
2374 const SmallVectorImpl<ISD::InputArg> &Ins,
2375 SDLoc dl, SelectionDAG &DAG,
2376 const CCValAssign &VA,
2377 MachineFrameInfo *MFI,
2379 // Create the nodes corresponding to a load from this parameter slot.
2380 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2381 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2382 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2383 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2386 // If value is passed by pointer we have address passed instead of the value
2388 bool ExtendedInMem = VA.isExtInLoc() &&
2389 VA.getValVT().getScalarType() == MVT::i1;
2391 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2392 ValVT = VA.getLocVT();
2394 ValVT = VA.getValVT();
2396 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2397 // changed with more analysis.
2398 // In case of tail call optimization mark all arguments mutable. Since they
2399 // could be overwritten by lowering of arguments in case of a tail call.
2400 if (Flags.isByVal()) {
2401 unsigned Bytes = Flags.getByValSize();
2402 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2403 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2404 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2406 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2407 VA.getLocMemOffset(), isImmutable);
2408 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2409 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2410 MachinePointerInfo::getFixedStack(FI),
2411 false, false, false, 0);
2412 return ExtendedInMem ?
2413 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2417 // FIXME: Get this from tablegen.
2418 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2419 const X86Subtarget *Subtarget) {
2420 assert(Subtarget->is64Bit());
2422 if (Subtarget->isCallingConvWin64(CallConv)) {
2423 static const MCPhysReg GPR64ArgRegsWin64[] = {
2424 X86::RCX, X86::RDX, X86::R8, X86::R9
2426 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2429 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2430 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2432 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2435 // FIXME: Get this from tablegen.
2436 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2437 CallingConv::ID CallConv,
2438 const X86Subtarget *Subtarget) {
2439 assert(Subtarget->is64Bit());
2440 if (Subtarget->isCallingConvWin64(CallConv)) {
2441 // The XMM registers which might contain var arg parameters are shadowed
2442 // in their paired GPR. So we only need to save the GPR to their home
2444 // TODO: __vectorcall will change this.
2448 const Function *Fn = MF.getFunction();
2449 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2450 bool isSoftFloat = Subtarget->useSoftFloat();
2451 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2452 "SSE register cannot be used when SSE is disabled!");
2453 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2454 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2458 static const MCPhysReg XMMArgRegs64Bit[] = {
2459 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2460 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2462 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2466 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2467 CallingConv::ID CallConv,
2469 const SmallVectorImpl<ISD::InputArg> &Ins,
2472 SmallVectorImpl<SDValue> &InVals)
2474 MachineFunction &MF = DAG.getMachineFunction();
2475 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2476 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2478 const Function* Fn = MF.getFunction();
2479 if (Fn->hasExternalLinkage() &&
2480 Subtarget->isTargetCygMing() &&
2481 Fn->getName() == "main")
2482 FuncInfo->setForceFramePointer(true);
2484 MachineFrameInfo *MFI = MF.getFrameInfo();
2485 bool Is64Bit = Subtarget->is64Bit();
2486 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2488 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2489 "Var args not supported with calling convention fastcc, ghc or hipe");
2491 // Assign locations to all of the incoming arguments.
2492 SmallVector<CCValAssign, 16> ArgLocs;
2493 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2495 // Allocate shadow area for Win64
2497 CCInfo.AllocateStack(32, 8);
2499 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2501 unsigned LastVal = ~0U;
2503 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504 CCValAssign &VA = ArgLocs[i];
2505 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2507 assert(VA.getValNo() != LastVal &&
2508 "Don't support value assigned to multiple locs yet");
2510 LastVal = VA.getValNo();
2512 if (VA.isRegLoc()) {
2513 EVT RegVT = VA.getLocVT();
2514 const TargetRegisterClass *RC;
2515 if (RegVT == MVT::i32)
2516 RC = &X86::GR32RegClass;
2517 else if (Is64Bit && RegVT == MVT::i64)
2518 RC = &X86::GR64RegClass;
2519 else if (RegVT == MVT::f32)
2520 RC = &X86::FR32RegClass;
2521 else if (RegVT == MVT::f64)
2522 RC = &X86::FR64RegClass;
2523 else if (RegVT.is512BitVector())
2524 RC = &X86::VR512RegClass;
2525 else if (RegVT.is256BitVector())
2526 RC = &X86::VR256RegClass;
2527 else if (RegVT.is128BitVector())
2528 RC = &X86::VR128RegClass;
2529 else if (RegVT == MVT::x86mmx)
2530 RC = &X86::VR64RegClass;
2531 else if (RegVT == MVT::i1)
2532 RC = &X86::VK1RegClass;
2533 else if (RegVT == MVT::v8i1)
2534 RC = &X86::VK8RegClass;
2535 else if (RegVT == MVT::v16i1)
2536 RC = &X86::VK16RegClass;
2537 else if (RegVT == MVT::v32i1)
2538 RC = &X86::VK32RegClass;
2539 else if (RegVT == MVT::v64i1)
2540 RC = &X86::VK64RegClass;
2542 llvm_unreachable("Unknown argument type!");
2544 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2545 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2547 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2548 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2550 if (VA.getLocInfo() == CCValAssign::SExt)
2551 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2552 DAG.getValueType(VA.getValVT()));
2553 else if (VA.getLocInfo() == CCValAssign::ZExt)
2554 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2555 DAG.getValueType(VA.getValVT()));
2556 else if (VA.getLocInfo() == CCValAssign::BCvt)
2557 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2559 if (VA.isExtInLoc()) {
2560 // Handle MMX values passed in XMM regs.
2561 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2562 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2564 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2567 assert(VA.isMemLoc());
2568 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2571 // If value is passed via pointer - do a load.
2572 if (VA.getLocInfo() == CCValAssign::Indirect)
2573 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2574 MachinePointerInfo(), false, false, false, 0);
2576 InVals.push_back(ArgValue);
2579 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2580 // All x86 ABIs require that for returning structs by value we copy the
2581 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2582 // the argument into a virtual register so that we can access it from the
2584 if (Ins[i].Flags.isSRet()) {
2585 unsigned Reg = FuncInfo->getSRetReturnReg();
2587 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2588 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2589 FuncInfo->setSRetReturnReg(Reg);
2591 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2592 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2597 unsigned StackSize = CCInfo.getNextStackOffset();
2598 // Align stack specially for tail calls.
2599 if (FuncIsMadeTailCallSafe(CallConv,
2600 MF.getTarget().Options.GuaranteedTailCallOpt))
2601 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2603 // If the function takes variable number of arguments, make a frame index for
2604 // the start of the first vararg value... for expansion of llvm.va_start. We
2605 // can skip this if there are no va_start calls.
2606 if (MFI->hasVAStart() &&
2607 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2608 CallConv != CallingConv::X86_ThisCall))) {
2609 FuncInfo->setVarArgsFrameIndex(
2610 MFI->CreateFixedObject(1, StackSize, true));
2613 MachineModuleInfo &MMI = MF.getMMI();
2614 const Function *WinEHParent = nullptr;
2615 if (MMI.hasWinEHFuncInfo(Fn))
2616 WinEHParent = MMI.getWinEHParent(Fn);
2617 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2618 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2620 // Figure out if XMM registers are in use.
2621 assert(!(Subtarget->useSoftFloat() &&
2622 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2623 "SSE register cannot be used when SSE is disabled!");
2625 // 64-bit calling conventions support varargs and register parameters, so we
2626 // have to do extra work to spill them in the prologue.
2627 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2628 // Find the first unallocated argument registers.
2629 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2630 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2631 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2632 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2633 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2634 "SSE register cannot be used when SSE is disabled!");
2636 // Gather all the live in physical registers.
2637 SmallVector<SDValue, 6> LiveGPRs;
2638 SmallVector<SDValue, 8> LiveXMMRegs;
2640 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2641 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2643 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2645 if (!ArgXMMs.empty()) {
2646 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2647 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2648 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2649 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2650 LiveXMMRegs.push_back(
2651 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2656 // Get to the caller-allocated home save location. Add 8 to account
2657 // for the return address.
2658 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2659 FuncInfo->setRegSaveFrameIndex(
2660 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2661 // Fixup to set vararg frame on shadow area (4 x i64).
2663 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2665 // For X86-64, if there are vararg parameters that are passed via
2666 // registers, then we must store them to their spots on the stack so
2667 // they may be loaded by deferencing the result of va_next.
2668 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2669 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2670 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2671 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2674 // Store the integer parameter registers.
2675 SmallVector<SDValue, 8> MemOps;
2676 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2677 getPointerTy(DAG.getDataLayout()));
2678 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2679 for (SDValue Val : LiveGPRs) {
2680 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2681 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2683 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2684 MachinePointerInfo::getFixedStack(
2685 FuncInfo->getRegSaveFrameIndex(), Offset),
2687 MemOps.push_back(Store);
2691 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2692 // Now store the XMM (fp + vector) parameter registers.
2693 SmallVector<SDValue, 12> SaveXMMOps;
2694 SaveXMMOps.push_back(Chain);
2695 SaveXMMOps.push_back(ALVal);
2696 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2697 FuncInfo->getRegSaveFrameIndex(), dl));
2698 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2699 FuncInfo->getVarArgsFPOffset(), dl));
2700 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2702 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2703 MVT::Other, SaveXMMOps));
2706 if (!MemOps.empty())
2707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2708 } else if (IsWin64 && IsWinEHOutlined) {
2709 // Get to the caller-allocated home save location. Add 8 to account
2710 // for the return address.
2711 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2712 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2713 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2715 MMI.getWinEHFuncInfo(Fn)
2716 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2717 FuncInfo->getRegSaveFrameIndex();
2719 // Store the second integer parameter (rdx) into rsp+16 relative to the
2720 // stack pointer at the entry of the function.
2721 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2722 getPointerTy(DAG.getDataLayout()));
2723 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2724 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2725 Chain = DAG.getStore(
2726 Val.getValue(1), dl, Val, RSFIN,
2727 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2728 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2731 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2732 // Find the largest legal vector type.
2733 MVT VecVT = MVT::Other;
2734 // FIXME: Only some x86_32 calling conventions support AVX512.
2735 if (Subtarget->hasAVX512() &&
2736 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2737 CallConv == CallingConv::Intel_OCL_BI)))
2738 VecVT = MVT::v16f32;
2739 else if (Subtarget->hasAVX())
2741 else if (Subtarget->hasSSE2())
2744 // We forward some GPRs and some vector types.
2745 SmallVector<MVT, 2> RegParmTypes;
2746 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2747 RegParmTypes.push_back(IntVT);
2748 if (VecVT != MVT::Other)
2749 RegParmTypes.push_back(VecVT);
2751 // Compute the set of forwarded registers. The rest are scratch.
2752 SmallVectorImpl<ForwardedRegister> &Forwards =
2753 FuncInfo->getForwardedMustTailRegParms();
2754 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2756 // Conservatively forward AL on x86_64, since it might be used for varargs.
2757 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2758 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2759 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2762 // Copy all forwards from physical to virtual registers.
2763 for (ForwardedRegister &F : Forwards) {
2764 // FIXME: Can we use a less constrained schedule?
2765 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2766 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2767 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2771 // Some CCs need callee pop.
2772 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2773 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2774 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2776 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2777 // If this is an sret function, the return should pop the hidden pointer.
2778 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2779 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2780 argsAreStructReturn(Ins) == StackStructReturn)
2781 FuncInfo->setBytesToPopOnReturn(4);
2785 // RegSaveFrameIndex is X86-64 only.
2786 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2787 if (CallConv == CallingConv::X86_FastCall ||
2788 CallConv == CallingConv::X86_ThisCall)
2789 // fastcc functions can't have varargs.
2790 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2793 FuncInfo->setArgumentStackSize(StackSize);
2795 if (IsWinEHParent) {
2797 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2798 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2799 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2800 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2801 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2802 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2803 /*isVolatile=*/true,
2804 /*isNonTemporal=*/false, /*Alignment=*/0);
2806 // Functions using Win32 EH are considered to have opaque SP adjustments
2807 // to force local variables to be addressed from the frame or base
2809 MFI->setHasOpaqueSPAdjustment(true);
2817 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2818 SDValue StackPtr, SDValue Arg,
2819 SDLoc dl, SelectionDAG &DAG,
2820 const CCValAssign &VA,
2821 ISD::ArgFlagsTy Flags) const {
2822 unsigned LocMemOffset = VA.getLocMemOffset();
2823 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2824 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2826 if (Flags.isByVal())
2827 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2829 return DAG.getStore(Chain, dl, Arg, PtrOff,
2830 MachinePointerInfo::getStack(LocMemOffset),
2834 /// Emit a load of return address if tail call
2835 /// optimization is performed and it is required.
2837 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2838 SDValue &OutRetAddr, SDValue Chain,
2839 bool IsTailCall, bool Is64Bit,
2840 int FPDiff, SDLoc dl) const {
2841 // Adjust the Return address stack slot.
2842 EVT VT = getPointerTy(DAG.getDataLayout());
2843 OutRetAddr = getReturnAddressFrameIndex(DAG);
2845 // Load the "old" Return address.
2846 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2847 false, false, false, 0);
2848 return SDValue(OutRetAddr.getNode(), 1);
2851 /// Emit a store of the return address if tail call
2852 /// optimization is performed and it is required (FPDiff!=0).
2853 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2854 SDValue Chain, SDValue RetAddrFrIdx,
2855 EVT PtrVT, unsigned SlotSize,
2856 int FPDiff, SDLoc dl) {
2857 // Store the return address to the appropriate stack slot.
2858 if (!FPDiff) return Chain;
2859 // Calculate the new stack slot for the return address.
2860 int NewReturnAddrFI =
2861 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2863 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2864 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2865 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2871 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2872 SmallVectorImpl<SDValue> &InVals) const {
2873 SelectionDAG &DAG = CLI.DAG;
2875 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2876 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2877 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2878 SDValue Chain = CLI.Chain;
2879 SDValue Callee = CLI.Callee;
2880 CallingConv::ID CallConv = CLI.CallConv;
2881 bool &isTailCall = CLI.IsTailCall;
2882 bool isVarArg = CLI.IsVarArg;
2884 MachineFunction &MF = DAG.getMachineFunction();
2885 bool Is64Bit = Subtarget->is64Bit();
2886 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2887 StructReturnType SR = callIsStructReturn(Outs);
2888 bool IsSibcall = false;
2889 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2890 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2892 if (Attr.getValueAsString() == "true")
2895 if (Subtarget->isPICStyleGOT() &&
2896 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2897 // If we are using a GOT, disable tail calls to external symbols with
2898 // default visibility. Tail calling such a symbol requires using a GOT
2899 // relocation, which forces early binding of the symbol. This breaks code
2900 // that require lazy function symbol resolution. Using musttail or
2901 // GuaranteedTailCallOpt will override this.
2902 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2903 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2904 G->getGlobal()->hasDefaultVisibility()))
2908 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2910 // Force this to be a tail call. The verifier rules are enough to ensure
2911 // that we can lower this successfully without moving the return address
2914 } else if (isTailCall) {
2915 // Check if it's really possible to do a tail call.
2916 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2917 isVarArg, SR != NotStructReturn,
2918 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2919 Outs, OutVals, Ins, DAG);
2921 // Sibcalls are automatically detected tailcalls which do not require
2923 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2930 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2931 "Var args not supported with calling convention fastcc, ghc or hipe");
2933 // Analyze operands of the call, assigning locations to each operand.
2934 SmallVector<CCValAssign, 16> ArgLocs;
2935 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2937 // Allocate shadow area for Win64
2939 CCInfo.AllocateStack(32, 8);
2941 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2943 // Get a count of how many bytes are to be pushed on the stack.
2944 unsigned NumBytes = CCInfo.getNextStackOffset();
2946 // This is a sibcall. The memory operands are available in caller's
2947 // own caller's stack.
2949 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2950 IsTailCallConvention(CallConv))
2951 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2954 if (isTailCall && !IsSibcall && !IsMustTail) {
2955 // Lower arguments at fp - stackoffset + fpdiff.
2956 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2958 FPDiff = NumBytesCallerPushed - NumBytes;
2960 // Set the delta of movement of the returnaddr stackslot.
2961 // But only set if delta is greater than previous delta.
2962 if (FPDiff < X86Info->getTCReturnAddrDelta())
2963 X86Info->setTCReturnAddrDelta(FPDiff);
2966 unsigned NumBytesToPush = NumBytes;
2967 unsigned NumBytesToPop = NumBytes;
2969 // If we have an inalloca argument, all stack space has already been allocated
2970 // for us and be right at the top of the stack. We don't support multiple
2971 // arguments passed in memory when using inalloca.
2972 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2974 if (!ArgLocs.back().isMemLoc())
2975 report_fatal_error("cannot use inalloca attribute on a register "
2977 if (ArgLocs.back().getLocMemOffset() != 0)
2978 report_fatal_error("any parameter with the inalloca attribute must be "
2979 "the only memory argument");
2983 Chain = DAG.getCALLSEQ_START(
2984 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2986 SDValue RetAddrFrIdx;
2987 // Load return address for tail calls.
2988 if (isTailCall && FPDiff)
2989 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2990 Is64Bit, FPDiff, dl);
2992 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2993 SmallVector<SDValue, 8> MemOpChains;
2996 // Walk the register/memloc assignments, inserting copies/loads. In the case
2997 // of tail call optimization arguments are handle later.
2998 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2999 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3000 // Skip inalloca arguments, they have already been written.
3001 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3002 if (Flags.isInAlloca())
3005 CCValAssign &VA = ArgLocs[i];
3006 EVT RegVT = VA.getLocVT();
3007 SDValue Arg = OutVals[i];
3008 bool isByVal = Flags.isByVal();
3010 // Promote the value if needed.
3011 switch (VA.getLocInfo()) {
3012 default: llvm_unreachable("Unknown loc info!");
3013 case CCValAssign::Full: break;
3014 case CCValAssign::SExt:
3015 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3017 case CCValAssign::ZExt:
3018 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3020 case CCValAssign::AExt:
3021 if (Arg.getValueType().isVector() &&
3022 Arg.getValueType().getScalarType() == MVT::i1)
3023 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024 else if (RegVT.is128BitVector()) {
3025 // Special case: passing MMX values in XMM registers.
3026 Arg = DAG.getBitcast(MVT::i64, Arg);
3027 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3028 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3030 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3032 case CCValAssign::BCvt:
3033 Arg = DAG.getBitcast(RegVT, Arg);
3035 case CCValAssign::Indirect: {
3036 // Store the argument.
3037 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3038 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3039 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3040 MachinePointerInfo::getFixedStack(FI),
3047 if (VA.isRegLoc()) {
3048 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3049 if (isVarArg && IsWin64) {
3050 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3051 // shadow reg if callee is a varargs function.
3052 unsigned ShadowReg = 0;
3053 switch (VA.getLocReg()) {
3054 case X86::XMM0: ShadowReg = X86::RCX; break;
3055 case X86::XMM1: ShadowReg = X86::RDX; break;
3056 case X86::XMM2: ShadowReg = X86::R8; break;
3057 case X86::XMM3: ShadowReg = X86::R9; break;
3060 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3062 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3063 assert(VA.isMemLoc());
3064 if (!StackPtr.getNode())
3065 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3066 getPointerTy(DAG.getDataLayout()));
3067 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3068 dl, DAG, VA, Flags));
3072 if (!MemOpChains.empty())
3073 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3075 if (Subtarget->isPICStyleGOT()) {
3076 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3079 RegsToPass.push_back(std::make_pair(
3080 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3081 getPointerTy(DAG.getDataLayout()))));
3083 // If we are tail calling and generating PIC/GOT style code load the
3084 // address of the callee into ECX. The value in ecx is used as target of
3085 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3086 // for tail calls on PIC/GOT architectures. Normally we would just put the
3087 // address of GOT into ebx and then call target@PLT. But for tail calls
3088 // ebx would be restored (since ebx is callee saved) before jumping to the
3091 // Note: The actual moving to ECX is done further down.
3092 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3093 if (G && !G->getGlobal()->hasLocalLinkage() &&
3094 G->getGlobal()->hasDefaultVisibility())
3095 Callee = LowerGlobalAddress(Callee, DAG);
3096 else if (isa<ExternalSymbolSDNode>(Callee))
3097 Callee = LowerExternalSymbol(Callee, DAG);
3101 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3102 // From AMD64 ABI document:
3103 // For calls that may call functions that use varargs or stdargs
3104 // (prototype-less calls or calls to functions containing ellipsis (...) in
3105 // the declaration) %al is used as hidden argument to specify the number
3106 // of SSE registers used. The contents of %al do not need to match exactly
3107 // the number of registers, but must be an ubound on the number of SSE
3108 // registers used and is in the range 0 - 8 inclusive.
3110 // Count the number of XMM registers allocated.
3111 static const MCPhysReg XMMArgRegs[] = {
3112 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3113 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3115 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3116 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3117 && "SSE registers cannot be used when SSE is disabled");
3119 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3120 DAG.getConstant(NumXMMRegs, dl,
3124 if (isVarArg && IsMustTail) {
3125 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3126 for (const auto &F : Forwards) {
3127 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3128 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3132 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3133 // don't need this because the eligibility check rejects calls that require
3134 // shuffling arguments passed in memory.
3135 if (!IsSibcall && isTailCall) {
3136 // Force all the incoming stack arguments to be loaded from the stack
3137 // before any new outgoing arguments are stored to the stack, because the
3138 // outgoing stack slots may alias the incoming argument stack slots, and
3139 // the alias isn't otherwise explicit. This is slightly more conservative
3140 // than necessary, because it means that each store effectively depends
3141 // on every argument instead of just those arguments it would clobber.
3142 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3144 SmallVector<SDValue, 8> MemOpChains2;
3147 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3148 CCValAssign &VA = ArgLocs[i];
3151 assert(VA.isMemLoc());
3152 SDValue Arg = OutVals[i];
3153 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3154 // Skip inalloca arguments. They don't require any work.
3155 if (Flags.isInAlloca())
3157 // Create frame index.
3158 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3159 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3160 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3161 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3163 if (Flags.isByVal()) {
3164 // Copy relative to framepointer.
3165 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3166 if (!StackPtr.getNode())
3167 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3168 getPointerTy(DAG.getDataLayout()));
3169 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3172 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3176 // Store relative to framepointer.
3177 MemOpChains2.push_back(
3178 DAG.getStore(ArgChain, dl, Arg, FIN,
3179 MachinePointerInfo::getFixedStack(FI),
3184 if (!MemOpChains2.empty())
3185 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3187 // Store the return address to the appropriate stack slot.
3188 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3189 getPointerTy(DAG.getDataLayout()),
3190 RegInfo->getSlotSize(), FPDiff, dl);
3193 // Build a sequence of copy-to-reg nodes chained together with token chain
3194 // and flag operands which copy the outgoing args into registers.
3196 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3197 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3198 RegsToPass[i].second, InFlag);
3199 InFlag = Chain.getValue(1);
3202 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3203 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3204 // In the 64-bit large code model, we have to make all calls
3205 // through a register, since the call instruction's 32-bit
3206 // pc-relative offset may not be large enough to hold the whole
3208 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3209 // If the callee is a GlobalAddress node (quite common, every direct call
3210 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3212 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3214 // We should use extra load for direct calls to dllimported functions in
3216 const GlobalValue *GV = G->getGlobal();
3217 if (!GV->hasDLLImportStorageClass()) {
3218 unsigned char OpFlags = 0;
3219 bool ExtraLoad = false;
3220 unsigned WrapperKind = ISD::DELETED_NODE;
3222 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3223 // external symbols most go through the PLT in PIC mode. If the symbol
3224 // has hidden or protected visibility, or if it is static or local, then
3225 // we don't need to use the PLT - we can directly call it.
3226 if (Subtarget->isTargetELF() &&
3227 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3228 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3229 OpFlags = X86II::MO_PLT;
3230 } else if (Subtarget->isPICStyleStubAny() &&
3231 !GV->isStrongDefinitionForLinker() &&
3232 (!Subtarget->getTargetTriple().isMacOSX() ||
3233 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3234 // PC-relative references to external symbols should go through $stub,
3235 // unless we're building with the leopard linker or later, which
3236 // automatically synthesizes these stubs.
3237 OpFlags = X86II::MO_DARWIN_STUB;
3238 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3239 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3240 // If the function is marked as non-lazy, generate an indirect call
3241 // which loads from the GOT directly. This avoids runtime overhead
3242 // at the cost of eager binding (and one extra byte of encoding).
3243 OpFlags = X86II::MO_GOTPCREL;
3244 WrapperKind = X86ISD::WrapperRIP;
3248 Callee = DAG.getTargetGlobalAddress(
3249 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3251 // Add a wrapper if needed.
3252 if (WrapperKind != ISD::DELETED_NODE)
3253 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3254 getPointerTy(DAG.getDataLayout()), Callee);
3255 // Add extra indirection if needed.
3257 Callee = DAG.getLoad(
3258 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3259 MachinePointerInfo::getGOT(), false, false, false, 0);
3261 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3262 unsigned char OpFlags = 0;
3264 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3265 // external symbols should go through the PLT.
3266 if (Subtarget->isTargetELF() &&
3267 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3268 OpFlags = X86II::MO_PLT;
3269 } else if (Subtarget->isPICStyleStubAny() &&
3270 (!Subtarget->getTargetTriple().isMacOSX() ||
3271 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272 // PC-relative references to external symbols should go through $stub,
3273 // unless we're building with the leopard linker or later, which
3274 // automatically synthesizes these stubs.
3275 OpFlags = X86II::MO_DARWIN_STUB;
3278 Callee = DAG.getTargetExternalSymbol(
3279 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3280 } else if (Subtarget->isTarget64BitILP32() &&
3281 Callee->getValueType(0) == MVT::i32) {
3282 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3283 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3286 // Returns a chain & a flag for retval copy to use.
3287 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3288 SmallVector<SDValue, 8> Ops;
3290 if (!IsSibcall && isTailCall) {
3291 Chain = DAG.getCALLSEQ_END(Chain,
3292 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3293 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3294 InFlag = Chain.getValue(1);
3297 Ops.push_back(Chain);
3298 Ops.push_back(Callee);
3301 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3303 // Add argument registers to the end of the list so that they are known live
3305 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3306 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3307 RegsToPass[i].second.getValueType()));
3309 // Add a register mask operand representing the call-preserved registers.
3310 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3311 assert(Mask && "Missing call preserved mask for calling convention");
3313 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3314 // the function clobbers all registers. If an exception is thrown, the runtime
3315 // will not restore CSRs.
3316 // FIXME: Model this more precisely so that we can register allocate across
3317 // the normal edge and spill and fill across the exceptional edge.
3318 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3319 const Function *CallerFn = MF.getFunction();
3320 EHPersonality Pers =
3321 CallerFn->hasPersonalityFn()
3322 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3323 : EHPersonality::Unknown;
3324 if (isMSVCEHPersonality(Pers))
3325 Mask = RegInfo->getNoPreservedMask();
3328 Ops.push_back(DAG.getRegisterMask(Mask));
3330 if (InFlag.getNode())
3331 Ops.push_back(InFlag);
3335 //// If this is the first return lowered for this function, add the regs
3336 //// to the liveout set for the function.
3337 // This isn't right, although it's probably harmless on x86; liveouts
3338 // should be computed from returns not tail calls. Consider a void
3339 // function making a tail call to a function returning int.
3340 MF.getFrameInfo()->setHasTailCall();
3341 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3344 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3345 InFlag = Chain.getValue(1);
3347 // Create the CALLSEQ_END node.
3348 unsigned NumBytesForCalleeToPop;
3349 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3350 DAG.getTarget().Options.GuaranteedTailCallOpt))
3351 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3352 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3353 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3354 SR == StackStructReturn)
3355 // If this is a call to a struct-return function, the callee
3356 // pops the hidden struct pointer, so we have to push it back.
3357 // This is common for Darwin/X86, Linux & Mingw32 targets.
3358 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3359 NumBytesForCalleeToPop = 4;
3361 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3363 // Returns a flag for retval copy to use.
3365 Chain = DAG.getCALLSEQ_END(Chain,
3366 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3367 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3370 InFlag = Chain.getValue(1);
3373 // Handle result values, copying them out of physregs into vregs that we
3375 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3376 Ins, dl, DAG, InVals);
3379 //===----------------------------------------------------------------------===//
3380 // Fast Calling Convention (tail call) implementation
3381 //===----------------------------------------------------------------------===//
3383 // Like std call, callee cleans arguments, convention except that ECX is
3384 // reserved for storing the tail called function address. Only 2 registers are
3385 // free for argument passing (inreg). Tail call optimization is performed
3387 // * tailcallopt is enabled
3388 // * caller/callee are fastcc
3389 // On X86_64 architecture with GOT-style position independent code only local
3390 // (within module) calls are supported at the moment.
3391 // To keep the stack aligned according to platform abi the function
3392 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3393 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3394 // If a tail called function callee has more arguments than the caller the
3395 // caller needs to make sure that there is room to move the RETADDR to. This is
3396 // achieved by reserving an area the size of the argument delta right after the
3397 // original RETADDR, but before the saved framepointer or the spilled registers
3398 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3410 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3411 /// for a 16 byte align requirement.
3413 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3414 SelectionDAG& DAG) const {
3415 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3416 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3417 unsigned StackAlignment = TFI.getStackAlignment();
3418 uint64_t AlignMask = StackAlignment - 1;
3419 int64_t Offset = StackSize;
3420 unsigned SlotSize = RegInfo->getSlotSize();
3421 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3422 // Number smaller than 12 so just add the difference.
3423 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3425 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3426 Offset = ((~AlignMask) & Offset) + StackAlignment +
3427 (StackAlignment-SlotSize);
3432 /// MatchingStackOffset - Return true if the given stack call argument is
3433 /// already available in the same position (relatively) of the caller's
3434 /// incoming argument stack.
3436 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3437 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3438 const X86InstrInfo *TII) {
3439 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3441 if (Arg.getOpcode() == ISD::CopyFromReg) {
3442 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3443 if (!TargetRegisterInfo::isVirtualRegister(VR))
3445 MachineInstr *Def = MRI->getVRegDef(VR);
3448 if (!Flags.isByVal()) {
3449 if (!TII->isLoadFromStackSlot(Def, FI))
3452 unsigned Opcode = Def->getOpcode();
3453 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3454 Opcode == X86::LEA64_32r) &&
3455 Def->getOperand(1).isFI()) {
3456 FI = Def->getOperand(1).getIndex();
3457 Bytes = Flags.getByValSize();
3461 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3462 if (Flags.isByVal())
3463 // ByVal argument is passed in as a pointer but it's now being
3464 // dereferenced. e.g.
3465 // define @foo(%struct.X* %A) {
3466 // tail call @bar(%struct.X* byval %A)
3469 SDValue Ptr = Ld->getBasePtr();
3470 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3473 FI = FINode->getIndex();
3474 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3475 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3476 FI = FINode->getIndex();
3477 Bytes = Flags.getByValSize();
3481 assert(FI != INT_MAX);
3482 if (!MFI->isFixedObjectIndex(FI))
3484 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3487 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3488 /// for tail call optimization. Targets which want to do tail call
3489 /// optimization should implement this function.
3491 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3492 CallingConv::ID CalleeCC,
3494 bool isCalleeStructRet,
3495 bool isCallerStructRet,
3497 const SmallVectorImpl<ISD::OutputArg> &Outs,
3498 const SmallVectorImpl<SDValue> &OutVals,
3499 const SmallVectorImpl<ISD::InputArg> &Ins,
3500 SelectionDAG &DAG) const {
3501 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3504 // If -tailcallopt is specified, make fastcc functions tail-callable.
3505 const MachineFunction &MF = DAG.getMachineFunction();
3506 const Function *CallerF = MF.getFunction();
3508 // If the function return type is x86_fp80 and the callee return type is not,
3509 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3510 // perform a tailcall optimization here.
3511 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3514 CallingConv::ID CallerCC = CallerF->getCallingConv();
3515 bool CCMatch = CallerCC == CalleeCC;
3516 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3517 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3519 // Win64 functions have extra shadow space for argument homing. Don't do the
3520 // sibcall if the caller and callee have mismatched expectations for this
3522 if (IsCalleeWin64 != IsCallerWin64)
3525 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3526 if (IsTailCallConvention(CalleeCC) && CCMatch)
3531 // Look for obvious safe cases to perform tail call optimization that do not
3532 // require ABI changes. This is what gcc calls sibcall.
3534 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3535 // emit a special epilogue.
3536 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3537 if (RegInfo->needsStackRealignment(MF))
3540 // Also avoid sibcall optimization if either caller or callee uses struct
3541 // return semantics.
3542 if (isCalleeStructRet || isCallerStructRet)
3545 // An stdcall/thiscall caller is expected to clean up its arguments; the
3546 // callee isn't going to do that.
3547 // FIXME: this is more restrictive than needed. We could produce a tailcall
3548 // when the stack adjustment matches. For example, with a thiscall that takes
3549 // only one argument.
3550 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3551 CallerCC == CallingConv::X86_ThisCall))
3554 // Do not sibcall optimize vararg calls unless all arguments are passed via
3556 if (isVarArg && !Outs.empty()) {
3558 // Optimizing for varargs on Win64 is unlikely to be safe without
3559 // additional testing.
3560 if (IsCalleeWin64 || IsCallerWin64)
3563 SmallVector<CCValAssign, 16> ArgLocs;
3564 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3567 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3568 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3569 if (!ArgLocs[i].isRegLoc())
3573 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3574 // stack. Therefore, if it's not used by the call it is not safe to optimize
3575 // this into a sibcall.
3576 bool Unused = false;
3577 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3584 SmallVector<CCValAssign, 16> RVLocs;
3585 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3587 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3588 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3589 CCValAssign &VA = RVLocs[i];
3590 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3595 // If the calling conventions do not match, then we'd better make sure the
3596 // results are returned in the same way as what the caller expects.
3598 SmallVector<CCValAssign, 16> RVLocs1;
3599 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3601 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3603 SmallVector<CCValAssign, 16> RVLocs2;
3604 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3606 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3608 if (RVLocs1.size() != RVLocs2.size())
3610 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3611 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3613 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3615 if (RVLocs1[i].isRegLoc()) {
3616 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3619 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3625 // If the callee takes no arguments then go on to check the results of the
3627 if (!Outs.empty()) {
3628 // Check if stack adjustment is needed. For now, do not do this if any
3629 // argument is passed on the stack.
3630 SmallVector<CCValAssign, 16> ArgLocs;
3631 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3634 // Allocate shadow area for Win64
3636 CCInfo.AllocateStack(32, 8);
3638 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3639 if (CCInfo.getNextStackOffset()) {
3640 MachineFunction &MF = DAG.getMachineFunction();
3641 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3644 // Check if the arguments are already laid out in the right way as
3645 // the caller's fixed stack objects.
3646 MachineFrameInfo *MFI = MF.getFrameInfo();
3647 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3648 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3649 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3650 CCValAssign &VA = ArgLocs[i];
3651 SDValue Arg = OutVals[i];
3652 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3653 if (VA.getLocInfo() == CCValAssign::Indirect)
3655 if (!VA.isRegLoc()) {
3656 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3663 // If the tailcall address may be in a register, then make sure it's
3664 // possible to register allocate for it. In 32-bit, the call address can
3665 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3666 // callee-saved registers are restored. These happen to be the same
3667 // registers used to pass 'inreg' arguments so watch out for those.
3668 if (!Subtarget->is64Bit() &&
3669 ((!isa<GlobalAddressSDNode>(Callee) &&
3670 !isa<ExternalSymbolSDNode>(Callee)) ||
3671 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3672 unsigned NumInRegs = 0;
3673 // In PIC we need an extra register to formulate the address computation
3675 unsigned MaxInRegs =
3676 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3678 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3679 CCValAssign &VA = ArgLocs[i];
3682 unsigned Reg = VA.getLocReg();
3685 case X86::EAX: case X86::EDX: case X86::ECX:
3686 if (++NumInRegs == MaxInRegs)
3698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3699 const TargetLibraryInfo *libInfo) const {
3700 return X86::createFastISel(funcInfo, libInfo);
3703 //===----------------------------------------------------------------------===//
3704 // Other Lowering Hooks
3705 //===----------------------------------------------------------------------===//
3707 static bool MayFoldLoad(SDValue Op) {
3708 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3711 static bool MayFoldIntoStore(SDValue Op) {
3712 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3715 static bool isTargetShuffle(unsigned Opcode) {
3717 default: return false;
3718 case X86ISD::BLENDI:
3719 case X86ISD::PSHUFB:
3720 case X86ISD::PSHUFD:
3721 case X86ISD::PSHUFHW:
3722 case X86ISD::PSHUFLW:
3724 case X86ISD::PALIGNR:
3725 case X86ISD::MOVLHPS:
3726 case X86ISD::MOVLHPD:
3727 case X86ISD::MOVHLPS:
3728 case X86ISD::MOVLPS:
3729 case X86ISD::MOVLPD:
3730 case X86ISD::MOVSHDUP:
3731 case X86ISD::MOVSLDUP:
3732 case X86ISD::MOVDDUP:
3735 case X86ISD::UNPCKL:
3736 case X86ISD::UNPCKH:
3737 case X86ISD::VPERMILPI:
3738 case X86ISD::VPERM2X128:
3739 case X86ISD::VPERMI:
3744 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3745 SDValue V1, unsigned TargetMask,
3746 SelectionDAG &DAG) {
3748 default: llvm_unreachable("Unknown x86 shuffle node");
3749 case X86ISD::PSHUFD:
3750 case X86ISD::PSHUFHW:
3751 case X86ISD::PSHUFLW:
3752 case X86ISD::VPERMILPI:
3753 case X86ISD::VPERMI:
3754 return DAG.getNode(Opc, dl, VT, V1,
3755 DAG.getConstant(TargetMask, dl, MVT::i8));
3759 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3760 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3762 default: llvm_unreachable("Unknown x86 shuffle node");
3763 case X86ISD::MOVLHPS:
3764 case X86ISD::MOVLHPD:
3765 case X86ISD::MOVHLPS:
3766 case X86ISD::MOVLPS:
3767 case X86ISD::MOVLPD:
3770 case X86ISD::UNPCKL:
3771 case X86ISD::UNPCKH:
3772 return DAG.getNode(Opc, dl, VT, V1, V2);
3776 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3777 MachineFunction &MF = DAG.getMachineFunction();
3778 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3779 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3780 int ReturnAddrIndex = FuncInfo->getRAIndex();
3782 if (ReturnAddrIndex == 0) {
3783 // Set up a frame object for the return address.
3784 unsigned SlotSize = RegInfo->getSlotSize();
3785 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3788 FuncInfo->setRAIndex(ReturnAddrIndex);
3791 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3794 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3795 bool hasSymbolicDisplacement) {
3796 // Offset should fit into 32 bit immediate field.
3797 if (!isInt<32>(Offset))
3800 // If we don't have a symbolic displacement - we don't have any extra
3802 if (!hasSymbolicDisplacement)
3805 // FIXME: Some tweaks might be needed for medium code model.
3806 if (M != CodeModel::Small && M != CodeModel::Kernel)
3809 // For small code model we assume that latest object is 16MB before end of 31
3810 // bits boundary. We may also accept pretty large negative constants knowing
3811 // that all objects are in the positive half of address space.
3812 if (M == CodeModel::Small && Offset < 16*1024*1024)
3815 // For kernel code model we know that all object resist in the negative half
3816 // of 32bits address space. We may not accept negative offsets, since they may
3817 // be just off and we may accept pretty large positive ones.
3818 if (M == CodeModel::Kernel && Offset >= 0)
3824 /// isCalleePop - Determines whether the callee is required to pop its
3825 /// own arguments. Callee pop is necessary to support tail calls.
3826 bool X86::isCalleePop(CallingConv::ID CallingConv,
3827 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3828 switch (CallingConv) {
3831 case CallingConv::X86_StdCall:
3832 case CallingConv::X86_FastCall:
3833 case CallingConv::X86_ThisCall:
3835 case CallingConv::Fast:
3836 case CallingConv::GHC:
3837 case CallingConv::HiPE:
3844 /// \brief Return true if the condition is an unsigned comparison operation.
3845 static bool isX86CCUnsigned(unsigned X86CC) {
3847 default: llvm_unreachable("Invalid integer condition!");
3848 case X86::COND_E: return true;
3849 case X86::COND_G: return false;
3850 case X86::COND_GE: return false;
3851 case X86::COND_L: return false;
3852 case X86::COND_LE: return false;
3853 case X86::COND_NE: return true;
3854 case X86::COND_B: return true;
3855 case X86::COND_A: return true;
3856 case X86::COND_BE: return true;
3857 case X86::COND_AE: return true;
3859 llvm_unreachable("covered switch fell through?!");
3862 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3863 /// specific condition code, returning the condition code and the LHS/RHS of the
3864 /// comparison to make.
3865 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3866 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3868 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3869 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3870 // X > -1 -> X == 0, jump !sign.
3871 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3872 return X86::COND_NS;
3874 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3875 // X < 0 -> X == 0, jump on sign.
3878 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3880 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3881 return X86::COND_LE;
3885 switch (SetCCOpcode) {
3886 default: llvm_unreachable("Invalid integer condition!");
3887 case ISD::SETEQ: return X86::COND_E;
3888 case ISD::SETGT: return X86::COND_G;
3889 case ISD::SETGE: return X86::COND_GE;
3890 case ISD::SETLT: return X86::COND_L;
3891 case ISD::SETLE: return X86::COND_LE;
3892 case ISD::SETNE: return X86::COND_NE;
3893 case ISD::SETULT: return X86::COND_B;
3894 case ISD::SETUGT: return X86::COND_A;
3895 case ISD::SETULE: return X86::COND_BE;
3896 case ISD::SETUGE: return X86::COND_AE;
3900 // First determine if it is required or is profitable to flip the operands.
3902 // If LHS is a foldable load, but RHS is not, flip the condition.
3903 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3904 !ISD::isNON_EXTLoad(RHS.getNode())) {
3905 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3906 std::swap(LHS, RHS);
3909 switch (SetCCOpcode) {
3915 std::swap(LHS, RHS);
3919 // On a floating point condition, the flags are set as follows:
3921 // 0 | 0 | 0 | X > Y
3922 // 0 | 0 | 1 | X < Y
3923 // 1 | 0 | 0 | X == Y
3924 // 1 | 1 | 1 | unordered
3925 switch (SetCCOpcode) {
3926 default: llvm_unreachable("Condcode should be pre-legalized away");
3928 case ISD::SETEQ: return X86::COND_E;
3929 case ISD::SETOLT: // flipped
3931 case ISD::SETGT: return X86::COND_A;
3932 case ISD::SETOLE: // flipped
3934 case ISD::SETGE: return X86::COND_AE;
3935 case ISD::SETUGT: // flipped
3937 case ISD::SETLT: return X86::COND_B;
3938 case ISD::SETUGE: // flipped
3940 case ISD::SETLE: return X86::COND_BE;
3942 case ISD::SETNE: return X86::COND_NE;
3943 case ISD::SETUO: return X86::COND_P;
3944 case ISD::SETO: return X86::COND_NP;
3946 case ISD::SETUNE: return X86::COND_INVALID;
3950 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3951 /// code. Current x86 isa includes the following FP cmov instructions:
3952 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3953 static bool hasFPCMov(unsigned X86CC) {
3969 /// isFPImmLegal - Returns true if the target can instruction select the
3970 /// specified FP immediate natively. If false, the legalizer will
3971 /// materialize the FP immediate as a load from a constant pool.
3972 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3973 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3974 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3980 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3981 ISD::LoadExtType ExtTy,
3983 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3984 // relocation target a movq or addq instruction: don't let the load shrink.
3985 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3986 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3987 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3988 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3992 /// \brief Returns true if it is beneficial to convert a load of a constant
3993 /// to just the constant itself.
3994 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3996 assert(Ty->isIntegerTy());
3998 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3999 if (BitSize == 0 || BitSize > 64)
4004 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4005 unsigned Index) const {
4006 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4009 return (Index == 0 || Index == ResVT.getVectorNumElements());
4012 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4013 // Speculate cttz only if we can directly use TZCNT.
4014 return Subtarget->hasBMI();
4017 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4018 // Speculate ctlz only if we can directly use LZCNT.
4019 return Subtarget->hasLZCNT();
4022 /// isUndefInRange - Return true if every element in Mask, beginning
4023 /// from position Pos and ending in Pos+Size is undef.
4024 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4025 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4031 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4032 /// the specified range (L, H].
4033 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4034 return (Val < 0) || (Val >= Low && Val < Hi);
4037 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4038 /// specified value.
4039 static bool isUndefOrEqual(int Val, int CmpVal) {
4040 return (Val < 0 || Val == CmpVal);
4043 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4044 /// from position Pos and ending in Pos+Size, falls within the specified
4045 /// sequential range (Low, Low+Size]. or is undef.
4046 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4047 unsigned Pos, unsigned Size, int Low) {
4048 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4049 if (!isUndefOrEqual(Mask[i], Low))
4054 /// isVEXTRACTIndex - Return true if the specified
4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4056 /// suitable for instruction that extract 128 or 256 bit vectors
4057 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4058 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4059 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4062 // The index should be aligned on a vecWidth-bit boundary.
4064 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4066 MVT VT = N->getSimpleValueType(0);
4067 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4068 bool Result = (Index * ElSize) % vecWidth == 0;
4073 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4074 /// operand specifies a subvector insert that is suitable for input to
4075 /// insertion of 128 or 256-bit subvectors
4076 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4077 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4078 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4080 // The index should be aligned on a vecWidth-bit boundary.
4082 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4084 MVT VT = N->getSimpleValueType(0);
4085 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4086 bool Result = (Index * ElSize) % vecWidth == 0;
4091 bool X86::isVINSERT128Index(SDNode *N) {
4092 return isVINSERTIndex(N, 128);
4095 bool X86::isVINSERT256Index(SDNode *N) {
4096 return isVINSERTIndex(N, 256);
4099 bool X86::isVEXTRACT128Index(SDNode *N) {
4100 return isVEXTRACTIndex(N, 128);
4103 bool X86::isVEXTRACT256Index(SDNode *N) {
4104 return isVEXTRACTIndex(N, 256);
4107 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4108 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4109 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4110 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4113 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4115 MVT VecVT = N->getOperand(0).getSimpleValueType();
4116 MVT ElVT = VecVT.getVectorElementType();
4118 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4119 return Index / NumElemsPerChunk;
4122 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4123 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4124 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4125 llvm_unreachable("Illegal insert subvector for VINSERT");
4128 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4130 MVT VecVT = N->getSimpleValueType(0);
4131 MVT ElVT = VecVT.getVectorElementType();
4133 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4134 return Index / NumElemsPerChunk;
4137 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 /// and VINSERTI128 instructions.
4140 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4141 return getExtractVEXTRACTImmediate(N, 128);
4144 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4145 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4146 /// and VINSERTI64x4 instructions.
4147 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4148 return getExtractVEXTRACTImmediate(N, 256);
4151 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4152 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4153 /// and VINSERTI128 instructions.
4154 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4155 return getInsertVINSERTImmediate(N, 128);
4158 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4159 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4160 /// and VINSERTI64x4 instructions.
4161 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4162 return getInsertVINSERTImmediate(N, 256);
4165 /// isZero - Returns true if Elt is a constant integer zero
4166 static bool isZero(SDValue V) {
4167 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4168 return C && C->isNullValue();
4171 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4173 bool X86::isZeroNode(SDValue Elt) {
4176 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4177 return CFP->getValueAPF().isPosZero();
4181 /// getZeroVector - Returns a vector of specified type with all zero elements.
4183 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4184 SelectionDAG &DAG, SDLoc dl) {
4185 assert(VT.isVector() && "Expected a vector type");
4187 // Always build SSE zero vectors as <4 x i32> bitcasted
4188 // to their dest type. This ensures they get CSE'd.
4190 if (VT.is128BitVector()) { // SSE
4191 if (Subtarget->hasSSE2()) { // SSE2
4192 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4193 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4195 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4196 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4198 } else if (VT.is256BitVector()) { // AVX
4199 if (Subtarget->hasInt256()) { // AVX2
4200 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4201 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4202 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4204 // 256-bit logic and arithmetic instructions in AVX are all
4205 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4206 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4207 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4208 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4210 } else if (VT.is512BitVector()) { // AVX-512
4211 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4212 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4213 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4214 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4215 } else if (VT.getScalarType() == MVT::i1) {
4217 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4218 && "Unexpected vector type");
4219 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4220 && "Unexpected vector type");
4221 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4222 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4223 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4225 llvm_unreachable("Unexpected vector type");
4227 return DAG.getBitcast(VT, Vec);
4230 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4231 SelectionDAG &DAG, SDLoc dl,
4232 unsigned vectorWidth) {
4233 assert((vectorWidth == 128 || vectorWidth == 256) &&
4234 "Unsupported vector width");
4235 EVT VT = Vec.getValueType();
4236 EVT ElVT = VT.getVectorElementType();
4237 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4238 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4239 VT.getVectorNumElements()/Factor);
4241 // Extract from UNDEF is UNDEF.
4242 if (Vec.getOpcode() == ISD::UNDEF)
4243 return DAG.getUNDEF(ResultVT);
4245 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4246 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4248 // This is the index of the first element of the vectorWidth-bit chunk
4250 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4253 // If the input is a buildvector just emit a smaller one.
4254 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4255 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4256 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4259 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4260 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4263 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4264 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4265 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4266 /// instructions or a simple subregister reference. Idx is an index in the
4267 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4268 /// lowering EXTRACT_VECTOR_ELT operations easier.
4269 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4270 SelectionDAG &DAG, SDLoc dl) {
4271 assert((Vec.getValueType().is256BitVector() ||
4272 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4273 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4276 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4277 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4278 SelectionDAG &DAG, SDLoc dl) {
4279 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4280 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4283 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4284 unsigned IdxVal, SelectionDAG &DAG,
4285 SDLoc dl, unsigned vectorWidth) {
4286 assert((vectorWidth == 128 || vectorWidth == 256) &&
4287 "Unsupported vector width");
4288 // Inserting UNDEF is Result
4289 if (Vec.getOpcode() == ISD::UNDEF)
4291 EVT VT = Vec.getValueType();
4292 EVT ElVT = VT.getVectorElementType();
4293 EVT ResultVT = Result.getValueType();
4295 // Insert the relevant vectorWidth bits.
4296 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4298 // This is the index of the first element of the vectorWidth-bit chunk
4300 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4303 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4304 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4307 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4308 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4309 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4310 /// simple superregister reference. Idx is an index in the 128 bits
4311 /// we want. It need not be aligned to a 128-bit boundary. That makes
4312 /// lowering INSERT_VECTOR_ELT operations easier.
4313 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314 SelectionDAG &DAG, SDLoc dl) {
4315 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4317 // For insertion into the zero index (low half) of a 256-bit vector, it is
4318 // more efficient to generate a blend with immediate instead of an insert*128.
4319 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4320 // extend the subvector to the size of the result vector. Make sure that
4321 // we are not recursing on that node by checking for undef here.
4322 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4323 Result.getOpcode() != ISD::UNDEF) {
4324 EVT ResultVT = Result.getValueType();
4325 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4326 SDValue Undef = DAG.getUNDEF(ResultVT);
4327 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4330 // The blend instruction, and therefore its mask, depend on the data type.
4331 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4332 if (ScalarType.isFloatingPoint()) {
4333 // Choose either vblendps (float) or vblendpd (double).
4334 unsigned ScalarSize = ScalarType.getSizeInBits();
4335 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4336 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4337 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4338 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4341 const X86Subtarget &Subtarget =
4342 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4344 // AVX2 is needed for 256-bit integer blend support.
4345 // Integers must be cast to 32-bit because there is only vpblendd;
4346 // vpblendw can't be used for this because it has a handicapped mask.
4348 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4349 // is still more efficient than using the wrong domain vinsertf128 that
4350 // will be created by InsertSubVector().
4351 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4353 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4354 Vec256 = DAG.getBitcast(CastVT, Vec256);
4355 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4356 return DAG.getBitcast(ResultVT, Vec256);
4359 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4362 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4363 SelectionDAG &DAG, SDLoc dl) {
4364 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4365 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4368 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4369 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4370 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4371 /// large BUILD_VECTORS.
4372 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4373 unsigned NumElems, SelectionDAG &DAG,
4375 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4376 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4379 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4380 unsigned NumElems, SelectionDAG &DAG,
4382 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4383 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4386 /// getOnesVector - Returns a vector of specified type with all bits set.
4387 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4388 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4389 /// Then bitcast to their original type, ensuring they get CSE'd.
4390 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4392 assert(VT.isVector() && "Expected a vector type");
4394 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4396 if (VT.is256BitVector()) {
4397 if (HasInt256) { // AVX2
4398 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4401 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4404 } else if (VT.is128BitVector()) {
4405 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4407 llvm_unreachable("Unexpected vector type");
4409 return DAG.getBitcast(VT, Vec);
4412 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4413 /// operation of specified width.
4414 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4416 unsigned NumElems = VT.getVectorNumElements();
4417 SmallVector<int, 8> Mask;
4418 Mask.push_back(NumElems);
4419 for (unsigned i = 1; i != NumElems; ++i)
4421 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4424 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4425 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4427 unsigned NumElems = VT.getVectorNumElements();
4428 SmallVector<int, 8> Mask;
4429 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4431 Mask.push_back(i + NumElems);
4433 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4436 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4437 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4439 unsigned NumElems = VT.getVectorNumElements();
4440 SmallVector<int, 8> Mask;
4441 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4442 Mask.push_back(i + Half);
4443 Mask.push_back(i + NumElems + Half);
4445 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4448 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4449 /// vector of zero or undef vector. This produces a shuffle where the low
4450 /// element of V2 is swizzled into the zero/undef vector, landing at element
4451 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4452 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4454 const X86Subtarget *Subtarget,
4455 SelectionDAG &DAG) {
4456 MVT VT = V2.getSimpleValueType();
4458 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4459 unsigned NumElems = VT.getVectorNumElements();
4460 SmallVector<int, 16> MaskVec;
4461 for (unsigned i = 0; i != NumElems; ++i)
4462 // If this is the insertion idx, put the low elt of V2 here.
4463 MaskVec.push_back(i == Idx ? NumElems : i);
4464 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4467 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4468 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4469 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4470 /// shuffles which use a single input multiple times, and in those cases it will
4471 /// adjust the mask to only have indices within that single input.
4472 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4473 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4474 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4475 unsigned NumElems = VT.getVectorNumElements();
4479 bool IsFakeUnary = false;
4480 switch(N->getOpcode()) {
4481 case X86ISD::BLENDI:
4482 ImmN = N->getOperand(N->getNumOperands()-1);
4483 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4486 ImmN = N->getOperand(N->getNumOperands()-1);
4487 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4488 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4490 case X86ISD::UNPCKH:
4491 DecodeUNPCKHMask(VT, Mask);
4492 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4494 case X86ISD::UNPCKL:
4495 DecodeUNPCKLMask(VT, Mask);
4496 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4498 case X86ISD::MOVHLPS:
4499 DecodeMOVHLPSMask(NumElems, Mask);
4500 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4502 case X86ISD::MOVLHPS:
4503 DecodeMOVLHPSMask(NumElems, Mask);
4504 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4506 case X86ISD::PALIGNR:
4507 ImmN = N->getOperand(N->getNumOperands()-1);
4508 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510 case X86ISD::PSHUFD:
4511 case X86ISD::VPERMILPI:
4512 ImmN = N->getOperand(N->getNumOperands()-1);
4513 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516 case X86ISD::PSHUFHW:
4517 ImmN = N->getOperand(N->getNumOperands()-1);
4518 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521 case X86ISD::PSHUFLW:
4522 ImmN = N->getOperand(N->getNumOperands()-1);
4523 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526 case X86ISD::PSHUFB: {
4528 SDValue MaskNode = N->getOperand(1);
4529 while (MaskNode->getOpcode() == ISD::BITCAST)
4530 MaskNode = MaskNode->getOperand(0);
4532 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4533 // If we have a build-vector, then things are easy.
4534 EVT VT = MaskNode.getValueType();
4535 assert(VT.isVector() &&
4536 "Can't produce a non-vector with a build_vector!");
4537 if (!VT.isInteger())
4540 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4542 SmallVector<uint64_t, 32> RawMask;
4543 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4544 SDValue Op = MaskNode->getOperand(i);
4545 if (Op->getOpcode() == ISD::UNDEF) {
4546 RawMask.push_back((uint64_t)SM_SentinelUndef);
4549 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4552 APInt MaskElement = CN->getAPIntValue();
4554 // We now have to decode the element which could be any integer size and
4555 // extract each byte of it.
4556 for (int j = 0; j < NumBytesPerElement; ++j) {
4557 // Note that this is x86 and so always little endian: the low byte is
4558 // the first byte of the mask.
4559 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4560 MaskElement = MaskElement.lshr(8);
4563 DecodePSHUFBMask(RawMask, Mask);
4567 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4571 SDValue Ptr = MaskLoad->getBasePtr();
4572 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4573 Ptr->getOpcode() == X86ISD::WrapperRIP)
4574 Ptr = Ptr->getOperand(0);
4576 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4577 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4580 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4581 DecodePSHUFBMask(C, Mask);
4589 case X86ISD::VPERMI:
4590 ImmN = N->getOperand(N->getNumOperands()-1);
4591 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4598 case X86ISD::VPERM2X128:
4599 ImmN = N->getOperand(N->getNumOperands()-1);
4600 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601 if (Mask.empty()) return false;
4602 // Mask only contains negative index if an element is zero.
4603 if (std::any_of(Mask.begin(), Mask.end(),
4604 [](int M){ return M == SM_SentinelZero; }))
4607 case X86ISD::MOVSLDUP:
4608 DecodeMOVSLDUPMask(VT, Mask);
4611 case X86ISD::MOVSHDUP:
4612 DecodeMOVSHDUPMask(VT, Mask);
4615 case X86ISD::MOVDDUP:
4616 DecodeMOVDDUPMask(VT, Mask);
4619 case X86ISD::MOVLHPD:
4620 case X86ISD::MOVLPD:
4621 case X86ISD::MOVLPS:
4622 // Not yet implemented
4624 default: llvm_unreachable("unknown target shuffle node");
4627 // If we have a fake unary shuffle, the shuffle mask is spread across two
4628 // inputs that are actually the same node. Re-map the mask to always point
4629 // into the first input.
4632 if (M >= (int)Mask.size())
4638 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4639 /// element of the result of the vector shuffle.
4640 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4643 return SDValue(); // Limit search depth.
4645 SDValue V = SDValue(N, 0);
4646 EVT VT = V.getValueType();
4647 unsigned Opcode = V.getOpcode();
4649 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4650 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4651 int Elt = SV->getMaskElt(Index);
4654 return DAG.getUNDEF(VT.getVectorElementType());
4656 unsigned NumElems = VT.getVectorNumElements();
4657 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4658 : SV->getOperand(1);
4659 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4662 // Recurse into target specific vector shuffles to find scalars.
4663 if (isTargetShuffle(Opcode)) {
4664 MVT ShufVT = V.getSimpleValueType();
4665 unsigned NumElems = ShufVT.getVectorNumElements();
4666 SmallVector<int, 16> ShuffleMask;
4669 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4672 int Elt = ShuffleMask[Index];
4674 return DAG.getUNDEF(ShufVT.getVectorElementType());
4676 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4678 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4682 // Actual nodes that may contain scalar elements
4683 if (Opcode == ISD::BITCAST) {
4684 V = V.getOperand(0);
4685 EVT SrcVT = V.getValueType();
4686 unsigned NumElems = VT.getVectorNumElements();
4688 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4692 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4693 return (Index == 0) ? V.getOperand(0)
4694 : DAG.getUNDEF(VT.getVectorElementType());
4696 if (V.getOpcode() == ISD::BUILD_VECTOR)
4697 return V.getOperand(Index);
4702 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4704 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4705 unsigned NumNonZero, unsigned NumZero,
4707 const X86Subtarget* Subtarget,
4708 const TargetLowering &TLI) {
4716 // SSE4.1 - use PINSRB to insert each byte directly.
4717 if (Subtarget->hasSSE41()) {
4718 for (unsigned i = 0; i < 16; ++i) {
4719 bool isNonZero = (NonZeros & (1 << i)) != 0;
4723 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4725 V = DAG.getUNDEF(MVT::v16i8);
4728 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4729 MVT::v16i8, V, Op.getOperand(i),
4730 DAG.getIntPtrConstant(i, dl));
4737 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4738 for (unsigned i = 0; i < 16; ++i) {
4739 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4740 if (ThisIsNonZero && First) {
4742 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4744 V = DAG.getUNDEF(MVT::v8i16);
4749 SDValue ThisElt, LastElt;
4750 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4751 if (LastIsNonZero) {
4752 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4753 MVT::i16, Op.getOperand(i-1));
4755 if (ThisIsNonZero) {
4756 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4757 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4758 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4760 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4764 if (ThisElt.getNode())
4765 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4766 DAG.getIntPtrConstant(i/2, dl));
4770 return DAG.getBitcast(MVT::v16i8, V);
4773 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4775 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4776 unsigned NumNonZero, unsigned NumZero,
4778 const X86Subtarget* Subtarget,
4779 const TargetLowering &TLI) {
4786 for (unsigned i = 0; i < 8; ++i) {
4787 bool isNonZero = (NonZeros & (1 << i)) != 0;
4791 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4793 V = DAG.getUNDEF(MVT::v8i16);
4796 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4797 MVT::v8i16, V, Op.getOperand(i),
4798 DAG.getIntPtrConstant(i, dl));
4805 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4806 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4807 const X86Subtarget *Subtarget,
4808 const TargetLowering &TLI) {
4809 // Find all zeroable elements.
4810 std::bitset<4> Zeroable;
4811 for (int i=0; i < 4; ++i) {
4812 SDValue Elt = Op->getOperand(i);
4813 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4815 assert(Zeroable.size() - Zeroable.count() > 1 &&
4816 "We expect at least two non-zero elements!");
4818 // We only know how to deal with build_vector nodes where elements are either
4819 // zeroable or extract_vector_elt with constant index.
4820 SDValue FirstNonZero;
4821 unsigned FirstNonZeroIdx;
4822 for (unsigned i=0; i < 4; ++i) {
4825 SDValue Elt = Op->getOperand(i);
4826 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4827 !isa<ConstantSDNode>(Elt.getOperand(1)))
4829 // Make sure that this node is extracting from a 128-bit vector.
4830 MVT VT = Elt.getOperand(0).getSimpleValueType();
4831 if (!VT.is128BitVector())
4833 if (!FirstNonZero.getNode()) {
4835 FirstNonZeroIdx = i;
4839 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4840 SDValue V1 = FirstNonZero.getOperand(0);
4841 MVT VT = V1.getSimpleValueType();
4843 // See if this build_vector can be lowered as a blend with zero.
4845 unsigned EltMaskIdx, EltIdx;
4847 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4848 if (Zeroable[EltIdx]) {
4849 // The zero vector will be on the right hand side.
4850 Mask[EltIdx] = EltIdx+4;
4854 Elt = Op->getOperand(EltIdx);
4855 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4856 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4857 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4859 Mask[EltIdx] = EltIdx;
4863 // Let the shuffle legalizer deal with blend operations.
4864 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4865 if (V1.getSimpleValueType() != VT)
4866 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4867 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4870 // See if we can lower this build_vector to a INSERTPS.
4871 if (!Subtarget->hasSSE41())
4874 SDValue V2 = Elt.getOperand(0);
4875 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4878 bool CanFold = true;
4879 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4883 SDValue Current = Op->getOperand(i);
4884 SDValue SrcVector = Current->getOperand(0);
4887 CanFold = SrcVector == V1 &&
4888 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4894 assert(V1.getNode() && "Expected at least two non-zero elements!");
4895 if (V1.getSimpleValueType() != MVT::v4f32)
4896 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4897 if (V2.getSimpleValueType() != MVT::v4f32)
4898 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4900 // Ok, we can emit an INSERTPS instruction.
4901 unsigned ZMask = Zeroable.to_ulong();
4903 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4904 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4906 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4907 DAG.getIntPtrConstant(InsertPSMask, DL));
4908 return DAG.getBitcast(VT, Result);
4911 /// Return a vector logical shift node.
4912 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4913 unsigned NumBits, SelectionDAG &DAG,
4914 const TargetLowering &TLI, SDLoc dl) {
4915 assert(VT.is128BitVector() && "Unknown type for VShift");
4916 MVT ShVT = MVT::v2i64;
4917 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4918 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4919 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4920 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4921 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4922 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4926 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4928 // Check if the scalar load can be widened into a vector load. And if
4929 // the address is "base + cst" see if the cst can be "absorbed" into
4930 // the shuffle mask.
4931 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4932 SDValue Ptr = LD->getBasePtr();
4933 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4935 EVT PVT = LD->getValueType(0);
4936 if (PVT != MVT::i32 && PVT != MVT::f32)
4941 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4942 FI = FINode->getIndex();
4944 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4945 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4946 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4947 Offset = Ptr.getConstantOperandVal(1);
4948 Ptr = Ptr.getOperand(0);
4953 // FIXME: 256-bit vector instructions don't require a strict alignment,
4954 // improve this code to support it better.
4955 unsigned RequiredAlign = VT.getSizeInBits()/8;
4956 SDValue Chain = LD->getChain();
4957 // Make sure the stack object alignment is at least 16 or 32.
4958 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4959 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4960 if (MFI->isFixedObjectIndex(FI)) {
4961 // Can't change the alignment. FIXME: It's possible to compute
4962 // the exact stack offset and reference FI + adjust offset instead.
4963 // If someone *really* cares about this. That's the way to implement it.
4966 MFI->setObjectAlignment(FI, RequiredAlign);
4970 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4971 // Ptr + (Offset & ~15).
4974 if ((Offset % RequiredAlign) & 3)
4976 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4979 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4980 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4983 int EltNo = (Offset - StartOffset) >> 2;
4984 unsigned NumElems = VT.getVectorNumElements();
4986 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4987 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4988 LD->getPointerInfo().getWithOffset(StartOffset),
4989 false, false, false, 0);
4991 SmallVector<int, 8> Mask(NumElems, EltNo);
4993 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4999 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5000 /// elements can be replaced by a single large load which has the same value as
5001 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5003 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5005 /// FIXME: we'd also like to handle the case where the last elements are zero
5006 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5007 /// There's even a handy isZeroNode for that purpose.
5008 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5009 SDLoc &DL, SelectionDAG &DAG,
5010 bool isAfterLegalize) {
5011 unsigned NumElems = Elts.size();
5013 LoadSDNode *LDBase = nullptr;
5014 unsigned LastLoadedElt = -1U;
5016 // For each element in the initializer, see if we've found a load or an undef.
5017 // If we don't find an initial load element, or later load elements are
5018 // non-consecutive, bail out.
5019 for (unsigned i = 0; i < NumElems; ++i) {
5020 SDValue Elt = Elts[i];
5021 // Look through a bitcast.
5022 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5023 Elt = Elt.getOperand(0);
5024 if (!Elt.getNode() ||
5025 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5028 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5030 LDBase = cast<LoadSDNode>(Elt.getNode());
5034 if (Elt.getOpcode() == ISD::UNDEF)
5037 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5038 EVT LdVT = Elt.getValueType();
5039 // Each loaded element must be the correct fractional portion of the
5040 // requested vector load.
5041 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5043 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5048 // If we have found an entire vector of loads and undefs, then return a large
5049 // load of the entire vector width starting at the base pointer. If we found
5050 // consecutive loads for the low half, generate a vzext_load node.
5051 if (LastLoadedElt == NumElems - 1) {
5052 assert(LDBase && "Did not find base load for merging consecutive loads");
5053 EVT EltVT = LDBase->getValueType(0);
5054 // Ensure that the input vector size for the merged loads matches the
5055 // cumulative size of the input elements.
5056 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5059 if (isAfterLegalize &&
5060 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5063 SDValue NewLd = SDValue();
5065 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5066 LDBase->getPointerInfo(), LDBase->isVolatile(),
5067 LDBase->isNonTemporal(), LDBase->isInvariant(),
5068 LDBase->getAlignment());
5070 if (LDBase->hasAnyUseOfValue(1)) {
5071 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5073 SDValue(NewLd.getNode(), 1));
5074 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5075 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5076 SDValue(NewLd.getNode(), 1));
5082 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5083 //of a v4i32 / v4f32. It's probably worth generalizing.
5084 EVT EltVT = VT.getVectorElementType();
5085 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5086 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5087 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5088 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5090 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5091 LDBase->getPointerInfo(),
5092 LDBase->getAlignment(),
5093 false/*isVolatile*/, true/*ReadMem*/,
5096 // Make sure the newly-created LOAD is in the same position as LDBase in
5097 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5098 // update uses of LDBase's output chain to use the TokenFactor.
5099 if (LDBase->hasAnyUseOfValue(1)) {
5100 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5101 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5102 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5103 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5104 SDValue(ResNode.getNode(), 1));
5107 return DAG.getBitcast(VT, ResNode);
5112 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5113 /// to generate a splat value for the following cases:
5114 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5115 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5116 /// a scalar load, or a constant.
5117 /// The VBROADCAST node is returned when a pattern is found,
5118 /// or SDValue() otherwise.
5119 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5120 SelectionDAG &DAG) {
5121 // VBROADCAST requires AVX.
5122 // TODO: Splats could be generated for non-AVX CPUs using SSE
5123 // instructions, but there's less potential gain for only 128-bit vectors.
5124 if (!Subtarget->hasAVX())
5127 MVT VT = Op.getSimpleValueType();
5130 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5131 "Unsupported vector type for broadcast.");
5136 switch (Op.getOpcode()) {
5138 // Unknown pattern found.
5141 case ISD::BUILD_VECTOR: {
5142 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5143 BitVector UndefElements;
5144 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5146 // We need a splat of a single value to use broadcast, and it doesn't
5147 // make any sense if the value is only in one element of the vector.
5148 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5152 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5153 Ld.getOpcode() == ISD::ConstantFP);
5155 // Make sure that all of the users of a non-constant load are from the
5156 // BUILD_VECTOR node.
5157 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5162 case ISD::VECTOR_SHUFFLE: {
5163 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5165 // Shuffles must have a splat mask where the first element is
5167 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5170 SDValue Sc = Op.getOperand(0);
5171 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5172 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5174 if (!Subtarget->hasInt256())
5177 // Use the register form of the broadcast instruction available on AVX2.
5178 if (VT.getSizeInBits() >= 256)
5179 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5180 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5183 Ld = Sc.getOperand(0);
5184 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5185 Ld.getOpcode() == ISD::ConstantFP);
5187 // The scalar_to_vector node and the suspected
5188 // load node must have exactly one user.
5189 // Constants may have multiple users.
5191 // AVX-512 has register version of the broadcast
5192 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5193 Ld.getValueType().getSizeInBits() >= 32;
5194 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5201 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5202 bool IsGE256 = (VT.getSizeInBits() >= 256);
5204 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5205 // instruction to save 8 or more bytes of constant pool data.
5206 // TODO: If multiple splats are generated to load the same constant,
5207 // it may be detrimental to overall size. There needs to be a way to detect
5208 // that condition to know if this is truly a size win.
5209 const Function *F = DAG.getMachineFunction().getFunction();
5210 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5212 // Handle broadcasting a single constant scalar from the constant pool
5214 // On Sandybridge (no AVX2), it is still better to load a constant vector
5215 // from the constant pool and not to broadcast it from a scalar.
5216 // But override that restriction when optimizing for size.
5217 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5218 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5219 EVT CVT = Ld.getValueType();
5220 assert(!CVT.isVector() && "Must not broadcast a vector type");
5222 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5223 // For size optimization, also splat v2f64 and v2i64, and for size opt
5224 // with AVX2, also splat i8 and i16.
5225 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5226 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5227 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5228 const Constant *C = nullptr;
5229 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5230 C = CI->getConstantIntValue();
5231 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5232 C = CF->getConstantFPValue();
5234 assert(C && "Invalid constant type");
5236 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5238 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5239 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5240 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5241 MachinePointerInfo::getConstantPool(),
5242 false, false, false, Alignment);
5244 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5248 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5250 // Handle AVX2 in-register broadcasts.
5251 if (!IsLoad && Subtarget->hasInt256() &&
5252 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5253 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5255 // The scalar source must be a normal load.
5259 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5260 (Subtarget->hasVLX() && ScalarSize == 64))
5261 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5263 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5264 // double since there is no vbroadcastsd xmm
5265 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5266 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5267 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270 // Unsupported broadcast.
5274 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5275 /// underlying vector and index.
5277 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5279 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5281 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5282 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5285 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5287 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5289 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5290 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5293 // In this case the vector is the extract_subvector expression and the index
5294 // is 2, as specified by the shuffle.
5295 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5296 SDValue ShuffleVec = SVOp->getOperand(0);
5297 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5298 assert(ShuffleVecVT.getVectorElementType() ==
5299 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5301 int ShuffleIdx = SVOp->getMaskElt(Idx);
5302 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5303 ExtractedFromVec = ShuffleVec;
5309 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5310 MVT VT = Op.getSimpleValueType();
5312 // Skip if insert_vec_elt is not supported.
5313 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5314 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5318 unsigned NumElems = Op.getNumOperands();
5322 SmallVector<unsigned, 4> InsertIndices;
5323 SmallVector<int, 8> Mask(NumElems, -1);
5325 for (unsigned i = 0; i != NumElems; ++i) {
5326 unsigned Opc = Op.getOperand(i).getOpcode();
5328 if (Opc == ISD::UNDEF)
5331 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5332 // Quit if more than 1 elements need inserting.
5333 if (InsertIndices.size() > 1)
5336 InsertIndices.push_back(i);
5340 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5341 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5342 // Quit if non-constant index.
5343 if (!isa<ConstantSDNode>(ExtIdx))
5345 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5347 // Quit if extracted from vector of different type.
5348 if (ExtractedFromVec.getValueType() != VT)
5351 if (!VecIn1.getNode())
5352 VecIn1 = ExtractedFromVec;
5353 else if (VecIn1 != ExtractedFromVec) {
5354 if (!VecIn2.getNode())
5355 VecIn2 = ExtractedFromVec;
5356 else if (VecIn2 != ExtractedFromVec)
5357 // Quit if more than 2 vectors to shuffle
5361 if (ExtractedFromVec == VecIn1)
5363 else if (ExtractedFromVec == VecIn2)
5364 Mask[i] = Idx + NumElems;
5367 if (!VecIn1.getNode())
5370 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5371 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5372 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5373 unsigned Idx = InsertIndices[i];
5374 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5375 DAG.getIntPtrConstant(Idx, DL));
5381 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5382 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5383 Op.getScalarValueSizeInBits() == 1 &&
5384 "Can not convert non-constant vector");
5385 uint64_t Immediate = 0;
5386 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5387 SDValue In = Op.getOperand(idx);
5388 if (In.getOpcode() != ISD::UNDEF)
5389 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5393 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5394 return DAG.getConstant(Immediate, dl, VT);
5396 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5398 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5400 MVT VT = Op.getSimpleValueType();
5401 assert((VT.getVectorElementType() == MVT::i1) &&
5402 "Unexpected type in LowerBUILD_VECTORvXi1!");
5405 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5406 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5407 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5408 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5411 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5412 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5413 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5414 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5417 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5418 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5419 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5420 return DAG.getBitcast(VT, Imm);
5421 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5422 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5423 DAG.getIntPtrConstant(0, dl));
5426 // Vector has one or more non-const elements
5427 uint64_t Immediate = 0;
5428 SmallVector<unsigned, 16> NonConstIdx;
5429 bool IsSplat = true;
5430 bool HasConstElts = false;
5432 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5433 SDValue In = Op.getOperand(idx);
5434 if (In.getOpcode() == ISD::UNDEF)
5436 if (!isa<ConstantSDNode>(In))
5437 NonConstIdx.push_back(idx);
5439 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5440 HasConstElts = true;
5444 else if (In != Op.getOperand(SplatIdx))
5448 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5450 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5451 DAG.getConstant(1, dl, VT),
5452 DAG.getConstant(0, dl, VT));
5454 // insert elements one by one
5458 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5459 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5461 else if (HasConstElts)
5462 Imm = DAG.getConstant(0, dl, VT);
5464 Imm = DAG.getUNDEF(VT);
5465 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5466 DstVec = DAG.getBitcast(VT, Imm);
5468 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5469 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5470 DAG.getIntPtrConstant(0, dl));
5473 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5474 unsigned InsertIdx = NonConstIdx[i];
5475 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5476 Op.getOperand(InsertIdx),
5477 DAG.getIntPtrConstant(InsertIdx, dl));
5482 /// \brief Return true if \p N implements a horizontal binop and return the
5483 /// operands for the horizontal binop into V0 and V1.
5485 /// This is a helper function of LowerToHorizontalOp().
5486 /// This function checks that the build_vector \p N in input implements a
5487 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5488 /// operation to match.
5489 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5490 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5491 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5494 /// This function only analyzes elements of \p N whose indices are
5495 /// in range [BaseIdx, LastIdx).
5496 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5498 unsigned BaseIdx, unsigned LastIdx,
5499 SDValue &V0, SDValue &V1) {
5500 EVT VT = N->getValueType(0);
5502 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5503 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5504 "Invalid Vector in input!");
5506 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5507 bool CanFold = true;
5508 unsigned ExpectedVExtractIdx = BaseIdx;
5509 unsigned NumElts = LastIdx - BaseIdx;
5510 V0 = DAG.getUNDEF(VT);
5511 V1 = DAG.getUNDEF(VT);
5513 // Check if N implements a horizontal binop.
5514 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5515 SDValue Op = N->getOperand(i + BaseIdx);
5518 if (Op->getOpcode() == ISD::UNDEF) {
5519 // Update the expected vector extract index.
5520 if (i * 2 == NumElts)
5521 ExpectedVExtractIdx = BaseIdx;
5522 ExpectedVExtractIdx += 2;
5526 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5531 SDValue Op0 = Op.getOperand(0);
5532 SDValue Op1 = Op.getOperand(1);
5534 // Try to match the following pattern:
5535 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5536 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5537 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5538 Op0.getOperand(0) == Op1.getOperand(0) &&
5539 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5540 isa<ConstantSDNode>(Op1.getOperand(1)));
5544 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5545 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5547 if (i * 2 < NumElts) {
5548 if (V0.getOpcode() == ISD::UNDEF) {
5549 V0 = Op0.getOperand(0);
5550 if (V0.getValueType() != VT)
5554 if (V1.getOpcode() == ISD::UNDEF) {
5555 V1 = Op0.getOperand(0);
5556 if (V1.getValueType() != VT)
5559 if (i * 2 == NumElts)
5560 ExpectedVExtractIdx = BaseIdx;
5563 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5564 if (I0 == ExpectedVExtractIdx)
5565 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5566 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5567 // Try to match the following dag sequence:
5568 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5569 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5573 ExpectedVExtractIdx += 2;
5579 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5580 /// a concat_vector.
5582 /// This is a helper function of LowerToHorizontalOp().
5583 /// This function expects two 256-bit vectors called V0 and V1.
5584 /// At first, each vector is split into two separate 128-bit vectors.
5585 /// Then, the resulting 128-bit vectors are used to implement two
5586 /// horizontal binary operations.
5588 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5590 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5591 /// the two new horizontal binop.
5592 /// When Mode is set, the first horizontal binop dag node would take as input
5593 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5594 /// horizontal binop dag node would take as input the lower 128-bit of V1
5595 /// and the upper 128-bit of V1.
5597 /// HADD V0_LO, V0_HI
5598 /// HADD V1_LO, V1_HI
5600 /// Otherwise, the first horizontal binop dag node takes as input the lower
5601 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5602 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5604 /// HADD V0_LO, V1_LO
5605 /// HADD V0_HI, V1_HI
5607 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5608 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5609 /// the upper 128-bits of the result.
5610 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5611 SDLoc DL, SelectionDAG &DAG,
5612 unsigned X86Opcode, bool Mode,
5613 bool isUndefLO, bool isUndefHI) {
5614 EVT VT = V0.getValueType();
5615 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5616 "Invalid nodes in input!");
5618 unsigned NumElts = VT.getVectorNumElements();
5619 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5620 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5621 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5622 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5623 EVT NewVT = V0_LO.getValueType();
5625 SDValue LO = DAG.getUNDEF(NewVT);
5626 SDValue HI = DAG.getUNDEF(NewVT);
5629 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5630 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5631 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5632 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5633 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5635 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5636 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5637 V1_LO->getOpcode() != ISD::UNDEF))
5638 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5640 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5641 V1_HI->getOpcode() != ISD::UNDEF))
5642 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5645 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5648 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5650 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5651 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5652 EVT VT = BV->getValueType(0);
5653 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5654 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5658 unsigned NumElts = VT.getVectorNumElements();
5659 SDValue InVec0 = DAG.getUNDEF(VT);
5660 SDValue InVec1 = DAG.getUNDEF(VT);
5662 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5663 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5665 // Odd-numbered elements in the input build vector are obtained from
5666 // adding two integer/float elements.
5667 // Even-numbered elements in the input build vector are obtained from
5668 // subtracting two integer/float elements.
5669 unsigned ExpectedOpcode = ISD::FSUB;
5670 unsigned NextExpectedOpcode = ISD::FADD;
5671 bool AddFound = false;
5672 bool SubFound = false;
5674 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5675 SDValue Op = BV->getOperand(i);
5677 // Skip 'undef' values.
5678 unsigned Opcode = Op.getOpcode();
5679 if (Opcode == ISD::UNDEF) {
5680 std::swap(ExpectedOpcode, NextExpectedOpcode);
5684 // Early exit if we found an unexpected opcode.
5685 if (Opcode != ExpectedOpcode)
5688 SDValue Op0 = Op.getOperand(0);
5689 SDValue Op1 = Op.getOperand(1);
5691 // Try to match the following pattern:
5692 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5693 // Early exit if we cannot match that sequence.
5694 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5695 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5696 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5697 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5698 Op0.getOperand(1) != Op1.getOperand(1))
5701 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5705 // We found a valid add/sub node. Update the information accordingly.
5711 // Update InVec0 and InVec1.
5712 if (InVec0.getOpcode() == ISD::UNDEF) {
5713 InVec0 = Op0.getOperand(0);
5714 if (InVec0.getValueType() != VT)
5717 if (InVec1.getOpcode() == ISD::UNDEF) {
5718 InVec1 = Op1.getOperand(0);
5719 if (InVec1.getValueType() != VT)
5723 // Make sure that operands in input to each add/sub node always
5724 // come from a same pair of vectors.
5725 if (InVec0 != Op0.getOperand(0)) {
5726 if (ExpectedOpcode == ISD::FSUB)
5729 // FADD is commutable. Try to commute the operands
5730 // and then test again.
5731 std::swap(Op0, Op1);
5732 if (InVec0 != Op0.getOperand(0))
5736 if (InVec1 != Op1.getOperand(0))
5739 // Update the pair of expected opcodes.
5740 std::swap(ExpectedOpcode, NextExpectedOpcode);
5743 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5744 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5745 InVec1.getOpcode() != ISD::UNDEF)
5746 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5751 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5752 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5753 const X86Subtarget *Subtarget,
5754 SelectionDAG &DAG) {
5755 EVT VT = BV->getValueType(0);
5756 unsigned NumElts = VT.getVectorNumElements();
5757 unsigned NumUndefsLO = 0;
5758 unsigned NumUndefsHI = 0;
5759 unsigned Half = NumElts/2;
5761 // Count the number of UNDEF operands in the build_vector in input.
5762 for (unsigned i = 0, e = Half; i != e; ++i)
5763 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5766 for (unsigned i = Half, e = NumElts; i != e; ++i)
5767 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5770 // Early exit if this is either a build_vector of all UNDEFs or all the
5771 // operands but one are UNDEF.
5772 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5776 SDValue InVec0, InVec1;
5777 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5778 // Try to match an SSE3 float HADD/HSUB.
5779 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5780 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5782 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5783 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5784 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5785 // Try to match an SSSE3 integer HADD/HSUB.
5786 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5787 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5789 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5790 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5793 if (!Subtarget->hasAVX())
5796 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5797 // Try to match an AVX horizontal add/sub of packed single/double
5798 // precision floating point values from 256-bit vectors.
5799 SDValue InVec2, InVec3;
5800 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5801 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5802 ((InVec0.getOpcode() == ISD::UNDEF ||
5803 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5804 ((InVec1.getOpcode() == ISD::UNDEF ||
5805 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5806 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5808 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5809 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5810 ((InVec0.getOpcode() == ISD::UNDEF ||
5811 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5812 ((InVec1.getOpcode() == ISD::UNDEF ||
5813 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5814 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5815 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5816 // Try to match an AVX2 horizontal add/sub of signed integers.
5817 SDValue InVec2, InVec3;
5819 bool CanFold = true;
5821 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5822 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5823 ((InVec0.getOpcode() == ISD::UNDEF ||
5824 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5825 ((InVec1.getOpcode() == ISD::UNDEF ||
5826 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5827 X86Opcode = X86ISD::HADD;
5828 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5829 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5830 ((InVec0.getOpcode() == ISD::UNDEF ||
5831 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5832 ((InVec1.getOpcode() == ISD::UNDEF ||
5833 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5834 X86Opcode = X86ISD::HSUB;
5839 // Fold this build_vector into a single horizontal add/sub.
5840 // Do this only if the target has AVX2.
5841 if (Subtarget->hasAVX2())
5842 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5844 // Do not try to expand this build_vector into a pair of horizontal
5845 // add/sub if we can emit a pair of scalar add/sub.
5846 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5849 // Convert this build_vector into a pair of horizontal binop followed by
5851 bool isUndefLO = NumUndefsLO == Half;
5852 bool isUndefHI = NumUndefsHI == Half;
5853 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5854 isUndefLO, isUndefHI);
5858 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5859 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5861 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5862 X86Opcode = X86ISD::HADD;
5863 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5864 X86Opcode = X86ISD::HSUB;
5865 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5866 X86Opcode = X86ISD::FHADD;
5867 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5868 X86Opcode = X86ISD::FHSUB;
5872 // Don't try to expand this build_vector into a pair of horizontal add/sub
5873 // if we can simply emit a pair of scalar add/sub.
5874 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5877 // Convert this build_vector into two horizontal add/sub followed by
5879 bool isUndefLO = NumUndefsLO == Half;
5880 bool isUndefHI = NumUndefsHI == Half;
5881 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5882 isUndefLO, isUndefHI);
5889 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5892 MVT VT = Op.getSimpleValueType();
5893 MVT ExtVT = VT.getVectorElementType();
5894 unsigned NumElems = Op.getNumOperands();
5896 // Generate vectors for predicate vectors.
5897 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5898 return LowerBUILD_VECTORvXi1(Op, DAG);
5900 // Vectors containing all zeros can be matched by pxor and xorps later
5901 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5902 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5903 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5904 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5907 return getZeroVector(VT, Subtarget, DAG, dl);
5910 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5911 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5912 // vpcmpeqd on 256-bit vectors.
5913 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5914 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5917 if (!VT.is512BitVector())
5918 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5921 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5922 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5924 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5925 return HorizontalOp;
5926 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5929 unsigned EVTBits = ExtVT.getSizeInBits();
5931 unsigned NumZero = 0;
5932 unsigned NumNonZero = 0;
5933 unsigned NonZeros = 0;
5934 bool IsAllConstants = true;
5935 SmallSet<SDValue, 8> Values;
5936 for (unsigned i = 0; i < NumElems; ++i) {
5937 SDValue Elt = Op.getOperand(i);
5938 if (Elt.getOpcode() == ISD::UNDEF)
5941 if (Elt.getOpcode() != ISD::Constant &&
5942 Elt.getOpcode() != ISD::ConstantFP)
5943 IsAllConstants = false;
5944 if (X86::isZeroNode(Elt))
5947 NonZeros |= (1 << i);
5952 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5953 if (NumNonZero == 0)
5954 return DAG.getUNDEF(VT);
5956 // Special case for single non-zero, non-undef, element.
5957 if (NumNonZero == 1) {
5958 unsigned Idx = countTrailingZeros(NonZeros);
5959 SDValue Item = Op.getOperand(Idx);
5961 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5962 // the value are obviously zero, truncate the value to i32 and do the
5963 // insertion that way. Only do this if the value is non-constant or if the
5964 // value is a constant being inserted into element 0. It is cheaper to do
5965 // a constant pool load than it is to do a movd + shuffle.
5966 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5967 (!IsAllConstants || Idx == 0)) {
5968 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5970 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5971 EVT VecVT = MVT::v4i32;
5973 // Truncate the value (which may itself be a constant) to i32, and
5974 // convert it to a vector with movd (S2V+shuffle to zero extend).
5975 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5976 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5977 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5978 Item, Idx * 2, true, Subtarget, DAG));
5982 // If we have a constant or non-constant insertion into the low element of
5983 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5984 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5985 // depending on what the source datatype is.
5988 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5990 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5991 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5992 if (VT.is512BitVector()) {
5993 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5994 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5995 Item, DAG.getIntPtrConstant(0, dl));
5997 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5998 "Expected an SSE value type!");
5999 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6001 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6004 // We can't directly insert an i8 or i16 into a vector, so zero extend
6006 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6007 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6008 if (VT.is256BitVector()) {
6009 if (Subtarget->hasAVX()) {
6010 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6011 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6013 // Without AVX, we need to extend to a 128-bit vector and then
6014 // insert into the 256-bit vector.
6015 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6016 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6017 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6020 assert(VT.is128BitVector() && "Expected an SSE value type!");
6021 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6022 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6024 return DAG.getBitcast(VT, Item);
6028 // Is it a vector logical left shift?
6029 if (NumElems == 2 && Idx == 1 &&
6030 X86::isZeroNode(Op.getOperand(0)) &&
6031 !X86::isZeroNode(Op.getOperand(1))) {
6032 unsigned NumBits = VT.getSizeInBits();
6033 return getVShift(true, VT,
6034 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6035 VT, Op.getOperand(1)),
6036 NumBits/2, DAG, *this, dl);
6039 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6042 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6043 // is a non-constant being inserted into an element other than the low one,
6044 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6045 // movd/movss) to move this into the low element, then shuffle it into
6047 if (EVTBits == 32) {
6048 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6053 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6054 if (Values.size() == 1) {
6055 if (EVTBits == 32) {
6056 // Instead of a shuffle like this:
6057 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6058 // Check if it's possible to issue this instead.
6059 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6060 unsigned Idx = countTrailingZeros(NonZeros);
6061 SDValue Item = Op.getOperand(Idx);
6062 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6063 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6068 // A vector full of immediates; various special cases are already
6069 // handled, so this is best done with a single constant-pool load.
6073 // For AVX-length vectors, see if we can use a vector load to get all of the
6074 // elements, otherwise build the individual 128-bit pieces and use
6075 // shuffles to put them in place.
6076 if (VT.is256BitVector() || VT.is512BitVector()) {
6077 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6079 // Check for a build vector of consecutive loads.
6080 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6083 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6085 // Build both the lower and upper subvector.
6086 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6087 makeArrayRef(&V[0], NumElems/2));
6088 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6089 makeArrayRef(&V[NumElems / 2], NumElems/2));
6091 // Recreate the wider vector with the lower and upper part.
6092 if (VT.is256BitVector())
6093 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6094 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6097 // Let legalizer expand 2-wide build_vectors.
6098 if (EVTBits == 64) {
6099 if (NumNonZero == 1) {
6100 // One half is zero or undef.
6101 unsigned Idx = countTrailingZeros(NonZeros);
6102 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6103 Op.getOperand(Idx));
6104 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6109 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6110 if (EVTBits == 8 && NumElems == 16)
6111 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6115 if (EVTBits == 16 && NumElems == 8)
6116 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6120 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6121 if (EVTBits == 32 && NumElems == 4)
6122 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6125 // If element VT is == 32 bits, turn it into a number of shuffles.
6126 SmallVector<SDValue, 8> V(NumElems);
6127 if (NumElems == 4 && NumZero > 0) {
6128 for (unsigned i = 0; i < 4; ++i) {
6129 bool isZero = !(NonZeros & (1 << i));
6131 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6133 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6136 for (unsigned i = 0; i < 2; ++i) {
6137 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6140 V[i] = V[i*2]; // Must be a zero vector.
6143 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6146 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6149 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6154 bool Reverse1 = (NonZeros & 0x3) == 2;
6155 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6159 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6160 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6162 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6165 if (Values.size() > 1 && VT.is128BitVector()) {
6166 // Check for a build vector of consecutive loads.
6167 for (unsigned i = 0; i < NumElems; ++i)
6168 V[i] = Op.getOperand(i);
6170 // Check for elements which are consecutive loads.
6171 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6174 // Check for a build vector from mostly shuffle plus few inserting.
6175 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6178 // For SSE 4.1, use insertps to put the high elements into the low element.
6179 if (Subtarget->hasSSE41()) {
6181 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6182 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6184 Result = DAG.getUNDEF(VT);
6186 for (unsigned i = 1; i < NumElems; ++i) {
6187 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6188 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6189 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6194 // Otherwise, expand into a number of unpckl*, start by extending each of
6195 // our (non-undef) elements to the full vector width with the element in the
6196 // bottom slot of the vector (which generates no code for SSE).
6197 for (unsigned i = 0; i < NumElems; ++i) {
6198 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6199 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6201 V[i] = DAG.getUNDEF(VT);
6204 // Next, we iteratively mix elements, e.g. for v4f32:
6205 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6206 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6207 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6208 unsigned EltStride = NumElems >> 1;
6209 while (EltStride != 0) {
6210 for (unsigned i = 0; i < EltStride; ++i) {
6211 // If V[i+EltStride] is undef and this is the first round of mixing,
6212 // then it is safe to just drop this shuffle: V[i] is already in the
6213 // right place, the one element (since it's the first round) being
6214 // inserted as undef can be dropped. This isn't safe for successive
6215 // rounds because they will permute elements within both vectors.
6216 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6217 EltStride == NumElems/2)
6220 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6229 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6230 // to create 256-bit vectors from two other 128-bit ones.
6231 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6233 MVT ResVT = Op.getSimpleValueType();
6235 assert((ResVT.is256BitVector() ||
6236 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6238 SDValue V1 = Op.getOperand(0);
6239 SDValue V2 = Op.getOperand(1);
6240 unsigned NumElems = ResVT.getVectorNumElements();
6241 if (ResVT.is256BitVector())
6242 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6244 if (Op.getNumOperands() == 4) {
6245 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6246 ResVT.getVectorNumElements()/2);
6247 SDValue V3 = Op.getOperand(2);
6248 SDValue V4 = Op.getOperand(3);
6249 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6250 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6252 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6255 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6256 const X86Subtarget *Subtarget,
6257 SelectionDAG & DAG) {
6259 MVT ResVT = Op.getSimpleValueType();
6260 unsigned NumOfOperands = Op.getNumOperands();
6262 assert(isPowerOf2_32(NumOfOperands) &&
6263 "Unexpected number of operands in CONCAT_VECTORS");
6265 if (NumOfOperands > 2) {
6266 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6267 ResVT.getVectorNumElements()/2);
6268 SmallVector<SDValue, 2> Ops;
6269 for (unsigned i = 0; i < NumOfOperands/2; i++)
6270 Ops.push_back(Op.getOperand(i));
6271 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6273 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6274 Ops.push_back(Op.getOperand(i));
6275 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6276 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6279 SDValue V1 = Op.getOperand(0);
6280 SDValue V2 = Op.getOperand(1);
6281 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6282 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6284 if (IsZeroV1 && IsZeroV2)
6285 return getZeroVector(ResVT, Subtarget, DAG, dl);
6287 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6288 SDValue Undef = DAG.getUNDEF(ResVT);
6289 unsigned NumElems = ResVT.getVectorNumElements();
6290 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6292 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6293 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6297 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6298 // Zero the upper bits of V1
6299 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6300 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6303 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6306 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6307 const X86Subtarget *Subtarget,
6308 SelectionDAG &DAG) {
6309 MVT VT = Op.getSimpleValueType();
6310 if (VT.getVectorElementType() == MVT::i1)
6311 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6313 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6314 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6315 Op.getNumOperands() == 4)));
6317 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6318 // from two other 128-bit ones.
6320 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6321 return LowerAVXCONCAT_VECTORS(Op, DAG);
6325 //===----------------------------------------------------------------------===//
6326 // Vector shuffle lowering
6328 // This is an experimental code path for lowering vector shuffles on x86. It is
6329 // designed to handle arbitrary vector shuffles and blends, gracefully
6330 // degrading performance as necessary. It works hard to recognize idiomatic
6331 // shuffles and lower them to optimal instruction patterns without leaving
6332 // a framework that allows reasonably efficient handling of all vector shuffle
6334 //===----------------------------------------------------------------------===//
6336 /// \brief Tiny helper function to identify a no-op mask.
6338 /// This is a somewhat boring predicate function. It checks whether the mask
6339 /// array input, which is assumed to be a single-input shuffle mask of the kind
6340 /// used by the X86 shuffle instructions (not a fully general
6341 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6342 /// in-place shuffle are 'no-op's.
6343 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6344 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6345 if (Mask[i] != -1 && Mask[i] != i)
6350 /// \brief Helper function to classify a mask as a single-input mask.
6352 /// This isn't a generic single-input test because in the vector shuffle
6353 /// lowering we canonicalize single inputs to be the first input operand. This
6354 /// means we can more quickly test for a single input by only checking whether
6355 /// an input from the second operand exists. We also assume that the size of
6356 /// mask corresponds to the size of the input vectors which isn't true in the
6357 /// fully general case.
6358 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6360 if (M >= (int)Mask.size())
6365 /// \brief Test whether there are elements crossing 128-bit lanes in this
6368 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6369 /// and we routinely test for these.
6370 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6371 int LaneSize = 128 / VT.getScalarSizeInBits();
6372 int Size = Mask.size();
6373 for (int i = 0; i < Size; ++i)
6374 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6379 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6381 /// This checks a shuffle mask to see if it is performing the same
6382 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6383 /// that it is also not lane-crossing. It may however involve a blend from the
6384 /// same lane of a second vector.
6386 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6387 /// non-trivial to compute in the face of undef lanes. The representation is
6388 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6389 /// entries from both V1 and V2 inputs to the wider mask.
6391 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6392 SmallVectorImpl<int> &RepeatedMask) {
6393 int LaneSize = 128 / VT.getScalarSizeInBits();
6394 RepeatedMask.resize(LaneSize, -1);
6395 int Size = Mask.size();
6396 for (int i = 0; i < Size; ++i) {
6399 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6400 // This entry crosses lanes, so there is no way to model this shuffle.
6403 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6404 if (RepeatedMask[i % LaneSize] == -1)
6405 // This is the first non-undef entry in this slot of a 128-bit lane.
6406 RepeatedMask[i % LaneSize] =
6407 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6408 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6409 // Found a mismatch with the repeated mask.
6415 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6418 /// This is a fast way to test a shuffle mask against a fixed pattern:
6420 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6422 /// It returns true if the mask is exactly as wide as the argument list, and
6423 /// each element of the mask is either -1 (signifying undef) or the value given
6424 /// in the argument.
6425 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6426 ArrayRef<int> ExpectedMask) {
6427 if (Mask.size() != ExpectedMask.size())
6430 int Size = Mask.size();
6432 // If the values are build vectors, we can look through them to find
6433 // equivalent inputs that make the shuffles equivalent.
6434 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6435 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6437 for (int i = 0; i < Size; ++i)
6438 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6439 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6440 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6441 if (!MaskBV || !ExpectedBV ||
6442 MaskBV->getOperand(Mask[i] % Size) !=
6443 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6450 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6452 /// This helper function produces an 8-bit shuffle immediate corresponding to
6453 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6454 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6457 /// NB: We rely heavily on "undef" masks preserving the input lane.
6458 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6459 SelectionDAG &DAG) {
6460 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6461 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6462 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6463 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6464 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6467 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6468 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6469 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6470 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6471 return DAG.getConstant(Imm, DL, MVT::i8);
6474 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6476 /// This is used as a fallback approach when first class blend instructions are
6477 /// unavailable. Currently it is only suitable for integer vectors, but could
6478 /// be generalized for floating point vectors if desirable.
6479 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6480 SDValue V2, ArrayRef<int> Mask,
6481 SelectionDAG &DAG) {
6482 assert(VT.isInteger() && "Only supports integer vector types!");
6483 MVT EltVT = VT.getScalarType();
6484 int NumEltBits = EltVT.getSizeInBits();
6485 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6486 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6488 SmallVector<SDValue, 16> MaskOps;
6489 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6490 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6491 return SDValue(); // Shuffled input!
6492 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6495 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6496 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6497 // We have to cast V2 around.
6498 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6499 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6500 DAG.getBitcast(MaskVT, V1Mask),
6501 DAG.getBitcast(MaskVT, V2)));
6502 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6505 /// \brief Try to emit a blend instruction for a shuffle.
6507 /// This doesn't do any checks for the availability of instructions for blending
6508 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6509 /// be matched in the backend with the type given. What it does check for is
6510 /// that the shuffle mask is in fact a blend.
6511 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6512 SDValue V2, ArrayRef<int> Mask,
6513 const X86Subtarget *Subtarget,
6514 SelectionDAG &DAG) {
6515 unsigned BlendMask = 0;
6516 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6517 if (Mask[i] >= Size) {
6518 if (Mask[i] != i + Size)
6519 return SDValue(); // Shuffled V2 input!
6520 BlendMask |= 1u << i;
6523 if (Mask[i] >= 0 && Mask[i] != i)
6524 return SDValue(); // Shuffled V1 input!
6526 switch (VT.SimpleTy) {
6531 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6532 DAG.getConstant(BlendMask, DL, MVT::i8));
6536 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6540 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6541 // that instruction.
6542 if (Subtarget->hasAVX2()) {
6543 // Scale the blend by the number of 32-bit dwords per element.
6544 int Scale = VT.getScalarSizeInBits() / 32;
6546 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6547 if (Mask[i] >= Size)
6548 for (int j = 0; j < Scale; ++j)
6549 BlendMask |= 1u << (i * Scale + j);
6551 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6552 V1 = DAG.getBitcast(BlendVT, V1);
6553 V2 = DAG.getBitcast(BlendVT, V2);
6554 return DAG.getBitcast(
6555 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6556 DAG.getConstant(BlendMask, DL, MVT::i8)));
6560 // For integer shuffles we need to expand the mask and cast the inputs to
6561 // v8i16s prior to blending.
6562 int Scale = 8 / VT.getVectorNumElements();
6564 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6565 if (Mask[i] >= Size)
6566 for (int j = 0; j < Scale; ++j)
6567 BlendMask |= 1u << (i * Scale + j);
6569 V1 = DAG.getBitcast(MVT::v8i16, V1);
6570 V2 = DAG.getBitcast(MVT::v8i16, V2);
6571 return DAG.getBitcast(VT,
6572 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6573 DAG.getConstant(BlendMask, DL, MVT::i8)));
6577 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6578 SmallVector<int, 8> RepeatedMask;
6579 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6580 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6581 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6583 for (int i = 0; i < 8; ++i)
6584 if (RepeatedMask[i] >= 16)
6585 BlendMask |= 1u << i;
6586 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6587 DAG.getConstant(BlendMask, DL, MVT::i8));
6593 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6594 "256-bit byte-blends require AVX2 support!");
6596 // Scale the blend by the number of bytes per element.
6597 int Scale = VT.getScalarSizeInBits() / 8;
6599 // This form of blend is always done on bytes. Compute the byte vector
6601 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6603 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6604 // mix of LLVM's code generator and the x86 backend. We tell the code
6605 // generator that boolean values in the elements of an x86 vector register
6606 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6607 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6608 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6609 // of the element (the remaining are ignored) and 0 in that high bit would
6610 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6611 // the LLVM model for boolean values in vector elements gets the relevant
6612 // bit set, it is set backwards and over constrained relative to x86's
6614 SmallVector<SDValue, 32> VSELECTMask;
6615 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6616 for (int j = 0; j < Scale; ++j)
6617 VSELECTMask.push_back(
6618 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6619 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6622 V1 = DAG.getBitcast(BlendVT, V1);
6623 V2 = DAG.getBitcast(BlendVT, V2);
6624 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6625 DAG.getNode(ISD::BUILD_VECTOR, DL,
6626 BlendVT, VSELECTMask),
6631 llvm_unreachable("Not a supported integer vector type!");
6635 /// \brief Try to lower as a blend of elements from two inputs followed by
6636 /// a single-input permutation.
6638 /// This matches the pattern where we can blend elements from two inputs and
6639 /// then reduce the shuffle to a single-input permutation.
6640 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6643 SelectionDAG &DAG) {
6644 // We build up the blend mask while checking whether a blend is a viable way
6645 // to reduce the shuffle.
6646 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6647 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6649 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6653 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6655 if (BlendMask[Mask[i] % Size] == -1)
6656 BlendMask[Mask[i] % Size] = Mask[i];
6657 else if (BlendMask[Mask[i] % Size] != Mask[i])
6658 return SDValue(); // Can't blend in the needed input!
6660 PermuteMask[i] = Mask[i] % Size;
6663 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6664 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6667 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6668 /// blends and permutes.
6670 /// This matches the extremely common pattern for handling combined
6671 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6672 /// operations. It will try to pick the best arrangement of shuffles and
6674 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6678 SelectionDAG &DAG) {
6679 // Shuffle the input elements into the desired positions in V1 and V2 and
6680 // blend them together.
6681 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6682 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6683 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6684 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6685 if (Mask[i] >= 0 && Mask[i] < Size) {
6686 V1Mask[i] = Mask[i];
6688 } else if (Mask[i] >= Size) {
6689 V2Mask[i] = Mask[i] - Size;
6690 BlendMask[i] = i + Size;
6693 // Try to lower with the simpler initial blend strategy unless one of the
6694 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6695 // shuffle may be able to fold with a load or other benefit. However, when
6696 // we'll have to do 2x as many shuffles in order to achieve this, blending
6697 // first is a better strategy.
6698 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6699 if (SDValue BlendPerm =
6700 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6703 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6704 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6705 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6708 /// \brief Try to lower a vector shuffle as a byte rotation.
6710 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6711 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6712 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6713 /// try to generically lower a vector shuffle through such an pattern. It
6714 /// does not check for the profitability of lowering either as PALIGNR or
6715 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6716 /// This matches shuffle vectors that look like:
6718 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6720 /// Essentially it concatenates V1 and V2, shifts right by some number of
6721 /// elements, and takes the low elements as the result. Note that while this is
6722 /// specified as a *right shift* because x86 is little-endian, it is a *left
6723 /// rotate* of the vector lanes.
6724 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6727 const X86Subtarget *Subtarget,
6728 SelectionDAG &DAG) {
6729 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6731 int NumElts = Mask.size();
6732 int NumLanes = VT.getSizeInBits() / 128;
6733 int NumLaneElts = NumElts / NumLanes;
6735 // We need to detect various ways of spelling a rotation:
6736 // [11, 12, 13, 14, 15, 0, 1, 2]
6737 // [-1, 12, 13, 14, -1, -1, 1, -1]
6738 // [-1, -1, -1, -1, -1, -1, 1, 2]
6739 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6740 // [-1, 4, 5, 6, -1, -1, 9, -1]
6741 // [-1, 4, 5, 6, -1, -1, -1, -1]
6744 for (int l = 0; l < NumElts; l += NumLaneElts) {
6745 for (int i = 0; i < NumLaneElts; ++i) {
6746 if (Mask[l + i] == -1)
6748 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6750 // Get the mod-Size index and lane correct it.
6751 int LaneIdx = (Mask[l + i] % NumElts) - l;
6752 // Make sure it was in this lane.
6753 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6756 // Determine where a rotated vector would have started.
6757 int StartIdx = i - LaneIdx;
6759 // The identity rotation isn't interesting, stop.
6762 // If we found the tail of a vector the rotation must be the missing
6763 // front. If we found the head of a vector, it must be how much of the
6765 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6768 Rotation = CandidateRotation;
6769 else if (Rotation != CandidateRotation)
6770 // The rotations don't match, so we can't match this mask.
6773 // Compute which value this mask is pointing at.
6774 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6776 // Compute which of the two target values this index should be assigned
6777 // to. This reflects whether the high elements are remaining or the low
6778 // elements are remaining.
6779 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6781 // Either set up this value if we've not encountered it before, or check
6782 // that it remains consistent.
6785 else if (TargetV != MaskV)
6786 // This may be a rotation, but it pulls from the inputs in some
6787 // unsupported interleaving.
6792 // Check that we successfully analyzed the mask, and normalize the results.
6793 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6794 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6800 // The actual rotate instruction rotates bytes, so we need to scale the
6801 // rotation based on how many bytes are in the vector lane.
6802 int Scale = 16 / NumLaneElts;
6804 // SSSE3 targets can use the palignr instruction.
6805 if (Subtarget->hasSSSE3()) {
6806 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6807 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6808 Lo = DAG.getBitcast(AlignVT, Lo);
6809 Hi = DAG.getBitcast(AlignVT, Hi);
6811 return DAG.getBitcast(
6812 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6813 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6816 assert(VT.getSizeInBits() == 128 &&
6817 "Rotate-based lowering only supports 128-bit lowering!");
6818 assert(Mask.size() <= 16 &&
6819 "Can shuffle at most 16 bytes in a 128-bit vector!");
6821 // Default SSE2 implementation
6822 int LoByteShift = 16 - Rotation * Scale;
6823 int HiByteShift = Rotation * Scale;
6825 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6826 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6827 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6829 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6830 DAG.getConstant(LoByteShift, DL, MVT::i8));
6831 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6832 DAG.getConstant(HiByteShift, DL, MVT::i8));
6833 return DAG.getBitcast(VT,
6834 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6837 /// \brief Compute whether each element of a shuffle is zeroable.
6839 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6840 /// Either it is an undef element in the shuffle mask, the element of the input
6841 /// referenced is undef, or the element of the input referenced is known to be
6842 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6843 /// as many lanes with this technique as possible to simplify the remaining
6845 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6846 SDValue V1, SDValue V2) {
6847 SmallBitVector Zeroable(Mask.size(), false);
6849 while (V1.getOpcode() == ISD::BITCAST)
6850 V1 = V1->getOperand(0);
6851 while (V2.getOpcode() == ISD::BITCAST)
6852 V2 = V2->getOperand(0);
6854 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6855 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6857 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6859 // Handle the easy cases.
6860 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6865 // If this is an index into a build_vector node (which has the same number
6866 // of elements), dig out the input value and use it.
6867 SDValue V = M < Size ? V1 : V2;
6868 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6871 SDValue Input = V.getOperand(M % Size);
6872 // The UNDEF opcode check really should be dead code here, but not quite
6873 // worth asserting on (it isn't invalid, just unexpected).
6874 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6881 /// \brief Try to emit a bitmask instruction for a shuffle.
6883 /// This handles cases where we can model a blend exactly as a bitmask due to
6884 /// one of the inputs being zeroable.
6885 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6886 SDValue V2, ArrayRef<int> Mask,
6887 SelectionDAG &DAG) {
6888 MVT EltVT = VT.getScalarType();
6889 int NumEltBits = EltVT.getSizeInBits();
6890 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6891 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6892 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6894 if (EltVT.isFloatingPoint()) {
6895 Zero = DAG.getBitcast(EltVT, Zero);
6896 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6898 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6899 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6901 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6904 if (Mask[i] % Size != i)
6905 return SDValue(); // Not a blend.
6907 V = Mask[i] < Size ? V1 : V2;
6908 else if (V != (Mask[i] < Size ? V1 : V2))
6909 return SDValue(); // Can only let one input through the mask.
6911 VMaskOps[i] = AllOnes;
6914 return SDValue(); // No non-zeroable elements!
6916 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6917 V = DAG.getNode(VT.isFloatingPoint()
6918 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6923 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6925 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6926 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6927 /// matches elements from one of the input vectors shuffled to the left or
6928 /// right with zeroable elements 'shifted in'. It handles both the strictly
6929 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6932 /// PSHL : (little-endian) left bit shift.
6933 /// [ zz, 0, zz, 2 ]
6934 /// [ -1, 4, zz, -1 ]
6935 /// PSRL : (little-endian) right bit shift.
6937 /// [ -1, -1, 7, zz]
6938 /// PSLLDQ : (little-endian) left byte shift
6939 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6940 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6941 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6942 /// PSRLDQ : (little-endian) right byte shift
6943 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6944 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6945 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6946 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6947 SDValue V2, ArrayRef<int> Mask,
6948 SelectionDAG &DAG) {
6949 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6951 int Size = Mask.size();
6952 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6954 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6955 for (int i = 0; i < Size; i += Scale)
6956 for (int j = 0; j < Shift; ++j)
6957 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6963 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6964 for (int i = 0; i != Size; i += Scale) {
6965 unsigned Pos = Left ? i + Shift : i;
6966 unsigned Low = Left ? i : i + Shift;
6967 unsigned Len = Scale - Shift;
6968 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6969 Low + (V == V1 ? 0 : Size)))
6973 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6974 bool ByteShift = ShiftEltBits > 64;
6975 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6976 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6977 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6979 // Normalize the scale for byte shifts to still produce an i64 element
6981 Scale = ByteShift ? Scale / 2 : Scale;
6983 // We need to round trip through the appropriate type for the shift.
6984 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6985 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6986 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6987 "Illegal integer vector type");
6988 V = DAG.getBitcast(ShiftVT, V);
6990 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6991 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6992 return DAG.getBitcast(VT, V);
6995 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6996 // keep doubling the size of the integer elements up to that. We can
6997 // then shift the elements of the integer vector by whole multiples of
6998 // their width within the elements of the larger integer vector. Test each
6999 // multiple to see if we can find a match with the moved element indices
7000 // and that the shifted in elements are all zeroable.
7001 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7002 for (int Shift = 1; Shift != Scale; ++Shift)
7003 for (bool Left : {true, false})
7004 if (CheckZeros(Shift, Scale, Left))
7005 for (SDValue V : {V1, V2})
7006 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7013 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7014 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7015 SDValue V2, ArrayRef<int> Mask,
7016 SelectionDAG &DAG) {
7017 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7018 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7020 int Size = Mask.size();
7021 int HalfSize = Size / 2;
7022 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7024 // Upper half must be undefined.
7025 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7028 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7029 // Remainder of lower half result is zero and upper half is all undef.
7030 auto LowerAsEXTRQ = [&]() {
7031 // Determine the extraction length from the part of the
7032 // lower half that isn't zeroable.
7034 for (; Len >= 0; --Len)
7035 if (!Zeroable[Len - 1])
7037 assert(Len > 0 && "Zeroable shuffle mask");
7039 // Attempt to match first Len sequential elements from the lower half.
7042 for (int i = 0; i != Len; ++i) {
7046 SDValue &V = (M < Size ? V1 : V2);
7049 // All mask elements must be in the lower half.
7053 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7064 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7065 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7066 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7067 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7068 DAG.getConstant(BitLen, DL, MVT::i8),
7069 DAG.getConstant(BitIdx, DL, MVT::i8));
7072 if (SDValue ExtrQ = LowerAsEXTRQ())
7075 // INSERTQ: Extract lowest Len elements from lower half of second source and
7076 // insert over first source, starting at Idx.
7077 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7078 auto LowerAsInsertQ = [&]() {
7079 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7082 // Attempt to match first source from mask before insertion point.
7083 if (isUndefInRange(Mask, 0, Idx)) {
7085 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7087 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7093 // Extend the extraction length looking to match both the insertion of
7094 // the second source and the remaining elements of the first.
7095 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7100 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7102 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7108 // Match the remaining elements of the lower half.
7109 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7111 } else if ((!Base || (Base == V1)) &&
7112 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7114 } else if ((!Base || (Base == V2)) &&
7115 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7122 // We may not have a base (first source) - this can safely be undefined.
7124 Base = DAG.getUNDEF(VT);
7126 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7127 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7128 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7129 DAG.getConstant(BitLen, DL, MVT::i8),
7130 DAG.getConstant(BitIdx, DL, MVT::i8));
7137 if (SDValue InsertQ = LowerAsInsertQ())
7143 /// \brief Lower a vector shuffle as a zero or any extension.
7145 /// Given a specific number of elements, element bit width, and extension
7146 /// stride, produce either a zero or any extension based on the available
7147 /// features of the subtarget.
7148 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7149 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7150 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7151 assert(Scale > 1 && "Need a scale to extend.");
7152 int NumElements = VT.getVectorNumElements();
7153 int EltBits = VT.getScalarSizeInBits();
7154 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7155 "Only 8, 16, and 32 bit elements can be extended.");
7156 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7158 // Found a valid zext mask! Try various lowering strategies based on the
7159 // input type and available ISA extensions.
7160 if (Subtarget->hasSSE41()) {
7161 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7162 NumElements / Scale);
7163 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7166 // For any extends we can cheat for larger element sizes and use shuffle
7167 // instructions that can fold with a load and/or copy.
7168 if (AnyExt && EltBits == 32) {
7169 int PSHUFDMask[4] = {0, -1, 1, -1};
7170 return DAG.getBitcast(
7171 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7172 DAG.getBitcast(MVT::v4i32, InputV),
7173 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7175 if (AnyExt && EltBits == 16 && Scale > 2) {
7176 int PSHUFDMask[4] = {0, -1, 0, -1};
7177 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7178 DAG.getBitcast(MVT::v4i32, InputV),
7179 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7180 int PSHUFHWMask[4] = {1, -1, -1, -1};
7181 return DAG.getBitcast(
7182 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7183 DAG.getBitcast(MVT::v8i16, InputV),
7184 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7187 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7189 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7190 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7191 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7193 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7194 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7195 DAG.getConstant(EltBits, DL, MVT::i8),
7196 DAG.getConstant(0, DL, MVT::i8)));
7197 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7198 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7201 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7202 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7203 DAG.getConstant(EltBits, DL, MVT::i8),
7204 DAG.getConstant(EltBits, DL, MVT::i8)));
7205 return DAG.getNode(ISD::BITCAST, DL, VT,
7206 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7209 // If this would require more than 2 unpack instructions to expand, use
7210 // pshufb when available. We can only use more than 2 unpack instructions
7211 // when zero extending i8 elements which also makes it easier to use pshufb.
7212 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7213 assert(NumElements == 16 && "Unexpected byte vector width!");
7214 SDValue PSHUFBMask[16];
7215 for (int i = 0; i < 16; ++i)
7217 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7218 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7219 return DAG.getBitcast(VT,
7220 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7221 DAG.getNode(ISD::BUILD_VECTOR, DL,
7222 MVT::v16i8, PSHUFBMask)));
7225 // Otherwise emit a sequence of unpacks.
7227 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7228 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7229 : getZeroVector(InputVT, Subtarget, DAG, DL);
7230 InputV = DAG.getBitcast(InputVT, InputV);
7231 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7235 } while (Scale > 1);
7236 return DAG.getBitcast(VT, InputV);
7239 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7241 /// This routine will try to do everything in its power to cleverly lower
7242 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7243 /// check for the profitability of this lowering, it tries to aggressively
7244 /// match this pattern. It will use all of the micro-architectural details it
7245 /// can to emit an efficient lowering. It handles both blends with all-zero
7246 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7247 /// masking out later).
7249 /// The reason we have dedicated lowering for zext-style shuffles is that they
7250 /// are both incredibly common and often quite performance sensitive.
7251 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7252 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7253 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7254 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7256 int Bits = VT.getSizeInBits();
7257 int NumElements = VT.getVectorNumElements();
7258 assert(VT.getScalarSizeInBits() <= 32 &&
7259 "Exceeds 32-bit integer zero extension limit");
7260 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7262 // Define a helper function to check a particular ext-scale and lower to it if
7264 auto Lower = [&](int Scale) -> SDValue {
7267 for (int i = 0; i < NumElements; ++i) {
7269 continue; // Valid anywhere but doesn't tell us anything.
7270 if (i % Scale != 0) {
7271 // Each of the extended elements need to be zeroable.
7275 // We no longer are in the anyext case.
7280 // Each of the base elements needs to be consecutive indices into the
7281 // same input vector.
7282 SDValue V = Mask[i] < NumElements ? V1 : V2;
7285 else if (InputV != V)
7286 return SDValue(); // Flip-flopping inputs.
7288 if (Mask[i] % NumElements != i / Scale)
7289 return SDValue(); // Non-consecutive strided elements.
7292 // If we fail to find an input, we have a zero-shuffle which should always
7293 // have already been handled.
7294 // FIXME: Maybe handle this here in case during blending we end up with one?
7298 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7299 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7302 // The widest scale possible for extending is to a 64-bit integer.
7303 assert(Bits % 64 == 0 &&
7304 "The number of bits in a vector must be divisible by 64 on x86!");
7305 int NumExtElements = Bits / 64;
7307 // Each iteration, try extending the elements half as much, but into twice as
7309 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7310 assert(NumElements % NumExtElements == 0 &&
7311 "The input vector size must be divisible by the extended size.");
7312 if (SDValue V = Lower(NumElements / NumExtElements))
7316 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7320 // Returns one of the source operands if the shuffle can be reduced to a
7321 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7322 auto CanZExtLowHalf = [&]() {
7323 for (int i = NumElements / 2; i != NumElements; ++i)
7326 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7328 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7333 if (SDValue V = CanZExtLowHalf()) {
7334 V = DAG.getBitcast(MVT::v2i64, V);
7335 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7336 return DAG.getBitcast(VT, V);
7339 // No viable ext lowering found.
7343 /// \brief Try to get a scalar value for a specific element of a vector.
7345 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7346 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7347 SelectionDAG &DAG) {
7348 MVT VT = V.getSimpleValueType();
7349 MVT EltVT = VT.getVectorElementType();
7350 while (V.getOpcode() == ISD::BITCAST)
7351 V = V.getOperand(0);
7352 // If the bitcasts shift the element size, we can't extract an equivalent
7354 MVT NewVT = V.getSimpleValueType();
7355 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7358 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7359 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7360 // Ensure the scalar operand is the same size as the destination.
7361 // FIXME: Add support for scalar truncation where possible.
7362 SDValue S = V.getOperand(Idx);
7363 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7364 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7370 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7372 /// This is particularly important because the set of instructions varies
7373 /// significantly based on whether the operand is a load or not.
7374 static bool isShuffleFoldableLoad(SDValue V) {
7375 while (V.getOpcode() == ISD::BITCAST)
7376 V = V.getOperand(0);
7378 return ISD::isNON_EXTLoad(V.getNode());
7381 /// \brief Try to lower insertion of a single element into a zero vector.
7383 /// This is a common pattern that we have especially efficient patterns to lower
7384 /// across all subtarget feature sets.
7385 static SDValue lowerVectorShuffleAsElementInsertion(
7386 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7387 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7388 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7390 MVT EltVT = VT.getVectorElementType();
7392 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7393 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7395 bool IsV1Zeroable = true;
7396 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7397 if (i != V2Index && !Zeroable[i]) {
7398 IsV1Zeroable = false;
7402 // Check for a single input from a SCALAR_TO_VECTOR node.
7403 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7404 // all the smarts here sunk into that routine. However, the current
7405 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7406 // vector shuffle lowering is dead.
7407 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7409 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7410 // We need to zext the scalar if it is smaller than an i32.
7411 V2S = DAG.getBitcast(EltVT, V2S);
7412 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7413 // Using zext to expand a narrow element won't work for non-zero
7418 // Zero-extend directly to i32.
7420 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7422 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7423 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7424 EltVT == MVT::i16) {
7425 // Either not inserting from the low element of the input or the input
7426 // element size is too small to use VZEXT_MOVL to clear the high bits.
7430 if (!IsV1Zeroable) {
7431 // If V1 can't be treated as a zero vector we have fewer options to lower
7432 // this. We can't support integer vectors or non-zero targets cheaply, and
7433 // the V1 elements can't be permuted in any way.
7434 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7435 if (!VT.isFloatingPoint() || V2Index != 0)
7437 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7438 V1Mask[V2Index] = -1;
7439 if (!isNoopShuffleMask(V1Mask))
7441 // This is essentially a special case blend operation, but if we have
7442 // general purpose blend operations, they are always faster. Bail and let
7443 // the rest of the lowering handle these as blends.
7444 if (Subtarget->hasSSE41())
7447 // Otherwise, use MOVSD or MOVSS.
7448 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7449 "Only two types of floating point element types to handle!");
7450 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7454 // This lowering only works for the low element with floating point vectors.
7455 if (VT.isFloatingPoint() && V2Index != 0)
7458 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7460 V2 = DAG.getBitcast(VT, V2);
7463 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7464 // the desired position. Otherwise it is more efficient to do a vector
7465 // shift left. We know that we can do a vector shift left because all
7466 // the inputs are zero.
7467 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7468 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7469 V2Shuffle[V2Index] = 0;
7470 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7472 V2 = DAG.getBitcast(MVT::v2i64, V2);
7474 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7475 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7476 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7477 DAG.getDataLayout(), VT)));
7478 V2 = DAG.getBitcast(VT, V2);
7484 /// \brief Try to lower broadcast of a single element.
7486 /// For convenience, this code also bundles all of the subtarget feature set
7487 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7488 /// a convenient way to factor it out.
7489 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7491 const X86Subtarget *Subtarget,
7492 SelectionDAG &DAG) {
7493 if (!Subtarget->hasAVX())
7495 if (VT.isInteger() && !Subtarget->hasAVX2())
7498 // Check that the mask is a broadcast.
7499 int BroadcastIdx = -1;
7501 if (M >= 0 && BroadcastIdx == -1)
7503 else if (M >= 0 && M != BroadcastIdx)
7506 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7507 "a sorted mask where the broadcast "
7510 // Go up the chain of (vector) values to find a scalar load that we can
7511 // combine with the broadcast.
7513 switch (V.getOpcode()) {
7514 case ISD::CONCAT_VECTORS: {
7515 int OperandSize = Mask.size() / V.getNumOperands();
7516 V = V.getOperand(BroadcastIdx / OperandSize);
7517 BroadcastIdx %= OperandSize;
7521 case ISD::INSERT_SUBVECTOR: {
7522 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7523 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7527 int BeginIdx = (int)ConstantIdx->getZExtValue();
7529 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7530 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7531 BroadcastIdx -= BeginIdx;
7542 // Check if this is a broadcast of a scalar. We special case lowering
7543 // for scalars so that we can more effectively fold with loads.
7544 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7545 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7546 V = V.getOperand(BroadcastIdx);
7548 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7549 // Only AVX2 has register broadcasts.
7550 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7552 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7553 // We can't broadcast from a vector register without AVX2, and we can only
7554 // broadcast from the zero-element of a vector register.
7558 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7561 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7562 // INSERTPS when the V1 elements are already in the correct locations
7563 // because otherwise we can just always use two SHUFPS instructions which
7564 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7565 // perform INSERTPS if a single V1 element is out of place and all V2
7566 // elements are zeroable.
7567 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7569 SelectionDAG &DAG) {
7570 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7571 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7572 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7573 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7575 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7578 int V1DstIndex = -1;
7579 int V2DstIndex = -1;
7580 bool V1UsedInPlace = false;
7582 for (int i = 0; i < 4; ++i) {
7583 // Synthesize a zero mask from the zeroable elements (includes undefs).
7589 // Flag if we use any V1 inputs in place.
7591 V1UsedInPlace = true;
7595 // We can only insert a single non-zeroable element.
7596 if (V1DstIndex != -1 || V2DstIndex != -1)
7600 // V1 input out of place for insertion.
7603 // V2 input for insertion.
7608 // Don't bother if we have no (non-zeroable) element for insertion.
7609 if (V1DstIndex == -1 && V2DstIndex == -1)
7612 // Determine element insertion src/dst indices. The src index is from the
7613 // start of the inserted vector, not the start of the concatenated vector.
7614 unsigned V2SrcIndex = 0;
7615 if (V1DstIndex != -1) {
7616 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7617 // and don't use the original V2 at all.
7618 V2SrcIndex = Mask[V1DstIndex];
7619 V2DstIndex = V1DstIndex;
7622 V2SrcIndex = Mask[V2DstIndex] - 4;
7625 // If no V1 inputs are used in place, then the result is created only from
7626 // the zero mask and the V2 insertion - so remove V1 dependency.
7628 V1 = DAG.getUNDEF(MVT::v4f32);
7630 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7631 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7633 // Insert the V2 element into the desired position.
7635 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7636 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7639 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7640 /// UNPCK instruction.
7642 /// This specifically targets cases where we end up with alternating between
7643 /// the two inputs, and so can permute them into something that feeds a single
7644 /// UNPCK instruction. Note that this routine only targets integer vectors
7645 /// because for floating point vectors we have a generalized SHUFPS lowering
7646 /// strategy that handles everything that doesn't *exactly* match an unpack,
7647 /// making this clever lowering unnecessary.
7648 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7649 SDValue V2, ArrayRef<int> Mask,
7650 SelectionDAG &DAG) {
7651 assert(!VT.isFloatingPoint() &&
7652 "This routine only supports integer vectors.");
7653 assert(!isSingleInputShuffleMask(Mask) &&
7654 "This routine should only be used when blending two inputs.");
7655 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7657 int Size = Mask.size();
7659 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7660 return M >= 0 && M % Size < Size / 2;
7662 int NumHiInputs = std::count_if(
7663 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7665 bool UnpackLo = NumLoInputs >= NumHiInputs;
7667 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7668 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7669 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7671 for (int i = 0; i < Size; ++i) {
7675 // Each element of the unpack contains Scale elements from this mask.
7676 int UnpackIdx = i / Scale;
7678 // We only handle the case where V1 feeds the first slots of the unpack.
7679 // We rely on canonicalization to ensure this is the case.
7680 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7683 // Setup the mask for this input. The indexing is tricky as we have to
7684 // handle the unpack stride.
7685 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7686 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7690 // If we will have to shuffle both inputs to use the unpack, check whether
7691 // we can just unpack first and shuffle the result. If so, skip this unpack.
7692 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7693 !isNoopShuffleMask(V2Mask))
7696 // Shuffle the inputs into place.
7697 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7698 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7700 // Cast the inputs to the type we will use to unpack them.
7701 V1 = DAG.getBitcast(UnpackVT, V1);
7702 V2 = DAG.getBitcast(UnpackVT, V2);
7704 // Unpack the inputs and cast the result back to the desired type.
7705 return DAG.getBitcast(
7706 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7710 // We try each unpack from the largest to the smallest to try and find one
7711 // that fits this mask.
7712 int OrigNumElements = VT.getVectorNumElements();
7713 int OrigScalarSize = VT.getScalarSizeInBits();
7714 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7715 int Scale = ScalarSize / OrigScalarSize;
7716 int NumElements = OrigNumElements / Scale;
7717 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7718 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7722 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7724 if (NumLoInputs == 0 || NumHiInputs == 0) {
7725 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7726 "We have to have *some* inputs!");
7727 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7729 // FIXME: We could consider the total complexity of the permute of each
7730 // possible unpacking. Or at the least we should consider how many
7731 // half-crossings are created.
7732 // FIXME: We could consider commuting the unpacks.
7734 SmallVector<int, 32> PermMask;
7735 PermMask.assign(Size, -1);
7736 for (int i = 0; i < Size; ++i) {
7740 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7743 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7745 return DAG.getVectorShuffle(
7746 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7748 DAG.getUNDEF(VT), PermMask);
7754 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7756 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7757 /// support for floating point shuffles but not integer shuffles. These
7758 /// instructions will incur a domain crossing penalty on some chips though so
7759 /// it is better to avoid lowering through this for integer vectors where
7761 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7762 const X86Subtarget *Subtarget,
7763 SelectionDAG &DAG) {
7765 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7766 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7767 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7768 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7769 ArrayRef<int> Mask = SVOp->getMask();
7770 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7772 if (isSingleInputShuffleMask(Mask)) {
7773 // Use low duplicate instructions for masks that match their pattern.
7774 if (Subtarget->hasSSE3())
7775 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7776 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7778 // Straight shuffle of a single input vector. Simulate this by using the
7779 // single input as both of the "inputs" to this instruction..
7780 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7782 if (Subtarget->hasAVX()) {
7783 // If we have AVX, we can use VPERMILPS which will allow folding a load
7784 // into the shuffle.
7785 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7786 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7789 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7790 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7792 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7793 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7795 // If we have a single input, insert that into V1 if we can do so cheaply.
7796 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7797 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7798 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7800 // Try inverting the insertion since for v2 masks it is easy to do and we
7801 // can't reliably sort the mask one way or the other.
7802 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7803 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7804 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7805 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7809 // Try to use one of the special instruction patterns to handle two common
7810 // blend patterns if a zero-blend above didn't work.
7811 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7812 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7813 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7814 // We can either use a special instruction to load over the low double or
7815 // to move just the low double.
7817 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7819 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7821 if (Subtarget->hasSSE41())
7822 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7826 // Use dedicated unpack instructions for masks that match their pattern.
7827 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7828 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7829 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7830 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7832 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7833 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7834 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7837 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7839 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7840 /// the integer unit to minimize domain crossing penalties. However, for blends
7841 /// it falls back to the floating point shuffle operation with appropriate bit
7843 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7844 const X86Subtarget *Subtarget,
7845 SelectionDAG &DAG) {
7847 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7848 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7849 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7850 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7851 ArrayRef<int> Mask = SVOp->getMask();
7852 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7854 if (isSingleInputShuffleMask(Mask)) {
7855 // Check for being able to broadcast a single element.
7856 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7857 Mask, Subtarget, DAG))
7860 // Straight shuffle of a single input vector. For everything from SSE2
7861 // onward this has a single fast instruction with no scary immediates.
7862 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7863 V1 = DAG.getBitcast(MVT::v4i32, V1);
7864 int WidenedMask[4] = {
7865 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7866 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7867 return DAG.getBitcast(
7869 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7870 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7872 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7873 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7874 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7875 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7877 // If we have a blend of two PACKUS operations an the blend aligns with the
7878 // low and half halves, we can just merge the PACKUS operations. This is
7879 // particularly important as it lets us merge shuffles that this routine itself
7881 auto GetPackNode = [](SDValue V) {
7882 while (V.getOpcode() == ISD::BITCAST)
7883 V = V.getOperand(0);
7885 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7887 if (SDValue V1Pack = GetPackNode(V1))
7888 if (SDValue V2Pack = GetPackNode(V2))
7889 return DAG.getBitcast(MVT::v2i64,
7890 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7891 Mask[0] == 0 ? V1Pack.getOperand(0)
7892 : V1Pack.getOperand(1),
7893 Mask[1] == 2 ? V2Pack.getOperand(0)
7894 : V2Pack.getOperand(1)));
7896 // Try to use shift instructions.
7898 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7901 // When loading a scalar and then shuffling it into a vector we can often do
7902 // the insertion cheaply.
7903 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7904 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7906 // Try inverting the insertion since for v2 masks it is easy to do and we
7907 // can't reliably sort the mask one way or the other.
7908 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7909 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7910 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7913 // We have different paths for blend lowering, but they all must use the
7914 // *exact* same predicate.
7915 bool IsBlendSupported = Subtarget->hasSSE41();
7916 if (IsBlendSupported)
7917 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7921 // Use dedicated unpack instructions for masks that match their pattern.
7922 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7923 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7924 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7925 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7927 // Try to use byte rotation instructions.
7928 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7929 if (Subtarget->hasSSSE3())
7930 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7931 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7934 // If we have direct support for blends, we should lower by decomposing into
7935 // a permute. That will be faster than the domain cross.
7936 if (IsBlendSupported)
7937 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7940 // We implement this with SHUFPD which is pretty lame because it will likely
7941 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7942 // However, all the alternatives are still more cycles and newer chips don't
7943 // have this problem. It would be really nice if x86 had better shuffles here.
7944 V1 = DAG.getBitcast(MVT::v2f64, V1);
7945 V2 = DAG.getBitcast(MVT::v2f64, V2);
7946 return DAG.getBitcast(MVT::v2i64,
7947 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7950 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7952 /// This is used to disable more specialized lowerings when the shufps lowering
7953 /// will happen to be efficient.
7954 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7955 // This routine only handles 128-bit shufps.
7956 assert(Mask.size() == 4 && "Unsupported mask size!");
7958 // To lower with a single SHUFPS we need to have the low half and high half
7959 // each requiring a single input.
7960 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7962 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7968 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7970 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7971 /// It makes no assumptions about whether this is the *best* lowering, it simply
7973 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7974 ArrayRef<int> Mask, SDValue V1,
7975 SDValue V2, SelectionDAG &DAG) {
7976 SDValue LowV = V1, HighV = V2;
7977 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7980 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7982 if (NumV2Elements == 1) {
7984 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7987 // Compute the index adjacent to V2Index and in the same half by toggling
7989 int V2AdjIndex = V2Index ^ 1;
7991 if (Mask[V2AdjIndex] == -1) {
7992 // Handles all the cases where we have a single V2 element and an undef.
7993 // This will only ever happen in the high lanes because we commute the
7994 // vector otherwise.
7996 std::swap(LowV, HighV);
7997 NewMask[V2Index] -= 4;
7999 // Handle the case where the V2 element ends up adjacent to a V1 element.
8000 // To make this work, blend them together as the first step.
8001 int V1Index = V2AdjIndex;
8002 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8003 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8004 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8006 // Now proceed to reconstruct the final blend as we have the necessary
8007 // high or low half formed.
8014 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8015 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8017 } else if (NumV2Elements == 2) {
8018 if (Mask[0] < 4 && Mask[1] < 4) {
8019 // Handle the easy case where we have V1 in the low lanes and V2 in the
8023 } else if (Mask[2] < 4 && Mask[3] < 4) {
8024 // We also handle the reversed case because this utility may get called
8025 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8026 // arrange things in the right direction.
8032 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8033 // trying to place elements directly, just blend them and set up the final
8034 // shuffle to place them.
8036 // The first two blend mask elements are for V1, the second two are for
8038 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8039 Mask[2] < 4 ? Mask[2] : Mask[3],
8040 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8041 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8042 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8043 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8045 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8048 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8049 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8050 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8051 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8054 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8055 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8058 /// \brief Lower 4-lane 32-bit floating point shuffles.
8060 /// Uses instructions exclusively from the floating point unit to minimize
8061 /// domain crossing penalties, as these are sufficient to implement all v4f32
8063 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8064 const X86Subtarget *Subtarget,
8065 SelectionDAG &DAG) {
8067 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8068 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8069 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8070 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8071 ArrayRef<int> Mask = SVOp->getMask();
8072 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8075 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8077 if (NumV2Elements == 0) {
8078 // Check for being able to broadcast a single element.
8079 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8080 Mask, Subtarget, DAG))
8083 // Use even/odd duplicate instructions for masks that match their pattern.
8084 if (Subtarget->hasSSE3()) {
8085 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8086 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8087 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8088 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8091 if (Subtarget->hasAVX()) {
8092 // If we have AVX, we can use VPERMILPS which will allow folding a load
8093 // into the shuffle.
8094 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8095 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8098 // Otherwise, use a straight shuffle of a single input vector. We pass the
8099 // input vector to both operands to simulate this with a SHUFPS.
8100 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8101 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8104 // There are special ways we can lower some single-element blends. However, we
8105 // have custom ways we can lower more complex single-element blends below that
8106 // we defer to if both this and BLENDPS fail to match, so restrict this to
8107 // when the V2 input is targeting element 0 of the mask -- that is the fast
8109 if (NumV2Elements == 1 && Mask[0] >= 4)
8110 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8111 Mask, Subtarget, DAG))
8114 if (Subtarget->hasSSE41()) {
8115 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8119 // Use INSERTPS if we can complete the shuffle efficiently.
8120 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8123 if (!isSingleSHUFPSMask(Mask))
8124 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8125 DL, MVT::v4f32, V1, V2, Mask, DAG))
8129 // Use dedicated unpack instructions for masks that match their pattern.
8130 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8131 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8132 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8133 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8134 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8135 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8136 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8137 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8139 // Otherwise fall back to a SHUFPS lowering strategy.
8140 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8143 /// \brief Lower 4-lane i32 vector shuffles.
8145 /// We try to handle these with integer-domain shuffles where we can, but for
8146 /// blends we use the floating point domain blend instructions.
8147 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8148 const X86Subtarget *Subtarget,
8149 SelectionDAG &DAG) {
8151 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8152 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8153 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8154 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8155 ArrayRef<int> Mask = SVOp->getMask();
8156 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8158 // Whenever we can lower this as a zext, that instruction is strictly faster
8159 // than any alternative. It also allows us to fold memory operands into the
8160 // shuffle in many cases.
8161 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8162 Mask, Subtarget, DAG))
8166 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8168 if (NumV2Elements == 0) {
8169 // Check for being able to broadcast a single element.
8170 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8171 Mask, Subtarget, DAG))
8174 // Straight shuffle of a single input vector. For everything from SSE2
8175 // onward this has a single fast instruction with no scary immediates.
8176 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8177 // but we aren't actually going to use the UNPCK instruction because doing
8178 // so prevents folding a load into this instruction or making a copy.
8179 const int UnpackLoMask[] = {0, 0, 1, 1};
8180 const int UnpackHiMask[] = {2, 2, 3, 3};
8181 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8182 Mask = UnpackLoMask;
8183 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8184 Mask = UnpackHiMask;
8186 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8187 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8190 // Try to use shift instructions.
8192 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8195 // There are special ways we can lower some single-element blends.
8196 if (NumV2Elements == 1)
8197 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8198 Mask, Subtarget, DAG))
8201 // We have different paths for blend lowering, but they all must use the
8202 // *exact* same predicate.
8203 bool IsBlendSupported = Subtarget->hasSSE41();
8204 if (IsBlendSupported)
8205 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8209 if (SDValue Masked =
8210 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8213 // Use dedicated unpack instructions for masks that match their pattern.
8214 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8215 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8216 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8217 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8218 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8219 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8220 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8221 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8223 // Try to use byte rotation instructions.
8224 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8225 if (Subtarget->hasSSSE3())
8226 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8227 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8230 // If we have direct support for blends, we should lower by decomposing into
8231 // a permute. That will be faster than the domain cross.
8232 if (IsBlendSupported)
8233 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8236 // Try to lower by permuting the inputs into an unpack instruction.
8237 if (SDValue Unpack =
8238 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8241 // We implement this with SHUFPS because it can blend from two vectors.
8242 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8243 // up the inputs, bypassing domain shift penalties that we would encur if we
8244 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8246 return DAG.getBitcast(
8248 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8249 DAG.getBitcast(MVT::v4f32, V2), Mask));
8252 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8253 /// shuffle lowering, and the most complex part.
8255 /// The lowering strategy is to try to form pairs of input lanes which are
8256 /// targeted at the same half of the final vector, and then use a dword shuffle
8257 /// to place them onto the right half, and finally unpack the paired lanes into
8258 /// their final position.
8260 /// The exact breakdown of how to form these dword pairs and align them on the
8261 /// correct sides is really tricky. See the comments within the function for
8262 /// more of the details.
8264 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8265 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8266 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8267 /// vector, form the analogous 128-bit 8-element Mask.
8268 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8269 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8270 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8271 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8272 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8274 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8275 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8276 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8278 SmallVector<int, 4> LoInputs;
8279 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8280 [](int M) { return M >= 0; });
8281 std::sort(LoInputs.begin(), LoInputs.end());
8282 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8283 SmallVector<int, 4> HiInputs;
8284 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8285 [](int M) { return M >= 0; });
8286 std::sort(HiInputs.begin(), HiInputs.end());
8287 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8289 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8290 int NumHToL = LoInputs.size() - NumLToL;
8292 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8293 int NumHToH = HiInputs.size() - NumLToH;
8294 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8295 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8296 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8297 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8299 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8300 // such inputs we can swap two of the dwords across the half mark and end up
8301 // with <=2 inputs to each half in each half. Once there, we can fall through
8302 // to the generic code below. For example:
8304 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8305 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8307 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8308 // and an existing 2-into-2 on the other half. In this case we may have to
8309 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8310 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8311 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8312 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8313 // half than the one we target for fixing) will be fixed when we re-enter this
8314 // path. We will also combine away any sequence of PSHUFD instructions that
8315 // result into a single instruction. Here is an example of the tricky case:
8317 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8318 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8320 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8322 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8323 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8325 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8326 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8328 // The result is fine to be handled by the generic logic.
8329 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8330 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8331 int AOffset, int BOffset) {
8332 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8333 "Must call this with A having 3 or 1 inputs from the A half.");
8334 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8335 "Must call this with B having 1 or 3 inputs from the B half.");
8336 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8337 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8339 // Compute the index of dword with only one word among the three inputs in
8340 // a half by taking the sum of the half with three inputs and subtracting
8341 // the sum of the actual three inputs. The difference is the remaining
8344 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8345 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8346 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8347 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8348 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8349 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8350 int TripleNonInputIdx =
8351 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8352 TripleDWord = TripleNonInputIdx / 2;
8354 // We use xor with one to compute the adjacent DWord to whichever one the
8356 OneInputDWord = (OneInput / 2) ^ 1;
8358 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8359 // and BToA inputs. If there is also such a problem with the BToB and AToB
8360 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8361 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8362 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8363 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8364 // Compute how many inputs will be flipped by swapping these DWords. We
8366 // to balance this to ensure we don't form a 3-1 shuffle in the other
8368 int NumFlippedAToBInputs =
8369 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8370 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8371 int NumFlippedBToBInputs =
8372 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8373 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8374 if ((NumFlippedAToBInputs == 1 &&
8375 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8376 (NumFlippedBToBInputs == 1 &&
8377 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8378 // We choose whether to fix the A half or B half based on whether that
8379 // half has zero flipped inputs. At zero, we may not be able to fix it
8380 // with that half. We also bias towards fixing the B half because that
8381 // will more commonly be the high half, and we have to bias one way.
8382 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8383 ArrayRef<int> Inputs) {
8384 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8385 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8386 PinnedIdx ^ 1) != Inputs.end();
8387 // Determine whether the free index is in the flipped dword or the
8388 // unflipped dword based on where the pinned index is. We use this bit
8389 // in an xor to conditionally select the adjacent dword.
8390 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8391 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8392 FixFreeIdx) != Inputs.end();
8393 if (IsFixIdxInput == IsFixFreeIdxInput)
8395 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8396 FixFreeIdx) != Inputs.end();
8397 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8398 "We need to be changing the number of flipped inputs!");
8399 int PSHUFHalfMask[] = {0, 1, 2, 3};
8400 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8401 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8403 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8406 if (M != -1 && M == FixIdx)
8408 else if (M != -1 && M == FixFreeIdx)
8411 if (NumFlippedBToBInputs != 0) {
8413 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8414 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8416 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8418 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8419 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8424 int PSHUFDMask[] = {0, 1, 2, 3};
8425 PSHUFDMask[ADWord] = BDWord;
8426 PSHUFDMask[BDWord] = ADWord;
8429 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8430 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8432 // Adjust the mask to match the new locations of A and B.
8434 if (M != -1 && M/2 == ADWord)
8435 M = 2 * BDWord + M % 2;
8436 else if (M != -1 && M/2 == BDWord)
8437 M = 2 * ADWord + M % 2;
8439 // Recurse back into this routine to re-compute state now that this isn't
8440 // a 3 and 1 problem.
8441 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8444 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8445 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8446 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8447 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8449 // At this point there are at most two inputs to the low and high halves from
8450 // each half. That means the inputs can always be grouped into dwords and
8451 // those dwords can then be moved to the correct half with a dword shuffle.
8452 // We use at most one low and one high word shuffle to collect these paired
8453 // inputs into dwords, and finally a dword shuffle to place them.
8454 int PSHUFLMask[4] = {-1, -1, -1, -1};
8455 int PSHUFHMask[4] = {-1, -1, -1, -1};
8456 int PSHUFDMask[4] = {-1, -1, -1, -1};
8458 // First fix the masks for all the inputs that are staying in their
8459 // original halves. This will then dictate the targets of the cross-half
8461 auto fixInPlaceInputs =
8462 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8463 MutableArrayRef<int> SourceHalfMask,
8464 MutableArrayRef<int> HalfMask, int HalfOffset) {
8465 if (InPlaceInputs.empty())
8467 if (InPlaceInputs.size() == 1) {
8468 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8469 InPlaceInputs[0] - HalfOffset;
8470 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8473 if (IncomingInputs.empty()) {
8474 // Just fix all of the in place inputs.
8475 for (int Input : InPlaceInputs) {
8476 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8477 PSHUFDMask[Input / 2] = Input / 2;
8482 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8483 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8484 InPlaceInputs[0] - HalfOffset;
8485 // Put the second input next to the first so that they are packed into
8486 // a dword. We find the adjacent index by toggling the low bit.
8487 int AdjIndex = InPlaceInputs[0] ^ 1;
8488 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8489 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8490 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8492 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8493 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8495 // Now gather the cross-half inputs and place them into a free dword of
8496 // their target half.
8497 // FIXME: This operation could almost certainly be simplified dramatically to
8498 // look more like the 3-1 fixing operation.
8499 auto moveInputsToRightHalf = [&PSHUFDMask](
8500 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8501 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8502 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8504 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8505 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8507 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8509 int LowWord = Word & ~1;
8510 int HighWord = Word | 1;
8511 return isWordClobbered(SourceHalfMask, LowWord) ||
8512 isWordClobbered(SourceHalfMask, HighWord);
8515 if (IncomingInputs.empty())
8518 if (ExistingInputs.empty()) {
8519 // Map any dwords with inputs from them into the right half.
8520 for (int Input : IncomingInputs) {
8521 // If the source half mask maps over the inputs, turn those into
8522 // swaps and use the swapped lane.
8523 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8524 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8525 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8526 Input - SourceOffset;
8527 // We have to swap the uses in our half mask in one sweep.
8528 for (int &M : HalfMask)
8529 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8531 else if (M == Input)
8532 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8534 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8535 Input - SourceOffset &&
8536 "Previous placement doesn't match!");
8538 // Note that this correctly re-maps both when we do a swap and when
8539 // we observe the other side of the swap above. We rely on that to
8540 // avoid swapping the members of the input list directly.
8541 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8544 // Map the input's dword into the correct half.
8545 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8546 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8548 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8550 "Previous placement doesn't match!");
8553 // And just directly shift any other-half mask elements to be same-half
8554 // as we will have mirrored the dword containing the element into the
8555 // same position within that half.
8556 for (int &M : HalfMask)
8557 if (M >= SourceOffset && M < SourceOffset + 4) {
8558 M = M - SourceOffset + DestOffset;
8559 assert(M >= 0 && "This should never wrap below zero!");
8564 // Ensure we have the input in a viable dword of its current half. This
8565 // is particularly tricky because the original position may be clobbered
8566 // by inputs being moved and *staying* in that half.
8567 if (IncomingInputs.size() == 1) {
8568 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8569 int InputFixed = std::find(std::begin(SourceHalfMask),
8570 std::end(SourceHalfMask), -1) -
8571 std::begin(SourceHalfMask) + SourceOffset;
8572 SourceHalfMask[InputFixed - SourceOffset] =
8573 IncomingInputs[0] - SourceOffset;
8574 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8576 IncomingInputs[0] = InputFixed;
8578 } else if (IncomingInputs.size() == 2) {
8579 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8580 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8581 // We have two non-adjacent or clobbered inputs we need to extract from
8582 // the source half. To do this, we need to map them into some adjacent
8583 // dword slot in the source mask.
8584 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8585 IncomingInputs[1] - SourceOffset};
8587 // If there is a free slot in the source half mask adjacent to one of
8588 // the inputs, place the other input in it. We use (Index XOR 1) to
8589 // compute an adjacent index.
8590 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8591 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8592 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8593 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8594 InputsFixed[1] = InputsFixed[0] ^ 1;
8595 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8596 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8597 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8598 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8599 InputsFixed[0] = InputsFixed[1] ^ 1;
8600 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8601 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8602 // The two inputs are in the same DWord but it is clobbered and the
8603 // adjacent DWord isn't used at all. Move both inputs to the free
8605 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8606 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8607 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8608 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8610 // The only way we hit this point is if there is no clobbering
8611 // (because there are no off-half inputs to this half) and there is no
8612 // free slot adjacent to one of the inputs. In this case, we have to
8613 // swap an input with a non-input.
8614 for (int i = 0; i < 4; ++i)
8615 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8616 "We can't handle any clobbers here!");
8617 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8618 "Cannot have adjacent inputs here!");
8620 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8621 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8623 // We also have to update the final source mask in this case because
8624 // it may need to undo the above swap.
8625 for (int &M : FinalSourceHalfMask)
8626 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8627 M = InputsFixed[1] + SourceOffset;
8628 else if (M == InputsFixed[1] + SourceOffset)
8629 M = (InputsFixed[0] ^ 1) + SourceOffset;
8631 InputsFixed[1] = InputsFixed[0] ^ 1;
8634 // Point everything at the fixed inputs.
8635 for (int &M : HalfMask)
8636 if (M == IncomingInputs[0])
8637 M = InputsFixed[0] + SourceOffset;
8638 else if (M == IncomingInputs[1])
8639 M = InputsFixed[1] + SourceOffset;
8641 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8642 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8645 llvm_unreachable("Unhandled input size!");
8648 // Now hoist the DWord down to the right half.
8649 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8650 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8651 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8652 for (int &M : HalfMask)
8653 for (int Input : IncomingInputs)
8655 M = FreeDWord * 2 + Input % 2;
8657 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8658 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8659 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8660 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8662 // Now enact all the shuffles we've computed to move the inputs into their
8664 if (!isNoopShuffleMask(PSHUFLMask))
8665 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8666 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8667 if (!isNoopShuffleMask(PSHUFHMask))
8668 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8669 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8670 if (!isNoopShuffleMask(PSHUFDMask))
8673 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8674 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8676 // At this point, each half should contain all its inputs, and we can then
8677 // just shuffle them into their final position.
8678 assert(std::count_if(LoMask.begin(), LoMask.end(),
8679 [](int M) { return M >= 4; }) == 0 &&
8680 "Failed to lift all the high half inputs to the low mask!");
8681 assert(std::count_if(HiMask.begin(), HiMask.end(),
8682 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8683 "Failed to lift all the low half inputs to the high mask!");
8685 // Do a half shuffle for the low mask.
8686 if (!isNoopShuffleMask(LoMask))
8687 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8688 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8690 // Do a half shuffle with the high mask after shifting its values down.
8691 for (int &M : HiMask)
8694 if (!isNoopShuffleMask(HiMask))
8695 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8696 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8701 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8702 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8703 SDValue V2, ArrayRef<int> Mask,
8704 SelectionDAG &DAG, bool &V1InUse,
8706 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8712 int Size = Mask.size();
8713 int Scale = 16 / Size;
8714 for (int i = 0; i < 16; ++i) {
8715 if (Mask[i / Scale] == -1) {
8716 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8718 const int ZeroMask = 0x80;
8719 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8721 int V2Idx = Mask[i / Scale] < Size
8723 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8724 if (Zeroable[i / Scale])
8725 V1Idx = V2Idx = ZeroMask;
8726 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8727 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8728 V1InUse |= (ZeroMask != V1Idx);
8729 V2InUse |= (ZeroMask != V2Idx);
8734 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8735 DAG.getBitcast(MVT::v16i8, V1),
8736 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8738 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8739 DAG.getBitcast(MVT::v16i8, V2),
8740 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8742 // If we need shuffled inputs from both, blend the two.
8744 if (V1InUse && V2InUse)
8745 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8747 V = V1InUse ? V1 : V2;
8749 // Cast the result back to the correct type.
8750 return DAG.getBitcast(VT, V);
8753 /// \brief Generic lowering of 8-lane i16 shuffles.
8755 /// This handles both single-input shuffles and combined shuffle/blends with
8756 /// two inputs. The single input shuffles are immediately delegated to
8757 /// a dedicated lowering routine.
8759 /// The blends are lowered in one of three fundamental ways. If there are few
8760 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8761 /// of the input is significantly cheaper when lowered as an interleaving of
8762 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8763 /// halves of the inputs separately (making them have relatively few inputs)
8764 /// and then concatenate them.
8765 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8766 const X86Subtarget *Subtarget,
8767 SelectionDAG &DAG) {
8769 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8770 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8771 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8772 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8773 ArrayRef<int> OrigMask = SVOp->getMask();
8774 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8775 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8776 MutableArrayRef<int> Mask(MaskStorage);
8778 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8780 // Whenever we can lower this as a zext, that instruction is strictly faster
8781 // than any alternative.
8782 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8783 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8786 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8788 auto isV2 = [](int M) { return M >= 8; };
8790 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8792 if (NumV2Inputs == 0) {
8793 // Check for being able to broadcast a single element.
8794 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8795 Mask, Subtarget, DAG))
8798 // Try to use shift instructions.
8800 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8803 // Use dedicated unpack instructions for masks that match their pattern.
8804 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8805 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8806 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8807 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8809 // Try to use byte rotation instructions.
8810 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8811 Mask, Subtarget, DAG))
8814 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8818 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8819 "All single-input shuffles should be canonicalized to be V1-input "
8822 // Try to use shift instructions.
8824 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8827 // See if we can use SSE4A Extraction / Insertion.
8828 if (Subtarget->hasSSE4A())
8829 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8832 // There are special ways we can lower some single-element blends.
8833 if (NumV2Inputs == 1)
8834 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8835 Mask, Subtarget, DAG))
8838 // We have different paths for blend lowering, but they all must use the
8839 // *exact* same predicate.
8840 bool IsBlendSupported = Subtarget->hasSSE41();
8841 if (IsBlendSupported)
8842 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8846 if (SDValue Masked =
8847 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8850 // Use dedicated unpack instructions for masks that match their pattern.
8851 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8852 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8853 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8854 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8856 // Try to use byte rotation instructions.
8857 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8858 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8861 if (SDValue BitBlend =
8862 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8865 if (SDValue Unpack =
8866 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8869 // If we can't directly blend but can use PSHUFB, that will be better as it
8870 // can both shuffle and set up the inefficient blend.
8871 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8872 bool V1InUse, V2InUse;
8873 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8877 // We can always bit-blend if we have to so the fallback strategy is to
8878 // decompose into single-input permutes and blends.
8879 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8883 /// \brief Check whether a compaction lowering can be done by dropping even
8884 /// elements and compute how many times even elements must be dropped.
8886 /// This handles shuffles which take every Nth element where N is a power of
8887 /// two. Example shuffle masks:
8889 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8890 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8891 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8892 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8893 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8894 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8896 /// Any of these lanes can of course be undef.
8898 /// This routine only supports N <= 3.
8899 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8902 /// \returns N above, or the number of times even elements must be dropped if
8903 /// there is such a number. Otherwise returns zero.
8904 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8905 // Figure out whether we're looping over two inputs or just one.
8906 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8908 // The modulus for the shuffle vector entries is based on whether this is
8909 // a single input or not.
8910 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8911 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8912 "We should only be called with masks with a power-of-2 size!");
8914 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8916 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8917 // and 2^3 simultaneously. This is because we may have ambiguity with
8918 // partially undef inputs.
8919 bool ViableForN[3] = {true, true, true};
8921 for (int i = 0, e = Mask.size(); i < e; ++i) {
8922 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8927 bool IsAnyViable = false;
8928 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8929 if (ViableForN[j]) {
8932 // The shuffle mask must be equal to (i * 2^N) % M.
8933 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8936 ViableForN[j] = false;
8938 // Early exit if we exhaust the possible powers of two.
8943 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8947 // Return 0 as there is no viable power of two.
8951 /// \brief Generic lowering of v16i8 shuffles.
8953 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8954 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8955 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8956 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8958 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8959 const X86Subtarget *Subtarget,
8960 SelectionDAG &DAG) {
8962 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8963 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8964 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8965 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8966 ArrayRef<int> Mask = SVOp->getMask();
8967 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8969 // Try to use shift instructions.
8971 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8974 // Try to use byte rotation instructions.
8975 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8976 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8979 // Try to use a zext lowering.
8980 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8981 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8984 // See if we can use SSE4A Extraction / Insertion.
8985 if (Subtarget->hasSSE4A())
8986 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8990 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8992 // For single-input shuffles, there are some nicer lowering tricks we can use.
8993 if (NumV2Elements == 0) {
8994 // Check for being able to broadcast a single element.
8995 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8996 Mask, Subtarget, DAG))
8999 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9000 // Notably, this handles splat and partial-splat shuffles more efficiently.
9001 // However, it only makes sense if the pre-duplication shuffle simplifies
9002 // things significantly. Currently, this means we need to be able to
9003 // express the pre-duplication shuffle as an i16 shuffle.
9005 // FIXME: We should check for other patterns which can be widened into an
9006 // i16 shuffle as well.
9007 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9008 for (int i = 0; i < 16; i += 2)
9009 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9014 auto tryToWidenViaDuplication = [&]() -> SDValue {
9015 if (!canWidenViaDuplication(Mask))
9017 SmallVector<int, 4> LoInputs;
9018 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9019 [](int M) { return M >= 0 && M < 8; });
9020 std::sort(LoInputs.begin(), LoInputs.end());
9021 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9023 SmallVector<int, 4> HiInputs;
9024 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9025 [](int M) { return M >= 8; });
9026 std::sort(HiInputs.begin(), HiInputs.end());
9027 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9030 bool TargetLo = LoInputs.size() >= HiInputs.size();
9031 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9032 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9034 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9035 SmallDenseMap<int, int, 8> LaneMap;
9036 for (int I : InPlaceInputs) {
9037 PreDupI16Shuffle[I/2] = I/2;
9040 int j = TargetLo ? 0 : 4, je = j + 4;
9041 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9042 // Check if j is already a shuffle of this input. This happens when
9043 // there are two adjacent bytes after we move the low one.
9044 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9045 // If we haven't yet mapped the input, search for a slot into which
9047 while (j < je && PreDupI16Shuffle[j] != -1)
9051 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9054 // Map this input with the i16 shuffle.
9055 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9058 // Update the lane map based on the mapping we ended up with.
9059 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9061 V1 = DAG.getBitcast(
9063 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9064 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9066 // Unpack the bytes to form the i16s that will be shuffled into place.
9067 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9068 MVT::v16i8, V1, V1);
9070 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9071 for (int i = 0; i < 16; ++i)
9072 if (Mask[i] != -1) {
9073 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9074 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9075 if (PostDupI16Shuffle[i / 2] == -1)
9076 PostDupI16Shuffle[i / 2] = MappedMask;
9078 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9079 "Conflicting entrties in the original shuffle!");
9081 return DAG.getBitcast(
9083 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9084 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9086 if (SDValue V = tryToWidenViaDuplication())
9090 // Use dedicated unpack instructions for masks that match their pattern.
9091 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9092 0, 16, 1, 17, 2, 18, 3, 19,
9094 4, 20, 5, 21, 6, 22, 7, 23}))
9095 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9096 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9097 8, 24, 9, 25, 10, 26, 11, 27,
9099 12, 28, 13, 29, 14, 30, 15, 31}))
9100 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9102 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9103 // with PSHUFB. It is important to do this before we attempt to generate any
9104 // blends but after all of the single-input lowerings. If the single input
9105 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9106 // want to preserve that and we can DAG combine any longer sequences into
9107 // a PSHUFB in the end. But once we start blending from multiple inputs,
9108 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9109 // and there are *very* few patterns that would actually be faster than the
9110 // PSHUFB approach because of its ability to zero lanes.
9112 // FIXME: The only exceptions to the above are blends which are exact
9113 // interleavings with direct instructions supporting them. We currently don't
9114 // handle those well here.
9115 if (Subtarget->hasSSSE3()) {
9116 bool V1InUse = false;
9117 bool V2InUse = false;
9119 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9120 DAG, V1InUse, V2InUse);
9122 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9123 // do so. This avoids using them to handle blends-with-zero which is
9124 // important as a single pshufb is significantly faster for that.
9125 if (V1InUse && V2InUse) {
9126 if (Subtarget->hasSSE41())
9127 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9128 Mask, Subtarget, DAG))
9131 // We can use an unpack to do the blending rather than an or in some
9132 // cases. Even though the or may be (very minorly) more efficient, we
9133 // preference this lowering because there are common cases where part of
9134 // the complexity of the shuffles goes away when we do the final blend as
9136 // FIXME: It might be worth trying to detect if the unpack-feeding
9137 // shuffles will both be pshufb, in which case we shouldn't bother with
9139 if (SDValue Unpack =
9140 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9147 // There are special ways we can lower some single-element blends.
9148 if (NumV2Elements == 1)
9149 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9150 Mask, Subtarget, DAG))
9153 if (SDValue BitBlend =
9154 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9157 // Check whether a compaction lowering can be done. This handles shuffles
9158 // which take every Nth element for some even N. See the helper function for
9161 // We special case these as they can be particularly efficiently handled with
9162 // the PACKUSB instruction on x86 and they show up in common patterns of
9163 // rearranging bytes to truncate wide elements.
9164 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9165 // NumEvenDrops is the power of two stride of the elements. Another way of
9166 // thinking about it is that we need to drop the even elements this many
9167 // times to get the original input.
9168 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9170 // First we need to zero all the dropped bytes.
9171 assert(NumEvenDrops <= 3 &&
9172 "No support for dropping even elements more than 3 times.");
9173 // We use the mask type to pick which bytes are preserved based on how many
9174 // elements are dropped.
9175 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9176 SDValue ByteClearMask = DAG.getBitcast(
9177 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9178 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9180 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9182 // Now pack things back together.
9183 V1 = DAG.getBitcast(MVT::v8i16, V1);
9184 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9185 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9186 for (int i = 1; i < NumEvenDrops; ++i) {
9187 Result = DAG.getBitcast(MVT::v8i16, Result);
9188 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9194 // Handle multi-input cases by blending single-input shuffles.
9195 if (NumV2Elements > 0)
9196 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9199 // The fallback path for single-input shuffles widens this into two v8i16
9200 // vectors with unpacks, shuffles those, and then pulls them back together
9204 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9205 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9206 for (int i = 0; i < 16; ++i)
9208 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9210 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9212 SDValue VLoHalf, VHiHalf;
9213 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9214 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9216 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9217 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9218 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9219 [](int M) { return M >= 0 && M % 2 == 1; })) {
9220 // Use a mask to drop the high bytes.
9221 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9222 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9223 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9225 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9226 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9228 // Squash the masks to point directly into VLoHalf.
9229 for (int &M : LoBlendMask)
9232 for (int &M : HiBlendMask)
9236 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9237 // VHiHalf so that we can blend them as i16s.
9238 VLoHalf = DAG.getBitcast(
9239 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9240 VHiHalf = DAG.getBitcast(
9241 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9244 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9245 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9247 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9250 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9252 /// This routine breaks down the specific type of 128-bit shuffle and
9253 /// dispatches to the lowering routines accordingly.
9254 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9255 MVT VT, const X86Subtarget *Subtarget,
9256 SelectionDAG &DAG) {
9257 switch (VT.SimpleTy) {
9259 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9261 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9263 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9265 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9267 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9269 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9272 llvm_unreachable("Unimplemented!");
9276 /// \brief Helper function to test whether a shuffle mask could be
9277 /// simplified by widening the elements being shuffled.
9279 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9280 /// leaves it in an unspecified state.
9282 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9283 /// shuffle masks. The latter have the special property of a '-2' representing
9284 /// a zero-ed lane of a vector.
9285 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9286 SmallVectorImpl<int> &WidenedMask) {
9287 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9288 // If both elements are undef, its trivial.
9289 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9290 WidenedMask.push_back(SM_SentinelUndef);
9294 // Check for an undef mask and a mask value properly aligned to fit with
9295 // a pair of values. If we find such a case, use the non-undef mask's value.
9296 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9297 WidenedMask.push_back(Mask[i + 1] / 2);
9300 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9301 WidenedMask.push_back(Mask[i] / 2);
9305 // When zeroing, we need to spread the zeroing across both lanes to widen.
9306 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9307 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9308 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9309 WidenedMask.push_back(SM_SentinelZero);
9315 // Finally check if the two mask values are adjacent and aligned with
9317 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9318 WidenedMask.push_back(Mask[i] / 2);
9322 // Otherwise we can't safely widen the elements used in this shuffle.
9325 assert(WidenedMask.size() == Mask.size() / 2 &&
9326 "Incorrect size of mask after widening the elements!");
9331 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9333 /// This routine just extracts two subvectors, shuffles them independently, and
9334 /// then concatenates them back together. This should work effectively with all
9335 /// AVX vector shuffle types.
9336 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9337 SDValue V2, ArrayRef<int> Mask,
9338 SelectionDAG &DAG) {
9339 assert(VT.getSizeInBits() >= 256 &&
9340 "Only for 256-bit or wider vector shuffles!");
9341 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9342 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9344 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9345 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9347 int NumElements = VT.getVectorNumElements();
9348 int SplitNumElements = NumElements / 2;
9349 MVT ScalarVT = VT.getScalarType();
9350 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9352 // Rather than splitting build-vectors, just build two narrower build
9353 // vectors. This helps shuffling with splats and zeros.
9354 auto SplitVector = [&](SDValue V) {
9355 while (V.getOpcode() == ISD::BITCAST)
9356 V = V->getOperand(0);
9358 MVT OrigVT = V.getSimpleValueType();
9359 int OrigNumElements = OrigVT.getVectorNumElements();
9360 int OrigSplitNumElements = OrigNumElements / 2;
9361 MVT OrigScalarVT = OrigVT.getScalarType();
9362 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9366 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9368 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9369 DAG.getIntPtrConstant(0, DL));
9370 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9371 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9374 SmallVector<SDValue, 16> LoOps, HiOps;
9375 for (int i = 0; i < OrigSplitNumElements; ++i) {
9376 LoOps.push_back(BV->getOperand(i));
9377 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9379 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9380 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9382 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9383 DAG.getBitcast(SplitVT, HiV));
9386 SDValue LoV1, HiV1, LoV2, HiV2;
9387 std::tie(LoV1, HiV1) = SplitVector(V1);
9388 std::tie(LoV2, HiV2) = SplitVector(V2);
9390 // Now create two 4-way blends of these half-width vectors.
9391 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9392 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9393 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9394 for (int i = 0; i < SplitNumElements; ++i) {
9395 int M = HalfMask[i];
9396 if (M >= NumElements) {
9397 if (M >= NumElements + SplitNumElements)
9401 V2BlendMask.push_back(M - NumElements);
9402 V1BlendMask.push_back(-1);
9403 BlendMask.push_back(SplitNumElements + i);
9404 } else if (M >= 0) {
9405 if (M >= SplitNumElements)
9409 V2BlendMask.push_back(-1);
9410 V1BlendMask.push_back(M);
9411 BlendMask.push_back(i);
9413 V2BlendMask.push_back(-1);
9414 V1BlendMask.push_back(-1);
9415 BlendMask.push_back(-1);
9419 // Because the lowering happens after all combining takes place, we need to
9420 // manually combine these blend masks as much as possible so that we create
9421 // a minimal number of high-level vector shuffle nodes.
9423 // First try just blending the halves of V1 or V2.
9424 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9425 return DAG.getUNDEF(SplitVT);
9426 if (!UseLoV2 && !UseHiV2)
9427 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9428 if (!UseLoV1 && !UseHiV1)
9429 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9431 SDValue V1Blend, V2Blend;
9432 if (UseLoV1 && UseHiV1) {
9434 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9436 // We only use half of V1 so map the usage down into the final blend mask.
9437 V1Blend = UseLoV1 ? LoV1 : HiV1;
9438 for (int i = 0; i < SplitNumElements; ++i)
9439 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9440 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9442 if (UseLoV2 && UseHiV2) {
9444 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9446 // We only use half of V2 so map the usage down into the final blend mask.
9447 V2Blend = UseLoV2 ? LoV2 : HiV2;
9448 for (int i = 0; i < SplitNumElements; ++i)
9449 if (BlendMask[i] >= SplitNumElements)
9450 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9452 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9454 SDValue Lo = HalfBlend(LoMask);
9455 SDValue Hi = HalfBlend(HiMask);
9456 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9459 /// \brief Either split a vector in halves or decompose the shuffles and the
9462 /// This is provided as a good fallback for many lowerings of non-single-input
9463 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9464 /// between splitting the shuffle into 128-bit components and stitching those
9465 /// back together vs. extracting the single-input shuffles and blending those
9467 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9468 SDValue V2, ArrayRef<int> Mask,
9469 SelectionDAG &DAG) {
9470 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9471 "lower single-input shuffles as it "
9472 "could then recurse on itself.");
9473 int Size = Mask.size();
9475 // If this can be modeled as a broadcast of two elements followed by a blend,
9476 // prefer that lowering. This is especially important because broadcasts can
9477 // often fold with memory operands.
9478 auto DoBothBroadcast = [&] {
9479 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9482 if (V2BroadcastIdx == -1)
9483 V2BroadcastIdx = M - Size;
9484 else if (M - Size != V2BroadcastIdx)
9486 } else if (M >= 0) {
9487 if (V1BroadcastIdx == -1)
9489 else if (M != V1BroadcastIdx)
9494 if (DoBothBroadcast())
9495 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9498 // If the inputs all stem from a single 128-bit lane of each input, then we
9499 // split them rather than blending because the split will decompose to
9500 // unusually few instructions.
9501 int LaneCount = VT.getSizeInBits() / 128;
9502 int LaneSize = Size / LaneCount;
9503 SmallBitVector LaneInputs[2];
9504 LaneInputs[0].resize(LaneCount, false);
9505 LaneInputs[1].resize(LaneCount, false);
9506 for (int i = 0; i < Size; ++i)
9508 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9509 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9510 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9512 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9513 // that the decomposed single-input shuffles don't end up here.
9514 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9517 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9518 /// a permutation and blend of those lanes.
9520 /// This essentially blends the out-of-lane inputs to each lane into the lane
9521 /// from a permuted copy of the vector. This lowering strategy results in four
9522 /// instructions in the worst case for a single-input cross lane shuffle which
9523 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9524 /// of. Special cases for each particular shuffle pattern should be handled
9525 /// prior to trying this lowering.
9526 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9527 SDValue V1, SDValue V2,
9529 SelectionDAG &DAG) {
9530 // FIXME: This should probably be generalized for 512-bit vectors as well.
9531 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9532 int LaneSize = Mask.size() / 2;
9534 // If there are only inputs from one 128-bit lane, splitting will in fact be
9535 // less expensive. The flags track whether the given lane contains an element
9536 // that crosses to another lane.
9537 bool LaneCrossing[2] = {false, false};
9538 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9539 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9540 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9541 if (!LaneCrossing[0] || !LaneCrossing[1])
9542 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9544 if (isSingleInputShuffleMask(Mask)) {
9545 SmallVector<int, 32> FlippedBlendMask;
9546 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9547 FlippedBlendMask.push_back(
9548 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9550 : Mask[i] % LaneSize +
9551 (i / LaneSize) * LaneSize + Size));
9553 // Flip the vector, and blend the results which should now be in-lane. The
9554 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9555 // 5 for the high source. The value 3 selects the high half of source 2 and
9556 // the value 2 selects the low half of source 2. We only use source 2 to
9557 // allow folding it into a memory operand.
9558 unsigned PERMMask = 3 | 2 << 4;
9559 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9560 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9561 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9564 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9565 // will be handled by the above logic and a blend of the results, much like
9566 // other patterns in AVX.
9567 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9570 /// \brief Handle lowering 2-lane 128-bit shuffles.
9571 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9572 SDValue V2, ArrayRef<int> Mask,
9573 const X86Subtarget *Subtarget,
9574 SelectionDAG &DAG) {
9575 // TODO: If minimizing size and one of the inputs is a zero vector and the
9576 // the zero vector has only one use, we could use a VPERM2X128 to save the
9577 // instruction bytes needed to explicitly generate the zero vector.
9579 // Blends are faster and handle all the non-lane-crossing cases.
9580 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9584 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9585 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9587 // If either input operand is a zero vector, use VPERM2X128 because its mask
9588 // allows us to replace the zero input with an implicit zero.
9589 if (!IsV1Zero && !IsV2Zero) {
9590 // Check for patterns which can be matched with a single insert of a 128-bit
9592 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9593 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9594 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9595 VT.getVectorNumElements() / 2);
9596 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9597 DAG.getIntPtrConstant(0, DL));
9598 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9599 OnlyUsesV1 ? V1 : V2,
9600 DAG.getIntPtrConstant(0, DL));
9601 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9605 // Otherwise form a 128-bit permutation. After accounting for undefs,
9606 // convert the 64-bit shuffle mask selection values into 128-bit
9607 // selection bits by dividing the indexes by 2 and shifting into positions
9608 // defined by a vperm2*128 instruction's immediate control byte.
9610 // The immediate permute control byte looks like this:
9611 // [1:0] - select 128 bits from sources for low half of destination
9613 // [3] - zero low half of destination
9614 // [5:4] - select 128 bits from sources for high half of destination
9616 // [7] - zero high half of destination
9618 int MaskLO = Mask[0];
9619 if (MaskLO == SM_SentinelUndef)
9620 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9622 int MaskHI = Mask[2];
9623 if (MaskHI == SM_SentinelUndef)
9624 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9626 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9628 // If either input is a zero vector, replace it with an undef input.
9629 // Shuffle mask values < 4 are selecting elements of V1.
9630 // Shuffle mask values >= 4 are selecting elements of V2.
9631 // Adjust each half of the permute mask by clearing the half that was
9632 // selecting the zero vector and setting the zero mask bit.
9634 V1 = DAG.getUNDEF(VT);
9636 PermMask = (PermMask & 0xf0) | 0x08;
9638 PermMask = (PermMask & 0x0f) | 0x80;
9641 V2 = DAG.getUNDEF(VT);
9643 PermMask = (PermMask & 0xf0) | 0x08;
9645 PermMask = (PermMask & 0x0f) | 0x80;
9648 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9649 DAG.getConstant(PermMask, DL, MVT::i8));
9652 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9653 /// shuffling each lane.
9655 /// This will only succeed when the result of fixing the 128-bit lanes results
9656 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9657 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9658 /// the lane crosses early and then use simpler shuffles within each lane.
9660 /// FIXME: It might be worthwhile at some point to support this without
9661 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9662 /// in x86 only floating point has interesting non-repeating shuffles, and even
9663 /// those are still *marginally* more expensive.
9664 static SDValue lowerVectorShuffleByMerging128BitLanes(
9665 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9666 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9667 assert(!isSingleInputShuffleMask(Mask) &&
9668 "This is only useful with multiple inputs.");
9670 int Size = Mask.size();
9671 int LaneSize = 128 / VT.getScalarSizeInBits();
9672 int NumLanes = Size / LaneSize;
9673 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9675 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9676 // check whether the in-128-bit lane shuffles share a repeating pattern.
9677 SmallVector<int, 4> Lanes;
9678 Lanes.resize(NumLanes, -1);
9679 SmallVector<int, 4> InLaneMask;
9680 InLaneMask.resize(LaneSize, -1);
9681 for (int i = 0; i < Size; ++i) {
9685 int j = i / LaneSize;
9688 // First entry we've seen for this lane.
9689 Lanes[j] = Mask[i] / LaneSize;
9690 } else if (Lanes[j] != Mask[i] / LaneSize) {
9691 // This doesn't match the lane selected previously!
9695 // Check that within each lane we have a consistent shuffle mask.
9696 int k = i % LaneSize;
9697 if (InLaneMask[k] < 0) {
9698 InLaneMask[k] = Mask[i] % LaneSize;
9699 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9700 // This doesn't fit a repeating in-lane mask.
9705 // First shuffle the lanes into place.
9706 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9707 VT.getSizeInBits() / 64);
9708 SmallVector<int, 8> LaneMask;
9709 LaneMask.resize(NumLanes * 2, -1);
9710 for (int i = 0; i < NumLanes; ++i)
9711 if (Lanes[i] >= 0) {
9712 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9713 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9716 V1 = DAG.getBitcast(LaneVT, V1);
9717 V2 = DAG.getBitcast(LaneVT, V2);
9718 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9720 // Cast it back to the type we actually want.
9721 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9723 // Now do a simple shuffle that isn't lane crossing.
9724 SmallVector<int, 8> NewMask;
9725 NewMask.resize(Size, -1);
9726 for (int i = 0; i < Size; ++i)
9728 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9729 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9730 "Must not introduce lane crosses at this point!");
9732 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9735 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9738 /// This returns true if the elements from a particular input are already in the
9739 /// slot required by the given mask and require no permutation.
9740 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9741 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9742 int Size = Mask.size();
9743 for (int i = 0; i < Size; ++i)
9744 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9750 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9751 ArrayRef<int> Mask, SDValue V1,
9752 SDValue V2, SelectionDAG &DAG) {
9754 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9755 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9756 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9757 int NumElts = VT.getVectorNumElements();
9758 bool ShufpdMask = true;
9759 bool CommutableMask = true;
9760 unsigned Immediate = 0;
9761 for (int i = 0; i < NumElts; ++i) {
9764 int Val = (i & 6) + NumElts * (i & 1);
9765 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9766 if (Mask[i] < Val || Mask[i] > Val + 1)
9768 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9769 CommutableMask = false;
9770 Immediate |= (Mask[i] % 2) << i;
9773 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9774 DAG.getConstant(Immediate, DL, MVT::i8));
9776 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9777 DAG.getConstant(Immediate, DL, MVT::i8));
9781 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9783 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9784 /// isn't available.
9785 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9786 const X86Subtarget *Subtarget,
9787 SelectionDAG &DAG) {
9789 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9790 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9791 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9792 ArrayRef<int> Mask = SVOp->getMask();
9793 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9795 SmallVector<int, 4> WidenedMask;
9796 if (canWidenShuffleElements(Mask, WidenedMask))
9797 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9800 if (isSingleInputShuffleMask(Mask)) {
9801 // Check for being able to broadcast a single element.
9802 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9803 Mask, Subtarget, DAG))
9806 // Use low duplicate instructions for masks that match their pattern.
9807 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9808 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9810 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9811 // Non-half-crossing single input shuffles can be lowerid with an
9812 // interleaved permutation.
9813 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9814 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9815 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9816 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9819 // With AVX2 we have direct support for this permutation.
9820 if (Subtarget->hasAVX2())
9821 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9822 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9824 // Otherwise, fall back.
9825 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9829 // X86 has dedicated unpack instructions that can handle specific blend
9830 // operations: UNPCKH and UNPCKL.
9831 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9832 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9833 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9834 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9835 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9836 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9837 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9838 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9840 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9844 // Check if the blend happens to exactly fit that of SHUFPD.
9846 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9849 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9850 // shuffle. However, if we have AVX2 and either inputs are already in place,
9851 // we will be able to shuffle even across lanes the other input in a single
9852 // instruction so skip this pattern.
9853 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9854 isShuffleMaskInputInPlace(1, Mask))))
9855 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9856 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9859 // If we have AVX2 then we always want to lower with a blend because an v4 we
9860 // can fully permute the elements.
9861 if (Subtarget->hasAVX2())
9862 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9865 // Otherwise fall back on generic lowering.
9866 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9869 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9871 /// This routine is only called when we have AVX2 and thus a reasonable
9872 /// instruction set for v4i64 shuffling..
9873 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9874 const X86Subtarget *Subtarget,
9875 SelectionDAG &DAG) {
9877 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9878 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9879 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9880 ArrayRef<int> Mask = SVOp->getMask();
9881 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9882 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9884 SmallVector<int, 4> WidenedMask;
9885 if (canWidenShuffleElements(Mask, WidenedMask))
9886 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9889 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9893 // Check for being able to broadcast a single element.
9894 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9895 Mask, Subtarget, DAG))
9898 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9899 // use lower latency instructions that will operate on both 128-bit lanes.
9900 SmallVector<int, 2> RepeatedMask;
9901 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9902 if (isSingleInputShuffleMask(Mask)) {
9903 int PSHUFDMask[] = {-1, -1, -1, -1};
9904 for (int i = 0; i < 2; ++i)
9905 if (RepeatedMask[i] >= 0) {
9906 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9907 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9909 return DAG.getBitcast(
9911 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9912 DAG.getBitcast(MVT::v8i32, V1),
9913 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9917 // AVX2 provides a direct instruction for permuting a single input across
9919 if (isSingleInputShuffleMask(Mask))
9920 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9921 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9923 // Try to use shift instructions.
9925 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9928 // Use dedicated unpack instructions for masks that match their pattern.
9929 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9930 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9931 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9932 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9933 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9934 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9935 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9936 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9938 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9939 // shuffle. However, if we have AVX2 and either inputs are already in place,
9940 // we will be able to shuffle even across lanes the other input in a single
9941 // instruction so skip this pattern.
9942 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9943 isShuffleMaskInputInPlace(1, Mask))))
9944 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9945 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9948 // Otherwise fall back on generic blend lowering.
9949 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9953 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9955 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9956 /// isn't available.
9957 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9958 const X86Subtarget *Subtarget,
9959 SelectionDAG &DAG) {
9961 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9962 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9963 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9964 ArrayRef<int> Mask = SVOp->getMask();
9965 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9967 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9971 // Check for being able to broadcast a single element.
9972 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9973 Mask, Subtarget, DAG))
9976 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9977 // options to efficiently lower the shuffle.
9978 SmallVector<int, 4> RepeatedMask;
9979 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9980 assert(RepeatedMask.size() == 4 &&
9981 "Repeated masks must be half the mask width!");
9983 // Use even/odd duplicate instructions for masks that match their pattern.
9984 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9985 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9986 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9987 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9989 if (isSingleInputShuffleMask(Mask))
9990 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9991 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9993 // Use dedicated unpack instructions for masks that match their pattern.
9994 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9995 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9996 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9997 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9998 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9999 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10000 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10001 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10003 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10004 // have already handled any direct blends. We also need to squash the
10005 // repeated mask into a simulated v4f32 mask.
10006 for (int i = 0; i < 4; ++i)
10007 if (RepeatedMask[i] >= 8)
10008 RepeatedMask[i] -= 4;
10009 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10012 // If we have a single input shuffle with different shuffle patterns in the
10013 // two 128-bit lanes use the variable mask to VPERMILPS.
10014 if (isSingleInputShuffleMask(Mask)) {
10015 SDValue VPermMask[8];
10016 for (int i = 0; i < 8; ++i)
10017 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10018 : DAG.getConstant(Mask[i], DL, MVT::i32);
10019 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10020 return DAG.getNode(
10021 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10022 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10024 if (Subtarget->hasAVX2())
10025 return DAG.getNode(
10026 X86ISD::VPERMV, DL, MVT::v8f32,
10027 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10028 MVT::v8i32, VPermMask)),
10031 // Otherwise, fall back.
10032 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10036 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10038 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10039 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10042 // If we have AVX2 then we always want to lower with a blend because at v8 we
10043 // can fully permute the elements.
10044 if (Subtarget->hasAVX2())
10045 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10048 // Otherwise fall back on generic lowering.
10049 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10052 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10054 /// This routine is only called when we have AVX2 and thus a reasonable
10055 /// instruction set for v8i32 shuffling..
10056 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10057 const X86Subtarget *Subtarget,
10058 SelectionDAG &DAG) {
10060 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10061 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10062 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10063 ArrayRef<int> Mask = SVOp->getMask();
10064 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10065 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10067 // Whenever we can lower this as a zext, that instruction is strictly faster
10068 // than any alternative. It also allows us to fold memory operands into the
10069 // shuffle in many cases.
10070 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10071 Mask, Subtarget, DAG))
10074 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10078 // Check for being able to broadcast a single element.
10079 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10080 Mask, Subtarget, DAG))
10083 // If the shuffle mask is repeated in each 128-bit lane we can use more
10084 // efficient instructions that mirror the shuffles across the two 128-bit
10086 SmallVector<int, 4> RepeatedMask;
10087 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10088 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10089 if (isSingleInputShuffleMask(Mask))
10090 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10091 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10093 // Use dedicated unpack instructions for masks that match their pattern.
10094 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10095 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10096 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10097 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10098 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10099 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10100 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10101 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10104 // Try to use shift instructions.
10105 if (SDValue Shift =
10106 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10109 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10110 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10113 // If the shuffle patterns aren't repeated but it is a single input, directly
10114 // generate a cross-lane VPERMD instruction.
10115 if (isSingleInputShuffleMask(Mask)) {
10116 SDValue VPermMask[8];
10117 for (int i = 0; i < 8; ++i)
10118 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10119 : DAG.getConstant(Mask[i], DL, MVT::i32);
10120 return DAG.getNode(
10121 X86ISD::VPERMV, DL, MVT::v8i32,
10122 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10125 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10127 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10128 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10131 // Otherwise fall back on generic blend lowering.
10132 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10136 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10138 /// This routine is only called when we have AVX2 and thus a reasonable
10139 /// instruction set for v16i16 shuffling..
10140 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10141 const X86Subtarget *Subtarget,
10142 SelectionDAG &DAG) {
10144 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10145 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10146 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10147 ArrayRef<int> Mask = SVOp->getMask();
10148 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10149 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10151 // Whenever we can lower this as a zext, that instruction is strictly faster
10152 // than any alternative. It also allows us to fold memory operands into the
10153 // shuffle in many cases.
10154 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10155 Mask, Subtarget, DAG))
10158 // Check for being able to broadcast a single element.
10159 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10160 Mask, Subtarget, DAG))
10163 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10167 // Use dedicated unpack instructions for masks that match their pattern.
10168 if (isShuffleEquivalent(V1, V2, Mask,
10169 {// First 128-bit lane:
10170 0, 16, 1, 17, 2, 18, 3, 19,
10171 // Second 128-bit lane:
10172 8, 24, 9, 25, 10, 26, 11, 27}))
10173 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10174 if (isShuffleEquivalent(V1, V2, Mask,
10175 {// First 128-bit lane:
10176 4, 20, 5, 21, 6, 22, 7, 23,
10177 // Second 128-bit lane:
10178 12, 28, 13, 29, 14, 30, 15, 31}))
10179 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10181 // Try to use shift instructions.
10182 if (SDValue Shift =
10183 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10186 // Try to use byte rotation instructions.
10187 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10188 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10191 if (isSingleInputShuffleMask(Mask)) {
10192 // There are no generalized cross-lane shuffle operations available on i16
10194 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10195 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10198 SmallVector<int, 8> RepeatedMask;
10199 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10200 // As this is a single-input shuffle, the repeated mask should be
10201 // a strictly valid v8i16 mask that we can pass through to the v8i16
10202 // lowering to handle even the v16 case.
10203 return lowerV8I16GeneralSingleInputVectorShuffle(
10204 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10207 SDValue PSHUFBMask[32];
10208 for (int i = 0; i < 16; ++i) {
10209 if (Mask[i] == -1) {
10210 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10214 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10215 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10216 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10217 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10219 return DAG.getBitcast(MVT::v16i16,
10220 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10221 DAG.getBitcast(MVT::v32i8, V1),
10222 DAG.getNode(ISD::BUILD_VECTOR, DL,
10223 MVT::v32i8, PSHUFBMask)));
10226 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10228 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10229 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10232 // Otherwise fall back on generic lowering.
10233 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10236 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10238 /// This routine is only called when we have AVX2 and thus a reasonable
10239 /// instruction set for v32i8 shuffling..
10240 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10241 const X86Subtarget *Subtarget,
10242 SelectionDAG &DAG) {
10244 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10245 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10247 ArrayRef<int> Mask = SVOp->getMask();
10248 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10249 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10251 // Whenever we can lower this as a zext, that instruction is strictly faster
10252 // than any alternative. It also allows us to fold memory operands into the
10253 // shuffle in many cases.
10254 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10255 Mask, Subtarget, DAG))
10258 // Check for being able to broadcast a single element.
10259 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10260 Mask, Subtarget, DAG))
10263 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10267 // Use dedicated unpack instructions for masks that match their pattern.
10268 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10270 if (isShuffleEquivalent(
10272 {// First 128-bit lane:
10273 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10274 // Second 128-bit lane:
10275 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10276 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10277 if (isShuffleEquivalent(
10279 {// First 128-bit lane:
10280 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10281 // Second 128-bit lane:
10282 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10283 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10285 // Try to use shift instructions.
10286 if (SDValue Shift =
10287 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10290 // Try to use byte rotation instructions.
10291 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10292 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10295 if (isSingleInputShuffleMask(Mask)) {
10296 // There are no generalized cross-lane shuffle operations available on i8
10298 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10299 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10302 SDValue PSHUFBMask[32];
10303 for (int i = 0; i < 32; ++i)
10306 ? DAG.getUNDEF(MVT::i8)
10307 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10310 return DAG.getNode(
10311 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10312 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10315 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10317 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10318 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10321 // Otherwise fall back on generic lowering.
10322 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10325 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10327 /// This routine either breaks down the specific type of a 256-bit x86 vector
10328 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10329 /// together based on the available instructions.
10330 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10331 MVT VT, const X86Subtarget *Subtarget,
10332 SelectionDAG &DAG) {
10334 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10335 ArrayRef<int> Mask = SVOp->getMask();
10337 // If we have a single input to the zero element, insert that into V1 if we
10338 // can do so cheaply.
10339 int NumElts = VT.getVectorNumElements();
10340 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10341 return M >= NumElts;
10344 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10345 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10346 DL, VT, V1, V2, Mask, Subtarget, DAG))
10349 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10350 // check for those subtargets here and avoid much of the subtarget querying in
10351 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10352 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10353 // floating point types there eventually, just immediately cast everything to
10354 // a float and operate entirely in that domain.
10355 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10356 int ElementBits = VT.getScalarSizeInBits();
10357 if (ElementBits < 32)
10358 // No floating point type available, decompose into 128-bit vectors.
10359 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10361 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10362 VT.getVectorNumElements());
10363 V1 = DAG.getBitcast(FpVT, V1);
10364 V2 = DAG.getBitcast(FpVT, V2);
10365 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10368 switch (VT.SimpleTy) {
10370 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10372 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10376 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10378 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10380 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10383 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10387 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10388 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10389 const X86Subtarget *Subtarget,
10390 SelectionDAG &DAG) {
10392 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10393 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10394 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10395 ArrayRef<int> Mask = SVOp->getMask();
10396 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10398 // X86 has dedicated unpack instructions that can handle specific blend
10399 // operations: UNPCKH and UNPCKL.
10400 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10401 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10402 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10403 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10405 // FIXME: Implement direct support for this type!
10406 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10409 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10410 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10411 const X86Subtarget *Subtarget,
10412 SelectionDAG &DAG) {
10414 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10415 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10416 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10417 ArrayRef<int> Mask = SVOp->getMask();
10418 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10420 // Use dedicated unpack instructions for masks that match their pattern.
10421 if (isShuffleEquivalent(V1, V2, Mask,
10422 {// First 128-bit lane.
10423 0, 16, 1, 17, 4, 20, 5, 21,
10424 // Second 128-bit lane.
10425 8, 24, 9, 25, 12, 28, 13, 29}))
10426 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10427 if (isShuffleEquivalent(V1, V2, Mask,
10428 {// First 128-bit lane.
10429 2, 18, 3, 19, 6, 22, 7, 23,
10430 // Second 128-bit lane.
10431 10, 26, 11, 27, 14, 30, 15, 31}))
10432 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10434 // FIXME: Implement direct support for this type!
10435 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10438 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10439 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10440 const X86Subtarget *Subtarget,
10441 SelectionDAG &DAG) {
10443 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10444 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10445 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10446 ArrayRef<int> Mask = SVOp->getMask();
10447 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10449 // X86 has dedicated unpack instructions that can handle specific blend
10450 // operations: UNPCKH and UNPCKL.
10451 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10452 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10453 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10454 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10456 // FIXME: Implement direct support for this type!
10457 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10460 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10461 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10462 const X86Subtarget *Subtarget,
10463 SelectionDAG &DAG) {
10465 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10466 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10467 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10468 ArrayRef<int> Mask = SVOp->getMask();
10469 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10471 // Use dedicated unpack instructions for masks that match their pattern.
10472 if (isShuffleEquivalent(V1, V2, Mask,
10473 {// First 128-bit lane.
10474 0, 16, 1, 17, 4, 20, 5, 21,
10475 // Second 128-bit lane.
10476 8, 24, 9, 25, 12, 28, 13, 29}))
10477 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10478 if (isShuffleEquivalent(V1, V2, Mask,
10479 {// First 128-bit lane.
10480 2, 18, 3, 19, 6, 22, 7, 23,
10481 // Second 128-bit lane.
10482 10, 26, 11, 27, 14, 30, 15, 31}))
10483 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10485 // FIXME: Implement direct support for this type!
10486 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10489 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10490 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491 const X86Subtarget *Subtarget,
10492 SelectionDAG &DAG) {
10494 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10495 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10496 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497 ArrayRef<int> Mask = SVOp->getMask();
10498 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10499 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10501 // FIXME: Implement direct support for this type!
10502 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10505 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10506 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10507 const X86Subtarget *Subtarget,
10508 SelectionDAG &DAG) {
10510 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10511 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10512 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10513 ArrayRef<int> Mask = SVOp->getMask();
10514 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10515 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10517 // FIXME: Implement direct support for this type!
10518 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10521 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10523 /// This routine either breaks down the specific type of a 512-bit x86 vector
10524 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10525 /// together based on the available instructions.
10526 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10527 MVT VT, const X86Subtarget *Subtarget,
10528 SelectionDAG &DAG) {
10530 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10531 ArrayRef<int> Mask = SVOp->getMask();
10532 assert(Subtarget->hasAVX512() &&
10533 "Cannot lower 512-bit vectors w/ basic ISA!");
10535 // Check for being able to broadcast a single element.
10536 if (SDValue Broadcast =
10537 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10540 // Dispatch to each element type for lowering. If we don't have supprot for
10541 // specific element type shuffles at 512 bits, immediately split them and
10542 // lower them. Each lowering routine of a given type is allowed to assume that
10543 // the requisite ISA extensions for that element type are available.
10544 switch (VT.SimpleTy) {
10546 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10548 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10550 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10552 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10554 if (Subtarget->hasBWI())
10555 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10558 if (Subtarget->hasBWI())
10559 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10563 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10566 // Otherwise fall back on splitting.
10567 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10570 /// \brief Top-level lowering for x86 vector shuffles.
10572 /// This handles decomposition, canonicalization, and lowering of all x86
10573 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10574 /// above in helper routines. The canonicalization attempts to widen shuffles
10575 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10576 /// s.t. only one of the two inputs needs to be tested, etc.
10577 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10578 SelectionDAG &DAG) {
10579 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580 ArrayRef<int> Mask = SVOp->getMask();
10581 SDValue V1 = Op.getOperand(0);
10582 SDValue V2 = Op.getOperand(1);
10583 MVT VT = Op.getSimpleValueType();
10584 int NumElements = VT.getVectorNumElements();
10587 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10589 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10590 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10591 if (V1IsUndef && V2IsUndef)
10592 return DAG.getUNDEF(VT);
10594 // When we create a shuffle node we put the UNDEF node to second operand,
10595 // but in some cases the first operand may be transformed to UNDEF.
10596 // In this case we should just commute the node.
10598 return DAG.getCommutedVectorShuffle(*SVOp);
10600 // Check for non-undef masks pointing at an undef vector and make the masks
10601 // undef as well. This makes it easier to match the shuffle based solely on
10605 if (M >= NumElements) {
10606 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10607 for (int &M : NewMask)
10608 if (M >= NumElements)
10610 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10613 // We actually see shuffles that are entirely re-arrangements of a set of
10614 // zero inputs. This mostly happens while decomposing complex shuffles into
10615 // simple ones. Directly lower these as a buildvector of zeros.
10616 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10617 if (Zeroable.all())
10618 return getZeroVector(VT, Subtarget, DAG, dl);
10620 // Try to collapse shuffles into using a vector type with fewer elements but
10621 // wider element types. We cap this to not form integers or floating point
10622 // elements wider than 64 bits, but it might be interesting to form i128
10623 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10624 SmallVector<int, 16> WidenedMask;
10625 if (VT.getScalarSizeInBits() < 64 &&
10626 canWidenShuffleElements(Mask, WidenedMask)) {
10627 MVT NewEltVT = VT.isFloatingPoint()
10628 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10629 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10630 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10631 // Make sure that the new vector type is legal. For example, v2f64 isn't
10633 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10634 V1 = DAG.getBitcast(NewVT, V1);
10635 V2 = DAG.getBitcast(NewVT, V2);
10636 return DAG.getBitcast(
10637 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10641 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10642 for (int M : SVOp->getMask())
10644 ++NumUndefElements;
10645 else if (M < NumElements)
10650 // Commute the shuffle as needed such that more elements come from V1 than
10651 // V2. This allows us to match the shuffle pattern strictly on how many
10652 // elements come from V1 without handling the symmetric cases.
10653 if (NumV2Elements > NumV1Elements)
10654 return DAG.getCommutedVectorShuffle(*SVOp);
10656 // When the number of V1 and V2 elements are the same, try to minimize the
10657 // number of uses of V2 in the low half of the vector. When that is tied,
10658 // ensure that the sum of indices for V1 is equal to or lower than the sum
10659 // indices for V2. When those are equal, try to ensure that the number of odd
10660 // indices for V1 is lower than the number of odd indices for V2.
10661 if (NumV1Elements == NumV2Elements) {
10662 int LowV1Elements = 0, LowV2Elements = 0;
10663 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10664 if (M >= NumElements)
10668 if (LowV2Elements > LowV1Elements) {
10669 return DAG.getCommutedVectorShuffle(*SVOp);
10670 } else if (LowV2Elements == LowV1Elements) {
10671 int SumV1Indices = 0, SumV2Indices = 0;
10672 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10673 if (SVOp->getMask()[i] >= NumElements)
10675 else if (SVOp->getMask()[i] >= 0)
10677 if (SumV2Indices < SumV1Indices) {
10678 return DAG.getCommutedVectorShuffle(*SVOp);
10679 } else if (SumV2Indices == SumV1Indices) {
10680 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10681 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10682 if (SVOp->getMask()[i] >= NumElements)
10683 NumV2OddIndices += i % 2;
10684 else if (SVOp->getMask()[i] >= 0)
10685 NumV1OddIndices += i % 2;
10686 if (NumV2OddIndices < NumV1OddIndices)
10687 return DAG.getCommutedVectorShuffle(*SVOp);
10692 // For each vector width, delegate to a specialized lowering routine.
10693 if (VT.getSizeInBits() == 128)
10694 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10696 if (VT.getSizeInBits() == 256)
10697 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10699 // Force AVX-512 vectors to be scalarized for now.
10700 // FIXME: Implement AVX-512 support!
10701 if (VT.getSizeInBits() == 512)
10702 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10704 llvm_unreachable("Unimplemented!");
10707 // This function assumes its argument is a BUILD_VECTOR of constants or
10708 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10710 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10711 unsigned &MaskValue) {
10713 unsigned NumElems = BuildVector->getNumOperands();
10714 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10715 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10716 unsigned NumElemsInLane = NumElems / NumLanes;
10718 // Blend for v16i16 should be symetric for the both lanes.
10719 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10720 SDValue EltCond = BuildVector->getOperand(i);
10721 SDValue SndLaneEltCond =
10722 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10724 int Lane1Cond = -1, Lane2Cond = -1;
10725 if (isa<ConstantSDNode>(EltCond))
10726 Lane1Cond = !isZero(EltCond);
10727 if (isa<ConstantSDNode>(SndLaneEltCond))
10728 Lane2Cond = !isZero(SndLaneEltCond);
10730 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10731 // Lane1Cond != 0, means we want the first argument.
10732 // Lane1Cond == 0, means we want the second argument.
10733 // The encoding of this argument is 0 for the first argument, 1
10734 // for the second. Therefore, invert the condition.
10735 MaskValue |= !Lane1Cond << i;
10736 else if (Lane1Cond < 0)
10737 MaskValue |= !Lane2Cond << i;
10744 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10745 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10746 const X86Subtarget *Subtarget,
10747 SelectionDAG &DAG) {
10748 SDValue Cond = Op.getOperand(0);
10749 SDValue LHS = Op.getOperand(1);
10750 SDValue RHS = Op.getOperand(2);
10752 MVT VT = Op.getSimpleValueType();
10754 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10756 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10758 // Only non-legal VSELECTs reach this lowering, convert those into generic
10759 // shuffles and re-use the shuffle lowering path for blends.
10760 SmallVector<int, 32> Mask;
10761 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10762 SDValue CondElt = CondBV->getOperand(i);
10764 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10766 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10769 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10770 // A vselect where all conditions and data are constants can be optimized into
10771 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10772 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10773 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10774 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10777 // Try to lower this to a blend-style vector shuffle. This can handle all
10778 // constant condition cases.
10779 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10782 // Variable blends are only legal from SSE4.1 onward.
10783 if (!Subtarget->hasSSE41())
10786 // Only some types will be legal on some subtargets. If we can emit a legal
10787 // VSELECT-matching blend, return Op, and but if we need to expand, return
10789 switch (Op.getSimpleValueType().SimpleTy) {
10791 // Most of the vector types have blends past SSE4.1.
10795 // The byte blends for AVX vectors were introduced only in AVX2.
10796 if (Subtarget->hasAVX2())
10803 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10804 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10807 // FIXME: We should custom lower this by fixing the condition and using i8
10813 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10814 MVT VT = Op.getSimpleValueType();
10817 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10820 if (VT.getSizeInBits() == 8) {
10821 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10822 Op.getOperand(0), Op.getOperand(1));
10823 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10824 DAG.getValueType(VT));
10825 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10828 if (VT.getSizeInBits() == 16) {
10829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10830 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10832 return DAG.getNode(
10833 ISD::TRUNCATE, dl, MVT::i16,
10834 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10835 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10836 Op.getOperand(1)));
10837 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10838 Op.getOperand(0), Op.getOperand(1));
10839 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10840 DAG.getValueType(VT));
10841 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10844 if (VT == MVT::f32) {
10845 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10846 // the result back to FR32 register. It's only worth matching if the
10847 // result has a single use which is a store or a bitcast to i32. And in
10848 // the case of a store, it's not worth it if the index is a constant 0,
10849 // because a MOVSSmr can be used instead, which is smaller and faster.
10850 if (!Op.hasOneUse())
10852 SDNode *User = *Op.getNode()->use_begin();
10853 if ((User->getOpcode() != ISD::STORE ||
10854 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10855 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10856 (User->getOpcode() != ISD::BITCAST ||
10857 User->getValueType(0) != MVT::i32))
10859 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10860 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10862 return DAG.getBitcast(MVT::f32, Extract);
10865 if (VT == MVT::i32 || VT == MVT::i64) {
10866 // ExtractPS/pextrq works with constant index.
10867 if (isa<ConstantSDNode>(Op.getOperand(1)))
10873 /// Extract one bit from mask vector, like v16i1 or v8i1.
10874 /// AVX-512 feature.
10876 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10877 SDValue Vec = Op.getOperand(0);
10879 MVT VecVT = Vec.getSimpleValueType();
10880 SDValue Idx = Op.getOperand(1);
10881 MVT EltVT = Op.getSimpleValueType();
10883 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10884 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10885 "Unexpected vector type in ExtractBitFromMaskVector");
10887 // variable index can't be handled in mask registers,
10888 // extend vector to VR512
10889 if (!isa<ConstantSDNode>(Idx)) {
10890 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10891 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10892 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10893 ExtVT.getVectorElementType(), Ext, Idx);
10894 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10897 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10898 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10899 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10900 rc = getRegClassFor(MVT::v16i1);
10901 unsigned MaxSift = rc->getSize()*8 - 1;
10902 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10903 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10904 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10905 DAG.getConstant(MaxSift, dl, MVT::i8));
10906 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10907 DAG.getIntPtrConstant(0, dl));
10911 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10912 SelectionDAG &DAG) const {
10914 SDValue Vec = Op.getOperand(0);
10915 MVT VecVT = Vec.getSimpleValueType();
10916 SDValue Idx = Op.getOperand(1);
10918 if (Op.getSimpleValueType() == MVT::i1)
10919 return ExtractBitFromMaskVector(Op, DAG);
10921 if (!isa<ConstantSDNode>(Idx)) {
10922 if (VecVT.is512BitVector() ||
10923 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10924 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10927 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10928 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10929 MaskEltVT.getSizeInBits());
10931 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10932 auto PtrVT = getPointerTy(DAG.getDataLayout());
10933 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10934 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10935 DAG.getConstant(0, dl, PtrVT));
10936 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10937 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10938 DAG.getConstant(0, dl, PtrVT));
10943 // If this is a 256-bit vector result, first extract the 128-bit vector and
10944 // then extract the element from the 128-bit vector.
10945 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10947 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10948 // Get the 128-bit vector.
10949 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10950 MVT EltVT = VecVT.getVectorElementType();
10952 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10954 //if (IdxVal >= NumElems/2)
10955 // IdxVal -= NumElems/2;
10956 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10957 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10958 DAG.getConstant(IdxVal, dl, MVT::i32));
10961 assert(VecVT.is128BitVector() && "Unexpected vector length");
10963 if (Subtarget->hasSSE41())
10964 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10967 MVT VT = Op.getSimpleValueType();
10968 // TODO: handle v16i8.
10969 if (VT.getSizeInBits() == 16) {
10970 SDValue Vec = Op.getOperand(0);
10971 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10973 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10974 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10975 DAG.getBitcast(MVT::v4i32, Vec),
10976 Op.getOperand(1)));
10977 // Transform it so it match pextrw which produces a 32-bit result.
10978 MVT EltVT = MVT::i32;
10979 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10980 Op.getOperand(0), Op.getOperand(1));
10981 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10982 DAG.getValueType(VT));
10983 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10986 if (VT.getSizeInBits() == 32) {
10987 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10991 // SHUFPS the element to the lowest double word, then movss.
10992 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10993 MVT VVT = Op.getOperand(0).getSimpleValueType();
10994 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10995 DAG.getUNDEF(VVT), Mask);
10996 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10997 DAG.getIntPtrConstant(0, dl));
11000 if (VT.getSizeInBits() == 64) {
11001 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11002 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11003 // to match extract_elt for f64.
11004 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11008 // UNPCKHPD the element to the lowest double word, then movsd.
11009 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11010 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11011 int Mask[2] = { 1, -1 };
11012 MVT VVT = Op.getOperand(0).getSimpleValueType();
11013 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11014 DAG.getUNDEF(VVT), Mask);
11015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11016 DAG.getIntPtrConstant(0, dl));
11022 /// Insert one bit to mask vector, like v16i1 or v8i1.
11023 /// AVX-512 feature.
11025 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11027 SDValue Vec = Op.getOperand(0);
11028 SDValue Elt = Op.getOperand(1);
11029 SDValue Idx = Op.getOperand(2);
11030 MVT VecVT = Vec.getSimpleValueType();
11032 if (!isa<ConstantSDNode>(Idx)) {
11033 // Non constant index. Extend source and destination,
11034 // insert element and then truncate the result.
11035 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11036 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11037 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11038 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11039 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11040 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11043 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11044 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11046 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11047 DAG.getConstant(IdxVal, dl, MVT::i8));
11048 if (Vec.getOpcode() == ISD::UNDEF)
11050 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11053 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11054 SelectionDAG &DAG) const {
11055 MVT VT = Op.getSimpleValueType();
11056 MVT EltVT = VT.getVectorElementType();
11058 if (EltVT == MVT::i1)
11059 return InsertBitToMaskVector(Op, DAG);
11062 SDValue N0 = Op.getOperand(0);
11063 SDValue N1 = Op.getOperand(1);
11064 SDValue N2 = Op.getOperand(2);
11065 if (!isa<ConstantSDNode>(N2))
11067 auto *N2C = cast<ConstantSDNode>(N2);
11068 unsigned IdxVal = N2C->getZExtValue();
11070 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11071 // into that, and then insert the subvector back into the result.
11072 if (VT.is256BitVector() || VT.is512BitVector()) {
11073 // With a 256-bit vector, we can insert into the zero element efficiently
11074 // using a blend if we have AVX or AVX2 and the right data type.
11075 if (VT.is256BitVector() && IdxVal == 0) {
11076 // TODO: It is worthwhile to cast integer to floating point and back
11077 // and incur a domain crossing penalty if that's what we'll end up
11078 // doing anyway after extracting to a 128-bit vector.
11079 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11080 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11081 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11082 N2 = DAG.getIntPtrConstant(1, dl);
11083 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11087 // Get the desired 128-bit vector chunk.
11088 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11090 // Insert the element into the desired chunk.
11091 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11092 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11094 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11095 DAG.getConstant(IdxIn128, dl, MVT::i32));
11097 // Insert the changed part back into the bigger vector
11098 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11100 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11102 if (Subtarget->hasSSE41()) {
11103 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11105 if (VT == MVT::v8i16) {
11106 Opc = X86ISD::PINSRW;
11108 assert(VT == MVT::v16i8);
11109 Opc = X86ISD::PINSRB;
11112 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11114 if (N1.getValueType() != MVT::i32)
11115 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11116 if (N2.getValueType() != MVT::i32)
11117 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11118 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11121 if (EltVT == MVT::f32) {
11122 // Bits [7:6] of the constant are the source select. This will always be
11123 // zero here. The DAG Combiner may combine an extract_elt index into
11124 // these bits. For example (insert (extract, 3), 2) could be matched by
11125 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11126 // Bits [5:4] of the constant are the destination select. This is the
11127 // value of the incoming immediate.
11128 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11129 // combine either bitwise AND or insert of float 0.0 to set these bits.
11131 const Function *F = DAG.getMachineFunction().getFunction();
11132 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11133 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11134 // If this is an insertion of 32-bits into the low 32-bits of
11135 // a vector, we prefer to generate a blend with immediate rather
11136 // than an insertps. Blends are simpler operations in hardware and so
11137 // will always have equal or better performance than insertps.
11138 // But if optimizing for size and there's a load folding opportunity,
11139 // generate insertps because blendps does not have a 32-bit memory
11141 N2 = DAG.getIntPtrConstant(1, dl);
11142 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11143 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11145 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11146 // Create this as a scalar to vector..
11147 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11148 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11151 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11152 // PINSR* works with constant index.
11157 if (EltVT == MVT::i8)
11160 if (EltVT.getSizeInBits() == 16) {
11161 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11162 // as its second argument.
11163 if (N1.getValueType() != MVT::i32)
11164 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11165 if (N2.getValueType() != MVT::i32)
11166 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11167 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11172 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11174 MVT OpVT = Op.getSimpleValueType();
11176 // If this is a 256-bit vector result, first insert into a 128-bit
11177 // vector and then insert into the 256-bit vector.
11178 if (!OpVT.is128BitVector()) {
11179 // Insert into a 128-bit vector.
11180 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11181 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11182 OpVT.getVectorNumElements() / SizeFactor);
11184 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11186 // Insert the 128-bit vector.
11187 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11190 if (OpVT == MVT::v1i64 &&
11191 Op.getOperand(0).getValueType() == MVT::i64)
11192 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11194 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11195 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11196 return DAG.getBitcast(
11197 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11200 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11201 // a simple subregister reference or explicit instructions to grab
11202 // upper bits of a vector.
11203 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11204 SelectionDAG &DAG) {
11206 SDValue In = Op.getOperand(0);
11207 SDValue Idx = Op.getOperand(1);
11208 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11209 MVT ResVT = Op.getSimpleValueType();
11210 MVT InVT = In.getSimpleValueType();
11212 if (Subtarget->hasFp256()) {
11213 if (ResVT.is128BitVector() &&
11214 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11215 isa<ConstantSDNode>(Idx)) {
11216 return Extract128BitVector(In, IdxVal, DAG, dl);
11218 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11219 isa<ConstantSDNode>(Idx)) {
11220 return Extract256BitVector(In, IdxVal, DAG, dl);
11226 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11227 // simple superregister reference or explicit instructions to insert
11228 // the upper bits of a vector.
11229 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11230 SelectionDAG &DAG) {
11231 if (!Subtarget->hasAVX())
11235 SDValue Vec = Op.getOperand(0);
11236 SDValue SubVec = Op.getOperand(1);
11237 SDValue Idx = Op.getOperand(2);
11239 if (!isa<ConstantSDNode>(Idx))
11242 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11243 MVT OpVT = Op.getSimpleValueType();
11244 MVT SubVecVT = SubVec.getSimpleValueType();
11246 // Fold two 16-byte subvector loads into one 32-byte load:
11247 // (insert_subvector (insert_subvector undef, (load addr), 0),
11248 // (load addr + 16), Elts/2)
11250 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11251 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11252 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11253 !Subtarget->isUnalignedMem32Slow()) {
11254 SDValue SubVec2 = Vec.getOperand(1);
11255 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11256 if (Idx2->getZExtValue() == 0) {
11257 SDValue Ops[] = { SubVec2, SubVec };
11258 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11264 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11265 SubVecVT.is128BitVector())
11266 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11268 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11269 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11271 if (OpVT.getVectorElementType() == MVT::i1) {
11272 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11274 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11275 SDValue Undef = DAG.getUNDEF(OpVT);
11276 unsigned NumElems = OpVT.getVectorNumElements();
11277 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11279 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11280 // Zero upper bits of the Vec
11281 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11282 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11284 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11286 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11287 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11290 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11292 // Zero upper bits of the Vec2
11293 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11294 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11295 // Zero lower bits of the Vec
11296 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11297 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11298 // Merge them together
11299 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11305 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11306 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11307 // one of the above mentioned nodes. It has to be wrapped because otherwise
11308 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11309 // be used to form addressing mode. These wrapped nodes will be selected
11312 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11313 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11315 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11316 // global base reg.
11317 unsigned char OpFlag = 0;
11318 unsigned WrapperKind = X86ISD::Wrapper;
11319 CodeModel::Model M = DAG.getTarget().getCodeModel();
11321 if (Subtarget->isPICStyleRIPRel() &&
11322 (M == CodeModel::Small || M == CodeModel::Kernel))
11323 WrapperKind = X86ISD::WrapperRIP;
11324 else if (Subtarget->isPICStyleGOT())
11325 OpFlag = X86II::MO_GOTOFF;
11326 else if (Subtarget->isPICStyleStubPIC())
11327 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11329 auto PtrVT = getPointerTy(DAG.getDataLayout());
11330 SDValue Result = DAG.getTargetConstantPool(
11331 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11333 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11334 // With PIC, the address is actually $g + Offset.
11337 DAG.getNode(ISD::ADD, DL, PtrVT,
11338 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11344 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11345 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11347 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11348 // global base reg.
11349 unsigned char OpFlag = 0;
11350 unsigned WrapperKind = X86ISD::Wrapper;
11351 CodeModel::Model M = DAG.getTarget().getCodeModel();
11353 if (Subtarget->isPICStyleRIPRel() &&
11354 (M == CodeModel::Small || M == CodeModel::Kernel))
11355 WrapperKind = X86ISD::WrapperRIP;
11356 else if (Subtarget->isPICStyleGOT())
11357 OpFlag = X86II::MO_GOTOFF;
11358 else if (Subtarget->isPICStyleStubPIC())
11359 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11361 auto PtrVT = getPointerTy(DAG.getDataLayout());
11362 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11364 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11366 // With PIC, the address is actually $g + Offset.
11369 DAG.getNode(ISD::ADD, DL, PtrVT,
11370 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11376 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11377 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11379 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11380 // global base reg.
11381 unsigned char OpFlag = 0;
11382 unsigned WrapperKind = X86ISD::Wrapper;
11383 CodeModel::Model M = DAG.getTarget().getCodeModel();
11385 if (Subtarget->isPICStyleRIPRel() &&
11386 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11387 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11388 OpFlag = X86II::MO_GOTPCREL;
11389 WrapperKind = X86ISD::WrapperRIP;
11390 } else if (Subtarget->isPICStyleGOT()) {
11391 OpFlag = X86II::MO_GOT;
11392 } else if (Subtarget->isPICStyleStubPIC()) {
11393 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11394 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11395 OpFlag = X86II::MO_DARWIN_NONLAZY;
11398 auto PtrVT = getPointerTy(DAG.getDataLayout());
11399 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11402 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11404 // With PIC, the address is actually $g + Offset.
11405 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11406 !Subtarget->is64Bit()) {
11408 DAG.getNode(ISD::ADD, DL, PtrVT,
11409 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11412 // For symbols that require a load from a stub to get the address, emit the
11414 if (isGlobalStubReference(OpFlag))
11415 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11416 MachinePointerInfo::getGOT(), false, false, false, 0);
11422 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11423 // Create the TargetBlockAddressAddress node.
11424 unsigned char OpFlags =
11425 Subtarget->ClassifyBlockAddressReference();
11426 CodeModel::Model M = DAG.getTarget().getCodeModel();
11427 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11428 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11430 auto PtrVT = getPointerTy(DAG.getDataLayout());
11431 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11433 if (Subtarget->isPICStyleRIPRel() &&
11434 (M == CodeModel::Small || M == CodeModel::Kernel))
11435 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11437 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11439 // With PIC, the address is actually $g + Offset.
11440 if (isGlobalRelativeToPICBase(OpFlags)) {
11441 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11442 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11449 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11450 int64_t Offset, SelectionDAG &DAG) const {
11451 // Create the TargetGlobalAddress node, folding in the constant
11452 // offset if it is legal.
11453 unsigned char OpFlags =
11454 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11455 CodeModel::Model M = DAG.getTarget().getCodeModel();
11456 auto PtrVT = getPointerTy(DAG.getDataLayout());
11458 if (OpFlags == X86II::MO_NO_FLAG &&
11459 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11460 // A direct static reference to a global.
11461 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11464 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11467 if (Subtarget->isPICStyleRIPRel() &&
11468 (M == CodeModel::Small || M == CodeModel::Kernel))
11469 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11471 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11473 // With PIC, the address is actually $g + Offset.
11474 if (isGlobalRelativeToPICBase(OpFlags)) {
11475 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11476 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11479 // For globals that require a load from a stub to get the address, emit the
11481 if (isGlobalStubReference(OpFlags))
11482 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11483 MachinePointerInfo::getGOT(), false, false, false, 0);
11485 // If there was a non-zero offset that we didn't fold, create an explicit
11486 // addition for it.
11488 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11489 DAG.getConstant(Offset, dl, PtrVT));
11495 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11496 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11497 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11498 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11502 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11503 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11504 unsigned char OperandFlags, bool LocalDynamic = false) {
11505 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11506 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11508 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11509 GA->getValueType(0),
11513 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11517 SDValue Ops[] = { Chain, TGA, *InFlag };
11518 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11520 SDValue Ops[] = { Chain, TGA };
11521 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11524 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11525 MFI->setAdjustsStack(true);
11526 MFI->setHasCalls(true);
11528 SDValue Flag = Chain.getValue(1);
11529 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11532 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11534 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11537 SDLoc dl(GA); // ? function entry point might be better
11538 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11539 DAG.getNode(X86ISD::GlobalBaseReg,
11540 SDLoc(), PtrVT), InFlag);
11541 InFlag = Chain.getValue(1);
11543 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11546 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11548 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11550 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11551 X86::RAX, X86II::MO_TLSGD);
11554 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11560 // Get the start address of the TLS block for this module.
11561 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11562 .getInfo<X86MachineFunctionInfo>();
11563 MFI->incNumLocalDynamicTLSAccesses();
11567 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11568 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11571 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11572 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11573 InFlag = Chain.getValue(1);
11574 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11575 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11578 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11582 unsigned char OperandFlags = X86II::MO_DTPOFF;
11583 unsigned WrapperKind = X86ISD::Wrapper;
11584 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11585 GA->getValueType(0),
11586 GA->getOffset(), OperandFlags);
11587 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11589 // Add x@dtpoff with the base.
11590 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11593 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11594 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11595 const EVT PtrVT, TLSModel::Model model,
11596 bool is64Bit, bool isPIC) {
11599 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11600 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11601 is64Bit ? 257 : 256));
11603 SDValue ThreadPointer =
11604 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11605 MachinePointerInfo(Ptr), false, false, false, 0);
11607 unsigned char OperandFlags = 0;
11608 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11610 unsigned WrapperKind = X86ISD::Wrapper;
11611 if (model == TLSModel::LocalExec) {
11612 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11613 } else if (model == TLSModel::InitialExec) {
11615 OperandFlags = X86II::MO_GOTTPOFF;
11616 WrapperKind = X86ISD::WrapperRIP;
11618 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11621 llvm_unreachable("Unexpected model");
11624 // emit "addl x@ntpoff,%eax" (local exec)
11625 // or "addl x@indntpoff,%eax" (initial exec)
11626 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11628 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11629 GA->getOffset(), OperandFlags);
11630 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11632 if (model == TLSModel::InitialExec) {
11633 if (isPIC && !is64Bit) {
11634 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11635 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11639 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11640 MachinePointerInfo::getGOT(), false, false, false, 0);
11643 // The address of the thread local variable is the add of the thread
11644 // pointer with the offset of the variable.
11645 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11649 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11651 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11652 const GlobalValue *GV = GA->getGlobal();
11653 auto PtrVT = getPointerTy(DAG.getDataLayout());
11655 if (Subtarget->isTargetELF()) {
11656 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11658 case TLSModel::GeneralDynamic:
11659 if (Subtarget->is64Bit())
11660 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11661 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11662 case TLSModel::LocalDynamic:
11663 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11664 Subtarget->is64Bit());
11665 case TLSModel::InitialExec:
11666 case TLSModel::LocalExec:
11667 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11668 DAG.getTarget().getRelocationModel() ==
11671 llvm_unreachable("Unknown TLS model.");
11674 if (Subtarget->isTargetDarwin()) {
11675 // Darwin only has one model of TLS. Lower to that.
11676 unsigned char OpFlag = 0;
11677 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11678 X86ISD::WrapperRIP : X86ISD::Wrapper;
11680 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11681 // global base reg.
11682 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11683 !Subtarget->is64Bit();
11685 OpFlag = X86II::MO_TLVP_PIC_BASE;
11687 OpFlag = X86II::MO_TLVP;
11689 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11690 GA->getValueType(0),
11691 GA->getOffset(), OpFlag);
11692 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11694 // With PIC32, the address is actually $g + Offset.
11696 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11697 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11700 // Lowering the machine isd will make sure everything is in the right
11702 SDValue Chain = DAG.getEntryNode();
11703 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11704 SDValue Args[] = { Chain, Offset };
11705 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11707 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11708 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11709 MFI->setAdjustsStack(true);
11711 // And our return value (tls address) is in the standard call return value
11713 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11714 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11717 if (Subtarget->isTargetKnownWindowsMSVC() ||
11718 Subtarget->isTargetWindowsGNU()) {
11719 // Just use the implicit TLS architecture
11720 // Need to generate someting similar to:
11721 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11723 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11724 // mov rcx, qword [rdx+rcx*8]
11725 // mov eax, .tls$:tlsvar
11726 // [rax+rcx] contains the address
11727 // Windows 64bit: gs:0x58
11728 // Windows 32bit: fs:__tls_array
11731 SDValue Chain = DAG.getEntryNode();
11733 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11734 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11735 // use its literal value of 0x2C.
11736 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11737 ? Type::getInt8PtrTy(*DAG.getContext(),
11739 : Type::getInt32PtrTy(*DAG.getContext(),
11742 SDValue TlsArray = Subtarget->is64Bit()
11743 ? DAG.getIntPtrConstant(0x58, dl)
11744 : (Subtarget->isTargetWindowsGNU()
11745 ? DAG.getIntPtrConstant(0x2C, dl)
11746 : DAG.getExternalSymbol("_tls_array", PtrVT));
11748 SDValue ThreadPointer =
11749 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11753 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11754 res = ThreadPointer;
11756 // Load the _tls_index variable
11757 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11758 if (Subtarget->is64Bit())
11759 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11760 MachinePointerInfo(), MVT::i32, false, false,
11763 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11766 auto &DL = DAG.getDataLayout();
11768 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11769 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11771 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11774 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11777 // Get the offset of start of .tls section
11778 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11779 GA->getValueType(0),
11780 GA->getOffset(), X86II::MO_SECREL);
11781 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11783 // The address of the thread local variable is the add of the thread
11784 // pointer with the offset of the variable.
11785 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11788 llvm_unreachable("TLS not implemented for this target.");
11791 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11792 /// and take a 2 x i32 value to shift plus a shift amount.
11793 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11794 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11795 MVT VT = Op.getSimpleValueType();
11796 unsigned VTBits = VT.getSizeInBits();
11798 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11799 SDValue ShOpLo = Op.getOperand(0);
11800 SDValue ShOpHi = Op.getOperand(1);
11801 SDValue ShAmt = Op.getOperand(2);
11802 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11803 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11805 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11806 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11807 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11808 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11809 : DAG.getConstant(0, dl, VT);
11811 SDValue Tmp2, Tmp3;
11812 if (Op.getOpcode() == ISD::SHL_PARTS) {
11813 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11814 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11816 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11817 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11820 // If the shift amount is larger or equal than the width of a part we can't
11821 // rely on the results of shld/shrd. Insert a test and select the appropriate
11822 // values for large shift amounts.
11823 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11824 DAG.getConstant(VTBits, dl, MVT::i8));
11825 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11826 AndNode, DAG.getConstant(0, dl, MVT::i8));
11829 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11830 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11831 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11833 if (Op.getOpcode() == ISD::SHL_PARTS) {
11834 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11835 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11837 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11838 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11841 SDValue Ops[2] = { Lo, Hi };
11842 return DAG.getMergeValues(Ops, dl);
11845 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11846 SelectionDAG &DAG) const {
11847 SDValue Src = Op.getOperand(0);
11848 MVT SrcVT = Src.getSimpleValueType();
11849 MVT VT = Op.getSimpleValueType();
11852 if (SrcVT.isVector()) {
11853 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11854 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11855 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11856 DAG.getUNDEF(SrcVT)));
11858 if (SrcVT.getVectorElementType() == MVT::i1) {
11859 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11860 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11861 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11866 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11867 "Unknown SINT_TO_FP to lower!");
11869 // These are really Legal; return the operand so the caller accepts it as
11871 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11873 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11874 Subtarget->is64Bit()) {
11878 unsigned Size = SrcVT.getSizeInBits()/8;
11879 MachineFunction &MF = DAG.getMachineFunction();
11880 auto PtrVT = getPointerTy(MF.getDataLayout());
11881 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11882 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11883 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11885 MachinePointerInfo::getFixedStack(SSFI),
11887 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11890 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11892 SelectionDAG &DAG) const {
11896 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11898 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11900 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11902 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11904 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11905 MachineMemOperand *MMO;
11907 int SSFI = FI->getIndex();
11909 DAG.getMachineFunction()
11910 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11911 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11913 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11914 StackSlot = StackSlot.getOperand(1);
11916 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11917 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11919 Tys, Ops, SrcVT, MMO);
11922 Chain = Result.getValue(1);
11923 SDValue InFlag = Result.getValue(2);
11925 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11926 // shouldn't be necessary except that RFP cannot be live across
11927 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11928 MachineFunction &MF = DAG.getMachineFunction();
11929 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11930 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11931 auto PtrVT = getPointerTy(MF.getDataLayout());
11932 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11933 Tys = DAG.getVTList(MVT::Other);
11935 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11937 MachineMemOperand *MMO =
11938 DAG.getMachineFunction()
11939 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11940 MachineMemOperand::MOStore, SSFISize, SSFISize);
11942 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11943 Ops, Op.getValueType(), MMO);
11944 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11945 MachinePointerInfo::getFixedStack(SSFI),
11946 false, false, false, 0);
11952 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11953 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11954 SelectionDAG &DAG) const {
11955 // This algorithm is not obvious. Here it is what we're trying to output:
11958 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11959 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11961 haddpd %xmm0, %xmm0
11963 pshufd $0x4e, %xmm0, %xmm1
11969 LLVMContext *Context = DAG.getContext();
11971 // Build some magic constants.
11972 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11973 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11974 auto PtrVT = getPointerTy(DAG.getDataLayout());
11975 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11977 SmallVector<Constant*,2> CV1;
11979 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11980 APInt(64, 0x4330000000000000ULL))));
11982 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11983 APInt(64, 0x4530000000000000ULL))));
11984 Constant *C1 = ConstantVector::get(CV1);
11985 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11987 // Load the 64-bit value into an XMM register.
11988 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11990 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11991 MachinePointerInfo::getConstantPool(),
11992 false, false, false, 16);
11994 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11996 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11997 MachinePointerInfo::getConstantPool(),
11998 false, false, false, 16);
11999 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12000 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12003 if (Subtarget->hasSSE3()) {
12004 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12005 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12007 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12008 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12010 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12011 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12014 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12015 DAG.getIntPtrConstant(0, dl));
12018 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12019 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12020 SelectionDAG &DAG) const {
12022 // FP constant to bias correct the final result.
12023 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12026 // Load the 32-bit value into an XMM register.
12027 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12030 // Zero out the upper parts of the register.
12031 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12033 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12034 DAG.getBitcast(MVT::v2f64, Load),
12035 DAG.getIntPtrConstant(0, dl));
12037 // Or the load with the bias.
12038 SDValue Or = DAG.getNode(
12039 ISD::OR, dl, MVT::v2i64,
12040 DAG.getBitcast(MVT::v2i64,
12041 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12042 DAG.getBitcast(MVT::v2i64,
12043 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12045 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12046 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12048 // Subtract the bias.
12049 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12051 // Handle final rounding.
12052 EVT DestVT = Op.getValueType();
12054 if (DestVT.bitsLT(MVT::f64))
12055 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12056 DAG.getIntPtrConstant(0, dl));
12057 if (DestVT.bitsGT(MVT::f64))
12058 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12060 // Handle final rounding.
12064 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12065 const X86Subtarget &Subtarget) {
12066 // The algorithm is the following:
12067 // #ifdef __SSE4_1__
12068 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12069 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12070 // (uint4) 0x53000000, 0xaa);
12072 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12073 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12075 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12076 // return (float4) lo + fhi;
12079 SDValue V = Op->getOperand(0);
12080 EVT VecIntVT = V.getValueType();
12081 bool Is128 = VecIntVT == MVT::v4i32;
12082 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12083 // If we convert to something else than the supported type, e.g., to v4f64,
12085 if (VecFloatVT != Op->getValueType(0))
12088 unsigned NumElts = VecIntVT.getVectorNumElements();
12089 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12090 "Unsupported custom type");
12091 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12093 // In the #idef/#else code, we have in common:
12094 // - The vector of constants:
12100 // Create the splat vector for 0x4b000000.
12101 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12102 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12103 CstLow, CstLow, CstLow, CstLow};
12104 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12105 makeArrayRef(&CstLowArray[0], NumElts));
12106 // Create the splat vector for 0x53000000.
12107 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12108 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12109 CstHigh, CstHigh, CstHigh, CstHigh};
12110 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12111 makeArrayRef(&CstHighArray[0], NumElts));
12113 // Create the right shift.
12114 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12115 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12116 CstShift, CstShift, CstShift, CstShift};
12117 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12118 makeArrayRef(&CstShiftArray[0], NumElts));
12119 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12122 if (Subtarget.hasSSE41()) {
12123 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12124 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12125 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12126 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12127 // Low will be bitcasted right away, so do not bother bitcasting back to its
12129 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12130 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12131 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12132 // (uint4) 0x53000000, 0xaa);
12133 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12134 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12135 // High will be bitcasted right away, so do not bother bitcasting back to
12136 // its original type.
12137 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12138 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12140 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12141 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12142 CstMask, CstMask, CstMask);
12143 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12144 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12145 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12147 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12148 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12151 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12152 SDValue CstFAdd = DAG.getConstantFP(
12153 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12154 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12155 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12156 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12157 makeArrayRef(&CstFAddArray[0], NumElts));
12159 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12160 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12162 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12163 // return (float4) lo + fhi;
12164 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12165 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12168 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12169 SelectionDAG &DAG) const {
12170 SDValue N0 = Op.getOperand(0);
12171 MVT SVT = N0.getSimpleValueType();
12174 switch (SVT.SimpleTy) {
12176 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12181 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12182 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12183 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12187 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12190 if (Subtarget->hasAVX512())
12191 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12192 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12194 llvm_unreachable(nullptr);
12197 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12198 SelectionDAG &DAG) const {
12199 SDValue N0 = Op.getOperand(0);
12201 auto PtrVT = getPointerTy(DAG.getDataLayout());
12203 if (Op.getValueType().isVector())
12204 return lowerUINT_TO_FP_vec(Op, DAG);
12206 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12207 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12208 // the optimization here.
12209 if (DAG.SignBitIsZero(N0))
12210 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12212 MVT SrcVT = N0.getSimpleValueType();
12213 MVT DstVT = Op.getSimpleValueType();
12214 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12215 return LowerUINT_TO_FP_i64(Op, DAG);
12216 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12217 return LowerUINT_TO_FP_i32(Op, DAG);
12218 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12221 // Make a 64-bit buffer, and use it to build an FILD.
12222 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12223 if (SrcVT == MVT::i32) {
12224 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12225 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12226 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12227 StackSlot, MachinePointerInfo(),
12229 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12230 OffsetSlot, MachinePointerInfo(),
12232 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12236 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12237 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12238 StackSlot, MachinePointerInfo(),
12240 // For i64 source, we need to add the appropriate power of 2 if the input
12241 // was negative. This is the same as the optimization in
12242 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12243 // we must be careful to do the computation in x87 extended precision, not
12244 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12245 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12246 MachineMemOperand *MMO =
12247 DAG.getMachineFunction()
12248 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12249 MachineMemOperand::MOLoad, 8, 8);
12251 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12252 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12253 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12256 APInt FF(32, 0x5F800000ULL);
12258 // Check whether the sign bit is set.
12259 SDValue SignSet = DAG.getSetCC(
12260 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12261 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12263 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12264 SDValue FudgePtr = DAG.getConstantPool(
12265 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12267 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12268 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12269 SDValue Four = DAG.getIntPtrConstant(4, dl);
12270 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12272 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12274 // Load the value out, extending it from f32 to f80.
12275 // FIXME: Avoid the extend by constructing the right constant pool?
12276 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12277 FudgePtr, MachinePointerInfo::getConstantPool(),
12278 MVT::f32, false, false, false, 4);
12279 // Extend everything to 80 bits to force it to be done on x87.
12280 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12281 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12282 DAG.getIntPtrConstant(0, dl));
12285 std::pair<SDValue,SDValue>
12286 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12287 bool IsSigned, bool IsReplace) const {
12290 EVT DstTy = Op.getValueType();
12291 auto PtrVT = getPointerTy(DAG.getDataLayout());
12293 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12294 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12298 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12299 DstTy.getSimpleVT() >= MVT::i16 &&
12300 "Unknown FP_TO_INT to lower!");
12302 // These are really Legal.
12303 if (DstTy == MVT::i32 &&
12304 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12305 return std::make_pair(SDValue(), SDValue());
12306 if (Subtarget->is64Bit() &&
12307 DstTy == MVT::i64 &&
12308 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12309 return std::make_pair(SDValue(), SDValue());
12311 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12312 // stack slot, or into the FTOL runtime function.
12313 MachineFunction &MF = DAG.getMachineFunction();
12314 unsigned MemSize = DstTy.getSizeInBits()/8;
12315 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12316 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12319 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12320 Opc = X86ISD::WIN_FTOL;
12322 switch (DstTy.getSimpleVT().SimpleTy) {
12323 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12324 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12325 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12326 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12329 SDValue Chain = DAG.getEntryNode();
12330 SDValue Value = Op.getOperand(0);
12331 EVT TheVT = Op.getOperand(0).getValueType();
12332 // FIXME This causes a redundant load/store if the SSE-class value is already
12333 // in memory, such as if it is on the callstack.
12334 if (isScalarFPTypeInSSEReg(TheVT)) {
12335 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12336 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12337 MachinePointerInfo::getFixedStack(SSFI),
12339 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12341 Chain, StackSlot, DAG.getValueType(TheVT)
12344 MachineMemOperand *MMO =
12345 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12346 MachineMemOperand::MOLoad, MemSize, MemSize);
12347 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12348 Chain = Value.getValue(1);
12349 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12350 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12353 MachineMemOperand *MMO =
12354 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12355 MachineMemOperand::MOStore, MemSize, MemSize);
12357 if (Opc != X86ISD::WIN_FTOL) {
12358 // Build the FP_TO_INT*_IN_MEM
12359 SDValue Ops[] = { Chain, Value, StackSlot };
12360 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12362 return std::make_pair(FIST, StackSlot);
12364 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12365 DAG.getVTList(MVT::Other, MVT::Glue),
12367 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12368 MVT::i32, ftol.getValue(1));
12369 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12370 MVT::i32, eax.getValue(2));
12371 SDValue Ops[] = { eax, edx };
12372 SDValue pair = IsReplace
12373 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12374 : DAG.getMergeValues(Ops, DL);
12375 return std::make_pair(pair, SDValue());
12379 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12380 const X86Subtarget *Subtarget) {
12381 MVT VT = Op->getSimpleValueType(0);
12382 SDValue In = Op->getOperand(0);
12383 MVT InVT = In.getSimpleValueType();
12386 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12387 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12389 // Optimize vectors in AVX mode:
12392 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12393 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12394 // Concat upper and lower parts.
12397 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12398 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12399 // Concat upper and lower parts.
12402 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12403 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12404 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12407 if (Subtarget->hasInt256())
12408 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12410 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12411 SDValue Undef = DAG.getUNDEF(InVT);
12412 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12413 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12414 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12416 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12417 VT.getVectorNumElements()/2);
12419 OpLo = DAG.getBitcast(HVT, OpLo);
12420 OpHi = DAG.getBitcast(HVT, OpHi);
12422 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12425 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12426 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12427 MVT VT = Op->getSimpleValueType(0);
12428 SDValue In = Op->getOperand(0);
12429 MVT InVT = In.getSimpleValueType();
12431 unsigned int NumElts = VT.getVectorNumElements();
12432 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12435 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12436 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12438 assert(InVT.getVectorElementType() == MVT::i1);
12439 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12441 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12443 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12445 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12446 if (VT.is512BitVector())
12448 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12451 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12452 SelectionDAG &DAG) {
12453 if (Subtarget->hasFp256())
12454 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12460 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12461 SelectionDAG &DAG) {
12463 MVT VT = Op.getSimpleValueType();
12464 SDValue In = Op.getOperand(0);
12465 MVT SVT = In.getSimpleValueType();
12467 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12468 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12470 if (Subtarget->hasFp256())
12471 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12474 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12475 VT.getVectorNumElements() != SVT.getVectorNumElements());
12479 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12481 MVT VT = Op.getSimpleValueType();
12482 SDValue In = Op.getOperand(0);
12483 MVT InVT = In.getSimpleValueType();
12485 if (VT == MVT::i1) {
12486 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12487 "Invalid scalar TRUNCATE operation");
12488 if (InVT.getSizeInBits() >= 32)
12490 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12491 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12493 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12494 "Invalid TRUNCATE operation");
12496 // move vector to mask - truncate solution for SKX
12497 if (VT.getVectorElementType() == MVT::i1) {
12498 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12499 Subtarget->hasBWI())
12500 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12501 if ((InVT.is256BitVector() || InVT.is128BitVector())
12502 && InVT.getScalarSizeInBits() <= 16 &&
12503 Subtarget->hasBWI() && Subtarget->hasVLX())
12504 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12505 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12506 Subtarget->hasDQI())
12507 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12508 if ((InVT.is256BitVector() || InVT.is128BitVector())
12509 && InVT.getScalarSizeInBits() >= 32 &&
12510 Subtarget->hasDQI() && Subtarget->hasVLX())
12511 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12514 if (VT.getVectorElementType() == MVT::i1) {
12515 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12516 unsigned NumElts = InVT.getVectorNumElements();
12517 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12518 if (InVT.getSizeInBits() < 512) {
12519 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12520 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12525 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12526 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12527 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12530 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12531 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12532 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12533 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12535 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12536 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12537 if (Subtarget->hasInt256()) {
12538 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12539 In = DAG.getBitcast(MVT::v8i32, In);
12540 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12542 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12543 DAG.getIntPtrConstant(0, DL));
12546 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12547 DAG.getIntPtrConstant(0, DL));
12548 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12549 DAG.getIntPtrConstant(2, DL));
12550 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12551 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12552 static const int ShufMask[] = {0, 2, 4, 6};
12553 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12556 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12557 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12558 if (Subtarget->hasInt256()) {
12559 In = DAG.getBitcast(MVT::v32i8, In);
12561 SmallVector<SDValue,32> pshufbMask;
12562 for (unsigned i = 0; i < 2; ++i) {
12563 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12564 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12565 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12566 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12567 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12568 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12569 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12570 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12571 for (unsigned j = 0; j < 8; ++j)
12572 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12574 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12575 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12576 In = DAG.getBitcast(MVT::v4i64, In);
12578 static const int ShufMask[] = {0, 2, -1, -1};
12579 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12581 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12582 DAG.getIntPtrConstant(0, DL));
12583 return DAG.getBitcast(VT, In);
12586 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12587 DAG.getIntPtrConstant(0, DL));
12589 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12590 DAG.getIntPtrConstant(4, DL));
12592 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12593 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12595 // The PSHUFB mask:
12596 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12597 -1, -1, -1, -1, -1, -1, -1, -1};
12599 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12600 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12601 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12603 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12604 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12606 // The MOVLHPS Mask:
12607 static const int ShufMask2[] = {0, 1, 4, 5};
12608 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12609 return DAG.getBitcast(MVT::v8i16, res);
12612 // Handle truncation of V256 to V128 using shuffles.
12613 if (!VT.is128BitVector() || !InVT.is256BitVector())
12616 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12618 unsigned NumElems = VT.getVectorNumElements();
12619 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12621 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12622 // Prepare truncation shuffle mask
12623 for (unsigned i = 0; i != NumElems; ++i)
12624 MaskVec[i] = i * 2;
12625 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12626 DAG.getUNDEF(NVT), &MaskVec[0]);
12627 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12628 DAG.getIntPtrConstant(0, DL));
12631 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12632 SelectionDAG &DAG) const {
12633 assert(!Op.getSimpleValueType().isVector());
12635 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12636 /*IsSigned=*/ true, /*IsReplace=*/ false);
12637 SDValue FIST = Vals.first, StackSlot = Vals.second;
12638 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12639 if (!FIST.getNode()) return Op;
12641 if (StackSlot.getNode())
12642 // Load the result.
12643 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12644 FIST, StackSlot, MachinePointerInfo(),
12645 false, false, false, 0);
12647 // The node is the result.
12651 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12652 SelectionDAG &DAG) const {
12653 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12654 /*IsSigned=*/ false, /*IsReplace=*/ false);
12655 SDValue FIST = Vals.first, StackSlot = Vals.second;
12656 assert(FIST.getNode() && "Unexpected failure");
12658 if (StackSlot.getNode())
12659 // Load the result.
12660 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12661 FIST, StackSlot, MachinePointerInfo(),
12662 false, false, false, 0);
12664 // The node is the result.
12668 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12670 MVT VT = Op.getSimpleValueType();
12671 SDValue In = Op.getOperand(0);
12672 MVT SVT = In.getSimpleValueType();
12674 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12676 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12677 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12678 In, DAG.getUNDEF(SVT)));
12681 /// The only differences between FABS and FNEG are the mask and the logic op.
12682 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12683 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12684 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12685 "Wrong opcode for lowering FABS or FNEG.");
12687 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12689 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12690 // into an FNABS. We'll lower the FABS after that if it is still in use.
12692 for (SDNode *User : Op->uses())
12693 if (User->getOpcode() == ISD::FNEG)
12696 SDValue Op0 = Op.getOperand(0);
12697 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12700 MVT VT = Op.getSimpleValueType();
12701 // Assume scalar op for initialization; update for vector if needed.
12702 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12703 // generate a 16-byte vector constant and logic op even for the scalar case.
12704 // Using a 16-byte mask allows folding the load of the mask with
12705 // the logic op, so it can save (~4 bytes) on code size.
12707 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12708 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12709 // decide if we should generate a 16-byte constant mask when we only need 4 or
12710 // 8 bytes for the scalar case.
12711 if (VT.isVector()) {
12712 EltVT = VT.getVectorElementType();
12713 NumElts = VT.getVectorNumElements();
12716 unsigned EltBits = EltVT.getSizeInBits();
12717 LLVMContext *Context = DAG.getContext();
12718 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12720 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12721 Constant *C = ConstantInt::get(*Context, MaskElt);
12722 C = ConstantVector::getSplat(NumElts, C);
12723 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12724 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12725 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12726 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12727 MachinePointerInfo::getConstantPool(),
12728 false, false, false, Alignment);
12730 if (VT.isVector()) {
12731 // For a vector, cast operands to a vector type, perform the logic op,
12732 // and cast the result back to the original value type.
12733 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12734 SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12735 SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12736 : DAG.getBitcast(VecVT, Op0);
12737 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12738 return DAG.getBitcast(VT,
12739 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12742 // If not vector, then scalar.
12743 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12744 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12745 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12748 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12750 LLVMContext *Context = DAG.getContext();
12751 SDValue Op0 = Op.getOperand(0);
12752 SDValue Op1 = Op.getOperand(1);
12754 MVT VT = Op.getSimpleValueType();
12755 MVT SrcVT = Op1.getSimpleValueType();
12757 // If second operand is smaller, extend it first.
12758 if (SrcVT.bitsLT(VT)) {
12759 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12762 // And if it is bigger, shrink it first.
12763 if (SrcVT.bitsGT(VT)) {
12764 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12768 // At this point the operands and the result should have the same
12769 // type, and that won't be f80 since that is not custom lowered.
12771 const fltSemantics &Sem =
12772 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12773 const unsigned SizeInBits = VT.getSizeInBits();
12775 SmallVector<Constant *, 4> CV(
12776 VT == MVT::f64 ? 2 : 4,
12777 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12779 // First, clear all bits but the sign bit from the second operand (sign).
12780 CV[0] = ConstantFP::get(*Context,
12781 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12782 Constant *C = ConstantVector::get(CV);
12783 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12784 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12785 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12786 MachinePointerInfo::getConstantPool(),
12787 false, false, false, 16);
12788 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12790 // Next, clear the sign bit from the first operand (magnitude).
12791 // If it's a constant, we can clear it here.
12792 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12793 APFloat APF = Op0CN->getValueAPF();
12794 // If the magnitude is a positive zero, the sign bit alone is enough.
12795 if (APF.isPosZero())
12798 CV[0] = ConstantFP::get(*Context, APF);
12800 CV[0] = ConstantFP::get(
12802 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12804 C = ConstantVector::get(CV);
12805 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12806 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12807 MachinePointerInfo::getConstantPool(),
12808 false, false, false, 16);
12809 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12810 if (!isa<ConstantFPSDNode>(Op0))
12811 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12813 // OR the magnitude value with the sign bit.
12814 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12817 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12818 SDValue N0 = Op.getOperand(0);
12820 MVT VT = Op.getSimpleValueType();
12822 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12823 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12824 DAG.getConstant(1, dl, VT));
12825 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12828 // Check whether an OR'd tree is PTEST-able.
12829 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12830 SelectionDAG &DAG) {
12831 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12833 if (!Subtarget->hasSSE41())
12836 if (!Op->hasOneUse())
12839 SDNode *N = Op.getNode();
12842 SmallVector<SDValue, 8> Opnds;
12843 DenseMap<SDValue, unsigned> VecInMap;
12844 SmallVector<SDValue, 8> VecIns;
12845 EVT VT = MVT::Other;
12847 // Recognize a special case where a vector is casted into wide integer to
12849 Opnds.push_back(N->getOperand(0));
12850 Opnds.push_back(N->getOperand(1));
12852 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12853 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12854 // BFS traverse all OR'd operands.
12855 if (I->getOpcode() == ISD::OR) {
12856 Opnds.push_back(I->getOperand(0));
12857 Opnds.push_back(I->getOperand(1));
12858 // Re-evaluate the number of nodes to be traversed.
12859 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12863 // Quit if a non-EXTRACT_VECTOR_ELT
12864 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12867 // Quit if without a constant index.
12868 SDValue Idx = I->getOperand(1);
12869 if (!isa<ConstantSDNode>(Idx))
12872 SDValue ExtractedFromVec = I->getOperand(0);
12873 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12874 if (M == VecInMap.end()) {
12875 VT = ExtractedFromVec.getValueType();
12876 // Quit if not 128/256-bit vector.
12877 if (!VT.is128BitVector() && !VT.is256BitVector())
12879 // Quit if not the same type.
12880 if (VecInMap.begin() != VecInMap.end() &&
12881 VT != VecInMap.begin()->first.getValueType())
12883 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12884 VecIns.push_back(ExtractedFromVec);
12886 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12889 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12890 "Not extracted from 128-/256-bit vector.");
12892 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12894 for (DenseMap<SDValue, unsigned>::const_iterator
12895 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12896 // Quit if not all elements are used.
12897 if (I->second != FullMask)
12901 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12903 // Cast all vectors into TestVT for PTEST.
12904 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12905 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12907 // If more than one full vectors are evaluated, OR them first before PTEST.
12908 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12909 // Each iteration will OR 2 nodes and append the result until there is only
12910 // 1 node left, i.e. the final OR'd value of all vectors.
12911 SDValue LHS = VecIns[Slot];
12912 SDValue RHS = VecIns[Slot + 1];
12913 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12916 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12917 VecIns.back(), VecIns.back());
12920 /// \brief return true if \c Op has a use that doesn't just read flags.
12921 static bool hasNonFlagsUse(SDValue Op) {
12922 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12924 SDNode *User = *UI;
12925 unsigned UOpNo = UI.getOperandNo();
12926 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12927 // Look pass truncate.
12928 UOpNo = User->use_begin().getOperandNo();
12929 User = *User->use_begin();
12932 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12933 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12939 /// Emit nodes that will be selected as "test Op0,Op0", or something
12941 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12942 SelectionDAG &DAG) const {
12943 if (Op.getValueType() == MVT::i1) {
12944 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12945 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12946 DAG.getConstant(0, dl, MVT::i8));
12948 // CF and OF aren't always set the way we want. Determine which
12949 // of these we need.
12950 bool NeedCF = false;
12951 bool NeedOF = false;
12954 case X86::COND_A: case X86::COND_AE:
12955 case X86::COND_B: case X86::COND_BE:
12958 case X86::COND_G: case X86::COND_GE:
12959 case X86::COND_L: case X86::COND_LE:
12960 case X86::COND_O: case X86::COND_NO: {
12961 // Check if we really need to set the
12962 // Overflow flag. If NoSignedWrap is present
12963 // that is not actually needed.
12964 switch (Op->getOpcode()) {
12969 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12970 if (BinNode->Flags.hasNoSignedWrap())
12980 // See if we can use the EFLAGS value from the operand instead of
12981 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12982 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12983 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12984 // Emit a CMP with 0, which is the TEST pattern.
12985 //if (Op.getValueType() == MVT::i1)
12986 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12987 // DAG.getConstant(0, MVT::i1));
12988 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12989 DAG.getConstant(0, dl, Op.getValueType()));
12991 unsigned Opcode = 0;
12992 unsigned NumOperands = 0;
12994 // Truncate operations may prevent the merge of the SETCC instruction
12995 // and the arithmetic instruction before it. Attempt to truncate the operands
12996 // of the arithmetic instruction and use a reduced bit-width instruction.
12997 bool NeedTruncation = false;
12998 SDValue ArithOp = Op;
12999 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13000 SDValue Arith = Op->getOperand(0);
13001 // Both the trunc and the arithmetic op need to have one user each.
13002 if (Arith->hasOneUse())
13003 switch (Arith.getOpcode()) {
13010 NeedTruncation = true;
13016 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13017 // which may be the result of a CAST. We use the variable 'Op', which is the
13018 // non-casted variable when we check for possible users.
13019 switch (ArithOp.getOpcode()) {
13021 // Due to an isel shortcoming, be conservative if this add is likely to be
13022 // selected as part of a load-modify-store instruction. When the root node
13023 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13024 // uses of other nodes in the match, such as the ADD in this case. This
13025 // leads to the ADD being left around and reselected, with the result being
13026 // two adds in the output. Alas, even if none our users are stores, that
13027 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13028 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13029 // climbing the DAG back to the root, and it doesn't seem to be worth the
13031 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13032 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13033 if (UI->getOpcode() != ISD::CopyToReg &&
13034 UI->getOpcode() != ISD::SETCC &&
13035 UI->getOpcode() != ISD::STORE)
13038 if (ConstantSDNode *C =
13039 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13040 // An add of one will be selected as an INC.
13041 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13042 Opcode = X86ISD::INC;
13047 // An add of negative one (subtract of one) will be selected as a DEC.
13048 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13049 Opcode = X86ISD::DEC;
13055 // Otherwise use a regular EFLAGS-setting add.
13056 Opcode = X86ISD::ADD;
13061 // If we have a constant logical shift that's only used in a comparison
13062 // against zero turn it into an equivalent AND. This allows turning it into
13063 // a TEST instruction later.
13064 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13065 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13066 EVT VT = Op.getValueType();
13067 unsigned BitWidth = VT.getSizeInBits();
13068 unsigned ShAmt = Op->getConstantOperandVal(1);
13069 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13071 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13072 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13073 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13074 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13076 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13077 DAG.getConstant(Mask, dl, VT));
13078 DAG.ReplaceAllUsesWith(Op, New);
13084 // If the primary and result isn't used, don't bother using X86ISD::AND,
13085 // because a TEST instruction will be better.
13086 if (!hasNonFlagsUse(Op))
13092 // Due to the ISEL shortcoming noted above, be conservative if this op is
13093 // likely to be selected as part of a load-modify-store instruction.
13094 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13095 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13096 if (UI->getOpcode() == ISD::STORE)
13099 // Otherwise use a regular EFLAGS-setting instruction.
13100 switch (ArithOp.getOpcode()) {
13101 default: llvm_unreachable("unexpected operator!");
13102 case ISD::SUB: Opcode = X86ISD::SUB; break;
13103 case ISD::XOR: Opcode = X86ISD::XOR; break;
13104 case ISD::AND: Opcode = X86ISD::AND; break;
13106 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13107 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13108 if (EFLAGS.getNode())
13111 Opcode = X86ISD::OR;
13125 return SDValue(Op.getNode(), 1);
13131 // If we found that truncation is beneficial, perform the truncation and
13133 if (NeedTruncation) {
13134 EVT VT = Op.getValueType();
13135 SDValue WideVal = Op->getOperand(0);
13136 EVT WideVT = WideVal.getValueType();
13137 unsigned ConvertedOp = 0;
13138 // Use a target machine opcode to prevent further DAGCombine
13139 // optimizations that may separate the arithmetic operations
13140 // from the setcc node.
13141 switch (WideVal.getOpcode()) {
13143 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13144 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13145 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13146 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13147 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13151 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13152 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13153 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13154 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13155 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13161 // Emit a CMP with 0, which is the TEST pattern.
13162 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13163 DAG.getConstant(0, dl, Op.getValueType()));
13165 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13166 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13168 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13169 DAG.ReplaceAllUsesWith(Op, New);
13170 return SDValue(New.getNode(), 1);
13173 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13175 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13176 SDLoc dl, SelectionDAG &DAG) const {
13177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13178 if (C->getAPIntValue() == 0)
13179 return EmitTest(Op0, X86CC, dl, DAG);
13181 if (Op0.getValueType() == MVT::i1)
13182 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13185 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13186 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13187 // Do the comparison at i32 if it's smaller, besides the Atom case.
13188 // This avoids subregister aliasing issues. Keep the smaller reference
13189 // if we're optimizing for size, however, as that'll allow better folding
13190 // of memory operations.
13191 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13192 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13193 Attribute::MinSize) &&
13194 !Subtarget->isAtom()) {
13195 unsigned ExtendOp =
13196 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13197 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13198 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13200 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13201 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13202 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13204 return SDValue(Sub.getNode(), 1);
13206 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13209 /// Convert a comparison if required by the subtarget.
13210 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13211 SelectionDAG &DAG) const {
13212 // If the subtarget does not support the FUCOMI instruction, floating-point
13213 // comparisons have to be converted.
13214 if (Subtarget->hasCMov() ||
13215 Cmp.getOpcode() != X86ISD::CMP ||
13216 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13217 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13220 // The instruction selector will select an FUCOM instruction instead of
13221 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13222 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13223 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13225 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13226 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13227 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13228 DAG.getConstant(8, dl, MVT::i8));
13229 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13230 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13233 /// The minimum architected relative accuracy is 2^-12. We need one
13234 /// Newton-Raphson step to have a good float result (24 bits of precision).
13235 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13236 DAGCombinerInfo &DCI,
13237 unsigned &RefinementSteps,
13238 bool &UseOneConstNR) const {
13239 EVT VT = Op.getValueType();
13240 const char *RecipOp;
13242 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13243 // TODO: Add support for AVX512 (v16f32).
13244 // It is likely not profitable to do this for f64 because a double-precision
13245 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13246 // instructions: convert to single, rsqrtss, convert back to double, refine
13247 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13248 // along with FMA, this could be a throughput win.
13249 if (VT == MVT::f32 && Subtarget->hasSSE1())
13251 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13252 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13253 RecipOp = "vec-sqrtf";
13257 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13258 if (!Recips.isEnabled(RecipOp))
13261 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13262 UseOneConstNR = false;
13263 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13266 /// The minimum architected relative accuracy is 2^-12. We need one
13267 /// Newton-Raphson step to have a good float result (24 bits of precision).
13268 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13269 DAGCombinerInfo &DCI,
13270 unsigned &RefinementSteps) const {
13271 EVT VT = Op.getValueType();
13272 const char *RecipOp;
13274 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13275 // TODO: Add support for AVX512 (v16f32).
13276 // It is likely not profitable to do this for f64 because a double-precision
13277 // reciprocal estimate with refinement on x86 prior to FMA requires
13278 // 15 instructions: convert to single, rcpss, convert back to double, refine
13279 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13280 // along with FMA, this could be a throughput win.
13281 if (VT == MVT::f32 && Subtarget->hasSSE1())
13283 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13284 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13285 RecipOp = "vec-divf";
13289 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13290 if (!Recips.isEnabled(RecipOp))
13293 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13294 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13297 /// If we have at least two divisions that use the same divisor, convert to
13298 /// multplication by a reciprocal. This may need to be adjusted for a given
13299 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13300 /// This is because we still need one division to calculate the reciprocal and
13301 /// then we need two multiplies by that reciprocal as replacements for the
13302 /// original divisions.
13303 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13304 return NumUsers > 1;
13307 static bool isAllOnes(SDValue V) {
13308 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13309 return C && C->isAllOnesValue();
13312 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13313 /// if it's possible.
13314 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13315 SDLoc dl, SelectionDAG &DAG) const {
13316 SDValue Op0 = And.getOperand(0);
13317 SDValue Op1 = And.getOperand(1);
13318 if (Op0.getOpcode() == ISD::TRUNCATE)
13319 Op0 = Op0.getOperand(0);
13320 if (Op1.getOpcode() == ISD::TRUNCATE)
13321 Op1 = Op1.getOperand(0);
13324 if (Op1.getOpcode() == ISD::SHL)
13325 std::swap(Op0, Op1);
13326 if (Op0.getOpcode() == ISD::SHL) {
13327 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13328 if (And00C->getZExtValue() == 1) {
13329 // If we looked past a truncate, check that it's only truncating away
13331 unsigned BitWidth = Op0.getValueSizeInBits();
13332 unsigned AndBitWidth = And.getValueSizeInBits();
13333 if (BitWidth > AndBitWidth) {
13335 DAG.computeKnownBits(Op0, Zeros, Ones);
13336 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13340 RHS = Op0.getOperand(1);
13342 } else if (Op1.getOpcode() == ISD::Constant) {
13343 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13344 uint64_t AndRHSVal = AndRHS->getZExtValue();
13345 SDValue AndLHS = Op0;
13347 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13348 LHS = AndLHS.getOperand(0);
13349 RHS = AndLHS.getOperand(1);
13352 // Use BT if the immediate can't be encoded in a TEST instruction.
13353 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13355 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13359 if (LHS.getNode()) {
13360 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13361 // instruction. Since the shift amount is in-range-or-undefined, we know
13362 // that doing a bittest on the i32 value is ok. We extend to i32 because
13363 // the encoding for the i16 version is larger than the i32 version.
13364 // Also promote i16 to i32 for performance / code size reason.
13365 if (LHS.getValueType() == MVT::i8 ||
13366 LHS.getValueType() == MVT::i16)
13367 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13369 // If the operand types disagree, extend the shift amount to match. Since
13370 // BT ignores high bits (like shifts) we can use anyextend.
13371 if (LHS.getValueType() != RHS.getValueType())
13372 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13374 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13375 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13376 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13377 DAG.getConstant(Cond, dl, MVT::i8), BT);
13383 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13385 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13390 // SSE Condition code mapping:
13399 switch (SetCCOpcode) {
13400 default: llvm_unreachable("Unexpected SETCC condition");
13402 case ISD::SETEQ: SSECC = 0; break;
13404 case ISD::SETGT: Swap = true; // Fallthrough
13406 case ISD::SETOLT: SSECC = 1; break;
13408 case ISD::SETGE: Swap = true; // Fallthrough
13410 case ISD::SETOLE: SSECC = 2; break;
13411 case ISD::SETUO: SSECC = 3; break;
13413 case ISD::SETNE: SSECC = 4; break;
13414 case ISD::SETULE: Swap = true; // Fallthrough
13415 case ISD::SETUGE: SSECC = 5; break;
13416 case ISD::SETULT: Swap = true; // Fallthrough
13417 case ISD::SETUGT: SSECC = 6; break;
13418 case ISD::SETO: SSECC = 7; break;
13420 case ISD::SETONE: SSECC = 8; break;
13423 std::swap(Op0, Op1);
13428 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13429 // ones, and then concatenate the result back.
13430 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13431 MVT VT = Op.getSimpleValueType();
13433 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13434 "Unsupported value type for operation");
13436 unsigned NumElems = VT.getVectorNumElements();
13438 SDValue CC = Op.getOperand(2);
13440 // Extract the LHS vectors
13441 SDValue LHS = Op.getOperand(0);
13442 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13443 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13445 // Extract the RHS vectors
13446 SDValue RHS = Op.getOperand(1);
13447 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13448 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13450 // Issue the operation on the smaller types and concatenate the result back
13451 MVT EltVT = VT.getVectorElementType();
13452 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13453 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13454 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13455 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13458 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13459 SDValue Op0 = Op.getOperand(0);
13460 SDValue Op1 = Op.getOperand(1);
13461 SDValue CC = Op.getOperand(2);
13462 MVT VT = Op.getSimpleValueType();
13465 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13466 "Unexpected type for boolean compare operation");
13467 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13468 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13469 DAG.getConstant(-1, dl, VT));
13470 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13471 DAG.getConstant(-1, dl, VT));
13472 switch (SetCCOpcode) {
13473 default: llvm_unreachable("Unexpected SETCC condition");
13475 // (x == y) -> ~(x ^ y)
13476 return DAG.getNode(ISD::XOR, dl, VT,
13477 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13478 DAG.getConstant(-1, dl, VT));
13480 // (x != y) -> (x ^ y)
13481 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13484 // (x > y) -> (x & ~y)
13485 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13488 // (x < y) -> (~x & y)
13489 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13492 // (x <= y) -> (~x | y)
13493 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13496 // (x >=y) -> (x | ~y)
13497 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13501 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13502 const X86Subtarget *Subtarget) {
13503 SDValue Op0 = Op.getOperand(0);
13504 SDValue Op1 = Op.getOperand(1);
13505 SDValue CC = Op.getOperand(2);
13506 MVT VT = Op.getSimpleValueType();
13509 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13510 Op.getValueType().getScalarType() == MVT::i1 &&
13511 "Cannot set masked compare for this operation");
13513 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13515 bool Unsigned = false;
13518 switch (SetCCOpcode) {
13519 default: llvm_unreachable("Unexpected SETCC condition");
13520 case ISD::SETNE: SSECC = 4; break;
13521 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13522 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13523 case ISD::SETLT: Swap = true; //fall-through
13524 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13525 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13526 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13527 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13528 case ISD::SETULE: Unsigned = true; //fall-through
13529 case ISD::SETLE: SSECC = 2; break;
13533 std::swap(Op0, Op1);
13535 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13536 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13537 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13538 DAG.getConstant(SSECC, dl, MVT::i8));
13541 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13542 /// operand \p Op1. If non-trivial (for example because it's not constant)
13543 /// return an empty value.
13544 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13546 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13550 MVT VT = Op1.getSimpleValueType();
13551 MVT EVT = VT.getVectorElementType();
13552 unsigned n = VT.getVectorNumElements();
13553 SmallVector<SDValue, 8> ULTOp1;
13555 for (unsigned i = 0; i < n; ++i) {
13556 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13557 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13560 // Avoid underflow.
13561 APInt Val = Elt->getAPIntValue();
13565 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13568 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13571 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13572 SelectionDAG &DAG) {
13573 SDValue Op0 = Op.getOperand(0);
13574 SDValue Op1 = Op.getOperand(1);
13575 SDValue CC = Op.getOperand(2);
13576 MVT VT = Op.getSimpleValueType();
13577 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13578 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13583 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13584 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13587 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13588 unsigned Opc = X86ISD::CMPP;
13589 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13590 assert(VT.getVectorNumElements() <= 16);
13591 Opc = X86ISD::CMPM;
13593 // In the two special cases we can't handle, emit two comparisons.
13596 unsigned CombineOpc;
13597 if (SetCCOpcode == ISD::SETUEQ) {
13598 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13600 assert(SetCCOpcode == ISD::SETONE);
13601 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13604 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13605 DAG.getConstant(CC0, dl, MVT::i8));
13606 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13607 DAG.getConstant(CC1, dl, MVT::i8));
13608 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13610 // Handle all other FP comparisons here.
13611 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13612 DAG.getConstant(SSECC, dl, MVT::i8));
13615 // Break 256-bit integer vector compare into smaller ones.
13616 if (VT.is256BitVector() && !Subtarget->hasInt256())
13617 return Lower256IntVSETCC(Op, DAG);
13619 EVT OpVT = Op1.getValueType();
13620 if (OpVT.getVectorElementType() == MVT::i1)
13621 return LowerBoolVSETCC_AVX512(Op, DAG);
13623 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13624 if (Subtarget->hasAVX512()) {
13625 if (Op1.getValueType().is512BitVector() ||
13626 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13627 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13628 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13630 // In AVX-512 architecture setcc returns mask with i1 elements,
13631 // But there is no compare instruction for i8 and i16 elements in KNL.
13632 // We are not talking about 512-bit operands in this case, these
13633 // types are illegal.
13635 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13636 OpVT.getVectorElementType().getSizeInBits() >= 8))
13637 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13638 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13641 // We are handling one of the integer comparisons here. Since SSE only has
13642 // GT and EQ comparisons for integer, swapping operands and multiple
13643 // operations may be required for some comparisons.
13645 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13646 bool Subus = false;
13648 switch (SetCCOpcode) {
13649 default: llvm_unreachable("Unexpected SETCC condition");
13650 case ISD::SETNE: Invert = true;
13651 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13652 case ISD::SETLT: Swap = true;
13653 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13654 case ISD::SETGE: Swap = true;
13655 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13656 Invert = true; break;
13657 case ISD::SETULT: Swap = true;
13658 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13659 FlipSigns = true; break;
13660 case ISD::SETUGE: Swap = true;
13661 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13662 FlipSigns = true; Invert = true; break;
13665 // Special case: Use min/max operations for SETULE/SETUGE
13666 MVT VET = VT.getVectorElementType();
13668 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13669 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13672 switch (SetCCOpcode) {
13674 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13675 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13678 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13681 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13682 if (!MinMax && hasSubus) {
13683 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13685 // t = psubus Op0, Op1
13686 // pcmpeq t, <0..0>
13687 switch (SetCCOpcode) {
13689 case ISD::SETULT: {
13690 // If the comparison is against a constant we can turn this into a
13691 // setule. With psubus, setule does not require a swap. This is
13692 // beneficial because the constant in the register is no longer
13693 // destructed as the destination so it can be hoisted out of a loop.
13694 // Only do this pre-AVX since vpcmp* is no longer destructive.
13695 if (Subtarget->hasAVX())
13697 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13698 if (ULEOp1.getNode()) {
13700 Subus = true; Invert = false; Swap = false;
13704 // Psubus is better than flip-sign because it requires no inversion.
13705 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13706 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13710 Opc = X86ISD::SUBUS;
13716 std::swap(Op0, Op1);
13718 // Check that the operation in question is available (most are plain SSE2,
13719 // but PCMPGTQ and PCMPEQQ have different requirements).
13720 if (VT == MVT::v2i64) {
13721 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13722 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13724 // First cast everything to the right type.
13725 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13726 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13728 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13729 // bits of the inputs before performing those operations. The lower
13730 // compare is always unsigned.
13733 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13735 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13736 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13737 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13738 Sign, Zero, Sign, Zero);
13740 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13741 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13743 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13744 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13745 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13747 // Create masks for only the low parts/high parts of the 64 bit integers.
13748 static const int MaskHi[] = { 1, 1, 3, 3 };
13749 static const int MaskLo[] = { 0, 0, 2, 2 };
13750 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13751 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13752 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13754 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13755 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13758 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13760 return DAG.getBitcast(VT, Result);
13763 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13764 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13765 // pcmpeqd + pshufd + pand.
13766 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13768 // First cast everything to the right type.
13769 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13770 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13773 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13775 // Make sure the lower and upper halves are both all-ones.
13776 static const int Mask[] = { 1, 0, 3, 2 };
13777 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13778 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13781 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13783 return DAG.getBitcast(VT, Result);
13787 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13788 // bits of the inputs before performing those operations.
13790 EVT EltVT = VT.getVectorElementType();
13791 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13793 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13794 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13797 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13799 // If the logical-not of the result is required, perform that now.
13801 Result = DAG.getNOT(dl, Result, VT);
13804 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13807 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13808 getZeroVector(VT, Subtarget, DAG, dl));
13813 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13815 MVT VT = Op.getSimpleValueType();
13817 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13819 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13820 && "SetCC type must be 8-bit or 1-bit integer");
13821 SDValue Op0 = Op.getOperand(0);
13822 SDValue Op1 = Op.getOperand(1);
13824 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13826 // Optimize to BT if possible.
13827 // Lower (X & (1 << N)) == 0 to BT(X, N).
13828 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13829 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13830 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13831 Op1.getOpcode() == ISD::Constant &&
13832 cast<ConstantSDNode>(Op1)->isNullValue() &&
13833 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13834 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13835 if (NewSetCC.getNode()) {
13837 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13842 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13844 if (Op1.getOpcode() == ISD::Constant &&
13845 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13846 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13847 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13849 // If the input is a setcc, then reuse the input setcc or use a new one with
13850 // the inverted condition.
13851 if (Op0.getOpcode() == X86ISD::SETCC) {
13852 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13853 bool Invert = (CC == ISD::SETNE) ^
13854 cast<ConstantSDNode>(Op1)->isNullValue();
13858 CCode = X86::GetOppositeBranchCondition(CCode);
13859 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13860 DAG.getConstant(CCode, dl, MVT::i8),
13861 Op0.getOperand(1));
13863 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13867 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13868 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13869 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13871 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13872 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13875 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13876 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13877 if (X86CC == X86::COND_INVALID)
13880 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13881 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13882 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13883 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13885 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13889 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13890 static bool isX86LogicalCmp(SDValue Op) {
13891 unsigned Opc = Op.getNode()->getOpcode();
13892 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13893 Opc == X86ISD::SAHF)
13895 if (Op.getResNo() == 1 &&
13896 (Opc == X86ISD::ADD ||
13897 Opc == X86ISD::SUB ||
13898 Opc == X86ISD::ADC ||
13899 Opc == X86ISD::SBB ||
13900 Opc == X86ISD::SMUL ||
13901 Opc == X86ISD::UMUL ||
13902 Opc == X86ISD::INC ||
13903 Opc == X86ISD::DEC ||
13904 Opc == X86ISD::OR ||
13905 Opc == X86ISD::XOR ||
13906 Opc == X86ISD::AND))
13909 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13915 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13916 if (V.getOpcode() != ISD::TRUNCATE)
13919 SDValue VOp0 = V.getOperand(0);
13920 unsigned InBits = VOp0.getValueSizeInBits();
13921 unsigned Bits = V.getValueSizeInBits();
13922 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13925 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13926 bool addTest = true;
13927 SDValue Cond = Op.getOperand(0);
13928 SDValue Op1 = Op.getOperand(1);
13929 SDValue Op2 = Op.getOperand(2);
13931 EVT VT = Op1.getValueType();
13934 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13935 // are available or VBLENDV if AVX is available.
13936 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13937 if (Cond.getOpcode() == ISD::SETCC &&
13938 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13939 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13940 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13941 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13942 int SSECC = translateX86FSETCC(
13943 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13946 if (Subtarget->hasAVX512()) {
13947 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13948 DAG.getConstant(SSECC, DL, MVT::i8));
13949 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13952 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13953 DAG.getConstant(SSECC, DL, MVT::i8));
13955 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13956 // of 3 logic instructions for size savings and potentially speed.
13957 // Unfortunately, there is no scalar form of VBLENDV.
13959 // If either operand is a constant, don't try this. We can expect to
13960 // optimize away at least one of the logic instructions later in that
13961 // case, so that sequence would be faster than a variable blend.
13963 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13964 // uses XMM0 as the selection register. That may need just as many
13965 // instructions as the AND/ANDN/OR sequence due to register moves, so
13968 if (Subtarget->hasAVX() &&
13969 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13971 // Convert to vectors, do a VSELECT, and convert back to scalar.
13972 // All of the conversions should be optimized away.
13974 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13975 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13976 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13977 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13979 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13980 VCmp = DAG.getBitcast(VCmpVT, VCmp);
13982 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13984 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13985 VSel, DAG.getIntPtrConstant(0, DL));
13987 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13988 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13989 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13993 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13995 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13996 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13997 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13998 Op1Scalar = Op1.getOperand(0);
14000 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14001 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14002 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14003 Op2Scalar = Op2.getOperand(0);
14004 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14005 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14006 Op1Scalar.getValueType(),
14007 Cond, Op1Scalar, Op2Scalar);
14008 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14009 return DAG.getBitcast(VT, newSelect);
14010 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14011 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14012 DAG.getIntPtrConstant(0, DL));
14016 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14017 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14018 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14019 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14020 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14021 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14022 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14024 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14027 if (Cond.getOpcode() == ISD::SETCC) {
14028 SDValue NewCond = LowerSETCC(Cond, DAG);
14029 if (NewCond.getNode())
14033 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14034 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14035 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14036 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14037 if (Cond.getOpcode() == X86ISD::SETCC &&
14038 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14039 isZero(Cond.getOperand(1).getOperand(1))) {
14040 SDValue Cmp = Cond.getOperand(1);
14042 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14044 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14045 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14046 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14048 SDValue CmpOp0 = Cmp.getOperand(0);
14049 // Apply further optimizations for special cases
14050 // (select (x != 0), -1, 0) -> neg & sbb
14051 // (select (x == 0), 0, -1) -> neg & sbb
14052 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14053 if (YC->isNullValue() &&
14054 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14055 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14056 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14057 DAG.getConstant(0, DL,
14058 CmpOp0.getValueType()),
14060 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14061 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14062 SDValue(Neg.getNode(), 1));
14066 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14067 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14068 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14070 SDValue Res = // Res = 0 or -1.
14071 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14072 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14074 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14075 Res = DAG.getNOT(DL, Res, Res.getValueType());
14077 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14078 if (!N2C || !N2C->isNullValue())
14079 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14084 // Look past (and (setcc_carry (cmp ...)), 1).
14085 if (Cond.getOpcode() == ISD::AND &&
14086 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14087 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14088 if (C && C->getAPIntValue() == 1)
14089 Cond = Cond.getOperand(0);
14092 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14093 // setting operand in place of the X86ISD::SETCC.
14094 unsigned CondOpcode = Cond.getOpcode();
14095 if (CondOpcode == X86ISD::SETCC ||
14096 CondOpcode == X86ISD::SETCC_CARRY) {
14097 CC = Cond.getOperand(0);
14099 SDValue Cmp = Cond.getOperand(1);
14100 unsigned Opc = Cmp.getOpcode();
14101 MVT VT = Op.getSimpleValueType();
14103 bool IllegalFPCMov = false;
14104 if (VT.isFloatingPoint() && !VT.isVector() &&
14105 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14106 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14108 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14109 Opc == X86ISD::BT) { // FIXME
14113 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14114 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14115 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14116 Cond.getOperand(0).getValueType() != MVT::i8)) {
14117 SDValue LHS = Cond.getOperand(0);
14118 SDValue RHS = Cond.getOperand(1);
14119 unsigned X86Opcode;
14122 switch (CondOpcode) {
14123 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14124 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14125 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14126 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14127 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14128 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14129 default: llvm_unreachable("unexpected overflowing operator");
14131 if (CondOpcode == ISD::UMULO)
14132 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14135 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14137 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14139 if (CondOpcode == ISD::UMULO)
14140 Cond = X86Op.getValue(2);
14142 Cond = X86Op.getValue(1);
14144 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14149 // Look pass the truncate if the high bits are known zero.
14150 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14151 Cond = Cond.getOperand(0);
14153 // We know the result of AND is compared against zero. Try to match
14155 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14156 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14157 if (NewSetCC.getNode()) {
14158 CC = NewSetCC.getOperand(0);
14159 Cond = NewSetCC.getOperand(1);
14166 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14167 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14170 // a < b ? -1 : 0 -> RES = ~setcc_carry
14171 // a < b ? 0 : -1 -> RES = setcc_carry
14172 // a >= b ? -1 : 0 -> RES = setcc_carry
14173 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14174 if (Cond.getOpcode() == X86ISD::SUB) {
14175 Cond = ConvertCmpIfNecessary(Cond, DAG);
14176 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14178 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14179 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14180 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14181 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14183 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14184 return DAG.getNOT(DL, Res, Res.getValueType());
14189 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14190 // widen the cmov and push the truncate through. This avoids introducing a new
14191 // branch during isel and doesn't add any extensions.
14192 if (Op.getValueType() == MVT::i8 &&
14193 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14194 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14195 if (T1.getValueType() == T2.getValueType() &&
14196 // Blacklist CopyFromReg to avoid partial register stalls.
14197 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14198 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14199 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14200 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14204 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14205 // condition is true.
14206 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14207 SDValue Ops[] = { Op2, Op1, CC, Cond };
14208 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14211 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14212 const X86Subtarget *Subtarget,
14213 SelectionDAG &DAG) {
14214 MVT VT = Op->getSimpleValueType(0);
14215 SDValue In = Op->getOperand(0);
14216 MVT InVT = In.getSimpleValueType();
14217 MVT VTElt = VT.getVectorElementType();
14218 MVT InVTElt = InVT.getVectorElementType();
14222 if ((InVTElt == MVT::i1) &&
14223 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14224 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14226 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14227 VTElt.getSizeInBits() <= 16)) ||
14229 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14230 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14232 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14233 VTElt.getSizeInBits() >= 32))))
14234 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14236 unsigned int NumElts = VT.getVectorNumElements();
14238 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14241 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14242 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14243 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14244 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14247 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14248 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14250 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14253 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14255 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14256 if (VT.is512BitVector())
14258 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14261 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14262 const X86Subtarget *Subtarget,
14263 SelectionDAG &DAG) {
14264 SDValue In = Op->getOperand(0);
14265 MVT VT = Op->getSimpleValueType(0);
14266 MVT InVT = In.getSimpleValueType();
14267 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14269 MVT InSVT = InVT.getScalarType();
14270 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14272 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14274 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14279 // SSE41 targets can use the pmovsx* instructions directly.
14280 if (Subtarget->hasSSE41())
14281 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14283 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14287 // As SRAI is only available on i16/i32 types, we expand only up to i32
14288 // and handle i64 separately.
14289 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14290 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14291 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14292 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14293 Curr = DAG.getBitcast(CurrVT, Curr);
14296 SDValue SignExt = Curr;
14297 if (CurrVT != InVT) {
14298 unsigned SignExtShift =
14299 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14300 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14301 DAG.getConstant(SignExtShift, dl, MVT::i8));
14307 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14308 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14309 DAG.getConstant(31, dl, MVT::i8));
14310 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14311 return DAG.getBitcast(VT, Ext);
14317 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14318 SelectionDAG &DAG) {
14319 MVT VT = Op->getSimpleValueType(0);
14320 SDValue In = Op->getOperand(0);
14321 MVT InVT = In.getSimpleValueType();
14324 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14325 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14327 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14328 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14329 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14332 if (Subtarget->hasInt256())
14333 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14335 // Optimize vectors in AVX mode
14336 // Sign extend v8i16 to v8i32 and
14339 // Divide input vector into two parts
14340 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14341 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14342 // concat the vectors to original VT
14344 unsigned NumElems = InVT.getVectorNumElements();
14345 SDValue Undef = DAG.getUNDEF(InVT);
14347 SmallVector<int,8> ShufMask1(NumElems, -1);
14348 for (unsigned i = 0; i != NumElems/2; ++i)
14351 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14353 SmallVector<int,8> ShufMask2(NumElems, -1);
14354 for (unsigned i = 0; i != NumElems/2; ++i)
14355 ShufMask2[i] = i + NumElems/2;
14357 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14359 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14360 VT.getVectorNumElements()/2);
14362 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14363 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14365 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14368 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14369 // may emit an illegal shuffle but the expansion is still better than scalar
14370 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14371 // we'll emit a shuffle and a arithmetic shift.
14372 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14373 // TODO: It is possible to support ZExt by zeroing the undef values during
14374 // the shuffle phase or after the shuffle.
14375 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14376 SelectionDAG &DAG) {
14377 MVT RegVT = Op.getSimpleValueType();
14378 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14379 assert(RegVT.isInteger() &&
14380 "We only custom lower integer vector sext loads.");
14382 // Nothing useful we can do without SSE2 shuffles.
14383 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14385 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14387 EVT MemVT = Ld->getMemoryVT();
14388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14389 unsigned RegSz = RegVT.getSizeInBits();
14391 ISD::LoadExtType Ext = Ld->getExtensionType();
14393 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14394 && "Only anyext and sext are currently implemented.");
14395 assert(MemVT != RegVT && "Cannot extend to the same type");
14396 assert(MemVT.isVector() && "Must load a vector from memory");
14398 unsigned NumElems = RegVT.getVectorNumElements();
14399 unsigned MemSz = MemVT.getSizeInBits();
14400 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14402 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14403 // The only way in which we have a legal 256-bit vector result but not the
14404 // integer 256-bit operations needed to directly lower a sextload is if we
14405 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14406 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14407 // correctly legalized. We do this late to allow the canonical form of
14408 // sextload to persist throughout the rest of the DAG combiner -- it wants
14409 // to fold together any extensions it can, and so will fuse a sign_extend
14410 // of an sextload into a sextload targeting a wider value.
14412 if (MemSz == 128) {
14413 // Just switch this to a normal load.
14414 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14415 "it must be a legal 128-bit vector "
14417 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14418 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14419 Ld->isInvariant(), Ld->getAlignment());
14421 assert(MemSz < 128 &&
14422 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14423 // Do an sext load to a 128-bit vector type. We want to use the same
14424 // number of elements, but elements half as wide. This will end up being
14425 // recursively lowered by this routine, but will succeed as we definitely
14426 // have all the necessary features if we're using AVX1.
14428 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14429 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14431 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14432 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14433 Ld->isNonTemporal(), Ld->isInvariant(),
14434 Ld->getAlignment());
14437 // Replace chain users with the new chain.
14438 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14439 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14441 // Finally, do a normal sign-extend to the desired register.
14442 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14445 // All sizes must be a power of two.
14446 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14447 "Non-power-of-two elements are not custom lowered!");
14449 // Attempt to load the original value using scalar loads.
14450 // Find the largest scalar type that divides the total loaded size.
14451 MVT SclrLoadTy = MVT::i8;
14452 for (MVT Tp : MVT::integer_valuetypes()) {
14453 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14458 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14459 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14461 SclrLoadTy = MVT::f64;
14463 // Calculate the number of scalar loads that we need to perform
14464 // in order to load our vector from memory.
14465 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14467 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14468 "Can only lower sext loads with a single scalar load!");
14470 unsigned loadRegZize = RegSz;
14471 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14474 // Represent our vector as a sequence of elements which are the
14475 // largest scalar that we can load.
14476 EVT LoadUnitVecVT = EVT::getVectorVT(
14477 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14479 // Represent the data using the same element type that is stored in
14480 // memory. In practice, we ''widen'' MemVT.
14482 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14483 loadRegZize / MemVT.getScalarType().getSizeInBits());
14485 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14486 "Invalid vector type");
14488 // We can't shuffle using an illegal type.
14489 assert(TLI.isTypeLegal(WideVecVT) &&
14490 "We only lower types that form legal widened vector types");
14492 SmallVector<SDValue, 8> Chains;
14493 SDValue Ptr = Ld->getBasePtr();
14494 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14495 TLI.getPointerTy(DAG.getDataLayout()));
14496 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14498 for (unsigned i = 0; i < NumLoads; ++i) {
14499 // Perform a single load.
14500 SDValue ScalarLoad =
14501 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14502 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14503 Ld->getAlignment());
14504 Chains.push_back(ScalarLoad.getValue(1));
14505 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14506 // another round of DAGCombining.
14508 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14510 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14511 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14513 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14516 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14518 // Bitcast the loaded value to a vector of the original element type, in
14519 // the size of the target vector type.
14520 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14521 unsigned SizeRatio = RegSz / MemSz;
14523 if (Ext == ISD::SEXTLOAD) {
14524 // If we have SSE4.1, we can directly emit a VSEXT node.
14525 if (Subtarget->hasSSE41()) {
14526 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14527 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14531 // Otherwise we'll shuffle the small elements in the high bits of the
14532 // larger type and perform an arithmetic shift. If the shift is not legal
14533 // it's better to scalarize.
14534 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14535 "We can't implement a sext load without an arithmetic right shift!");
14537 // Redistribute the loaded elements into the different locations.
14538 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14539 for (unsigned i = 0; i != NumElems; ++i)
14540 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14542 SDValue Shuff = DAG.getVectorShuffle(
14543 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14545 Shuff = DAG.getBitcast(RegVT, Shuff);
14547 // Build the arithmetic shift.
14548 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14549 MemVT.getVectorElementType().getSizeInBits();
14551 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14552 DAG.getConstant(Amt, dl, RegVT));
14554 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14558 // Redistribute the loaded elements into the different locations.
14559 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14560 for (unsigned i = 0; i != NumElems; ++i)
14561 ShuffleVec[i * SizeRatio] = i;
14563 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14564 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14566 // Bitcast to the requested type.
14567 Shuff = DAG.getBitcast(RegVT, Shuff);
14568 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14572 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14573 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14574 // from the AND / OR.
14575 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14576 Opc = Op.getOpcode();
14577 if (Opc != ISD::OR && Opc != ISD::AND)
14579 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14580 Op.getOperand(0).hasOneUse() &&
14581 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14582 Op.getOperand(1).hasOneUse());
14585 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14586 // 1 and that the SETCC node has a single use.
14587 static bool isXor1OfSetCC(SDValue Op) {
14588 if (Op.getOpcode() != ISD::XOR)
14590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14591 if (N1C && N1C->getAPIntValue() == 1) {
14592 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14593 Op.getOperand(0).hasOneUse();
14598 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14599 bool addTest = true;
14600 SDValue Chain = Op.getOperand(0);
14601 SDValue Cond = Op.getOperand(1);
14602 SDValue Dest = Op.getOperand(2);
14605 bool Inverted = false;
14607 if (Cond.getOpcode() == ISD::SETCC) {
14608 // Check for setcc([su]{add,sub,mul}o == 0).
14609 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14610 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14611 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14612 Cond.getOperand(0).getResNo() == 1 &&
14613 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14614 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14615 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14616 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14617 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14618 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14620 Cond = Cond.getOperand(0);
14622 SDValue NewCond = LowerSETCC(Cond, DAG);
14623 if (NewCond.getNode())
14628 // FIXME: LowerXALUO doesn't handle these!!
14629 else if (Cond.getOpcode() == X86ISD::ADD ||
14630 Cond.getOpcode() == X86ISD::SUB ||
14631 Cond.getOpcode() == X86ISD::SMUL ||
14632 Cond.getOpcode() == X86ISD::UMUL)
14633 Cond = LowerXALUO(Cond, DAG);
14636 // Look pass (and (setcc_carry (cmp ...)), 1).
14637 if (Cond.getOpcode() == ISD::AND &&
14638 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14639 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14640 if (C && C->getAPIntValue() == 1)
14641 Cond = Cond.getOperand(0);
14644 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14645 // setting operand in place of the X86ISD::SETCC.
14646 unsigned CondOpcode = Cond.getOpcode();
14647 if (CondOpcode == X86ISD::SETCC ||
14648 CondOpcode == X86ISD::SETCC_CARRY) {
14649 CC = Cond.getOperand(0);
14651 SDValue Cmp = Cond.getOperand(1);
14652 unsigned Opc = Cmp.getOpcode();
14653 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14654 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14658 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14662 // These can only come from an arithmetic instruction with overflow,
14663 // e.g. SADDO, UADDO.
14664 Cond = Cond.getNode()->getOperand(1);
14670 CondOpcode = Cond.getOpcode();
14671 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14672 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14673 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14674 Cond.getOperand(0).getValueType() != MVT::i8)) {
14675 SDValue LHS = Cond.getOperand(0);
14676 SDValue RHS = Cond.getOperand(1);
14677 unsigned X86Opcode;
14680 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14681 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14683 switch (CondOpcode) {
14684 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14686 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14688 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14691 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14692 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14694 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14696 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14699 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14700 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14701 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14702 default: llvm_unreachable("unexpected overflowing operator");
14705 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14706 if (CondOpcode == ISD::UMULO)
14707 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14710 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14712 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14714 if (CondOpcode == ISD::UMULO)
14715 Cond = X86Op.getValue(2);
14717 Cond = X86Op.getValue(1);
14719 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14723 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14724 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14725 if (CondOpc == ISD::OR) {
14726 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14727 // two branches instead of an explicit OR instruction with a
14729 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14730 isX86LogicalCmp(Cmp)) {
14731 CC = Cond.getOperand(0).getOperand(0);
14732 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14733 Chain, Dest, CC, Cmp);
14734 CC = Cond.getOperand(1).getOperand(0);
14738 } else { // ISD::AND
14739 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14740 // two branches instead of an explicit AND instruction with a
14741 // separate test. However, we only do this if this block doesn't
14742 // have a fall-through edge, because this requires an explicit
14743 // jmp when the condition is false.
14744 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14745 isX86LogicalCmp(Cmp) &&
14746 Op.getNode()->hasOneUse()) {
14747 X86::CondCode CCode =
14748 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14749 CCode = X86::GetOppositeBranchCondition(CCode);
14750 CC = DAG.getConstant(CCode, dl, MVT::i8);
14751 SDNode *User = *Op.getNode()->use_begin();
14752 // Look for an unconditional branch following this conditional branch.
14753 // We need this because we need to reverse the successors in order
14754 // to implement FCMP_OEQ.
14755 if (User->getOpcode() == ISD::BR) {
14756 SDValue FalseBB = User->getOperand(1);
14758 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14759 assert(NewBR == User);
14763 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14764 Chain, Dest, CC, Cmp);
14765 X86::CondCode CCode =
14766 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14767 CCode = X86::GetOppositeBranchCondition(CCode);
14768 CC = DAG.getConstant(CCode, dl, MVT::i8);
14774 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14775 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14776 // It should be transformed during dag combiner except when the condition
14777 // is set by a arithmetics with overflow node.
14778 X86::CondCode CCode =
14779 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14780 CCode = X86::GetOppositeBranchCondition(CCode);
14781 CC = DAG.getConstant(CCode, dl, MVT::i8);
14782 Cond = Cond.getOperand(0).getOperand(1);
14784 } else if (Cond.getOpcode() == ISD::SETCC &&
14785 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14786 // For FCMP_OEQ, we can emit
14787 // two branches instead of an explicit AND instruction with a
14788 // separate test. However, we only do this if this block doesn't
14789 // have a fall-through edge, because this requires an explicit
14790 // jmp when the condition is false.
14791 if (Op.getNode()->hasOneUse()) {
14792 SDNode *User = *Op.getNode()->use_begin();
14793 // Look for an unconditional branch following this conditional branch.
14794 // We need this because we need to reverse the successors in order
14795 // to implement FCMP_OEQ.
14796 if (User->getOpcode() == ISD::BR) {
14797 SDValue FalseBB = User->getOperand(1);
14799 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14800 assert(NewBR == User);
14804 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14805 Cond.getOperand(0), Cond.getOperand(1));
14806 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14807 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14808 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14809 Chain, Dest, CC, Cmp);
14810 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14815 } else if (Cond.getOpcode() == ISD::SETCC &&
14816 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14817 // For FCMP_UNE, we can emit
14818 // two branches instead of an explicit AND instruction with a
14819 // separate test. However, we only do this if this block doesn't
14820 // have a fall-through edge, because this requires an explicit
14821 // jmp when the condition is false.
14822 if (Op.getNode()->hasOneUse()) {
14823 SDNode *User = *Op.getNode()->use_begin();
14824 // Look for an unconditional branch following this conditional branch.
14825 // We need this because we need to reverse the successors in order
14826 // to implement FCMP_UNE.
14827 if (User->getOpcode() == ISD::BR) {
14828 SDValue FalseBB = User->getOperand(1);
14830 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14831 assert(NewBR == User);
14834 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14835 Cond.getOperand(0), Cond.getOperand(1));
14836 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14837 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14838 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14839 Chain, Dest, CC, Cmp);
14840 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14850 // Look pass the truncate if the high bits are known zero.
14851 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14852 Cond = Cond.getOperand(0);
14854 // We know the result of AND is compared against zero. Try to match
14856 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14857 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14858 if (NewSetCC.getNode()) {
14859 CC = NewSetCC.getOperand(0);
14860 Cond = NewSetCC.getOperand(1);
14867 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14868 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14869 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14871 Cond = ConvertCmpIfNecessary(Cond, DAG);
14872 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14873 Chain, Dest, CC, Cond);
14876 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14877 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14878 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14879 // that the guard pages used by the OS virtual memory manager are allocated in
14880 // correct sequence.
14882 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14883 SelectionDAG &DAG) const {
14884 MachineFunction &MF = DAG.getMachineFunction();
14885 bool SplitStack = MF.shouldSplitStack();
14886 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14892 SDNode* Node = Op.getNode();
14894 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14895 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14896 " not tell us which reg is the stack pointer!");
14897 EVT VT = Node->getValueType(0);
14898 SDValue Tmp1 = SDValue(Node, 0);
14899 SDValue Tmp2 = SDValue(Node, 1);
14900 SDValue Tmp3 = Node->getOperand(2);
14901 SDValue Chain = Tmp1.getOperand(0);
14903 // Chain the dynamic stack allocation so that it doesn't modify the stack
14904 // pointer when other instructions are using the stack.
14905 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14908 SDValue Size = Tmp2.getOperand(1);
14909 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14910 Chain = SP.getValue(1);
14911 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14912 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14913 unsigned StackAlign = TFI.getStackAlignment();
14914 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14915 if (Align > StackAlign)
14916 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14917 DAG.getConstant(-(uint64_t)Align, dl, VT));
14918 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14920 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14921 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14924 SDValue Ops[2] = { Tmp1, Tmp2 };
14925 return DAG.getMergeValues(Ops, dl);
14929 SDValue Chain = Op.getOperand(0);
14930 SDValue Size = Op.getOperand(1);
14931 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14932 EVT VT = Op.getNode()->getValueType(0);
14934 bool Is64Bit = Subtarget->is64Bit();
14935 MVT SPTy = getPointerTy(DAG.getDataLayout());
14938 MachineRegisterInfo &MRI = MF.getRegInfo();
14941 // The 64 bit implementation of segmented stacks needs to clobber both r10
14942 // r11. This makes it impossible to use it along with nested parameters.
14943 const Function *F = MF.getFunction();
14945 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14947 if (I->hasNestAttr())
14948 report_fatal_error("Cannot use segmented stacks with functions that "
14949 "have nested arguments.");
14952 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14953 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14954 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14955 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14956 DAG.getRegister(Vreg, SPTy));
14957 SDValue Ops1[2] = { Value, Chain };
14958 return DAG.getMergeValues(Ops1, dl);
14961 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14963 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14964 Flag = Chain.getValue(1);
14965 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14967 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14969 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14970 unsigned SPReg = RegInfo->getStackRegister();
14971 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14972 Chain = SP.getValue(1);
14975 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14976 DAG.getConstant(-(uint64_t)Align, dl, VT));
14977 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14980 SDValue Ops1[2] = { SP, Chain };
14981 return DAG.getMergeValues(Ops1, dl);
14985 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14986 MachineFunction &MF = DAG.getMachineFunction();
14987 auto PtrVT = getPointerTy(MF.getDataLayout());
14988 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14990 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14993 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14994 // vastart just stores the address of the VarArgsFrameIndex slot into the
14995 // memory location argument.
14996 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14997 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14998 MachinePointerInfo(SV), false, false, 0);
15002 // gp_offset (0 - 6 * 8)
15003 // fp_offset (48 - 48 + 8 * 16)
15004 // overflow_arg_area (point to parameters coming in memory).
15006 SmallVector<SDValue, 8> MemOps;
15007 SDValue FIN = Op.getOperand(1);
15009 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15010 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15012 FIN, MachinePointerInfo(SV), false, false, 0);
15013 MemOps.push_back(Store);
15016 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15017 Store = DAG.getStore(Op.getOperand(0), DL,
15018 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15020 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15021 MemOps.push_back(Store);
15023 // Store ptr to overflow_arg_area
15024 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15025 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15026 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15027 MachinePointerInfo(SV, 8),
15029 MemOps.push_back(Store);
15031 // Store ptr to reg_save_area.
15032 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15033 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15034 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15035 MachinePointerInfo(SV, 16), false, false, 0);
15036 MemOps.push_back(Store);
15037 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15040 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15041 assert(Subtarget->is64Bit() &&
15042 "LowerVAARG only handles 64-bit va_arg!");
15043 assert((Subtarget->isTargetLinux() ||
15044 Subtarget->isTargetDarwin()) &&
15045 "Unhandled target in LowerVAARG");
15046 assert(Op.getNode()->getNumOperands() == 4);
15047 SDValue Chain = Op.getOperand(0);
15048 SDValue SrcPtr = Op.getOperand(1);
15049 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15050 unsigned Align = Op.getConstantOperandVal(3);
15053 EVT ArgVT = Op.getNode()->getValueType(0);
15054 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15055 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15058 // Decide which area this value should be read from.
15059 // TODO: Implement the AMD64 ABI in its entirety. This simple
15060 // selection mechanism works only for the basic types.
15061 if (ArgVT == MVT::f80) {
15062 llvm_unreachable("va_arg for f80 not yet implemented");
15063 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15064 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15065 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15066 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15068 llvm_unreachable("Unhandled argument type in LowerVAARG");
15071 if (ArgMode == 2) {
15072 // Sanity Check: Make sure using fp_offset makes sense.
15073 assert(!Subtarget->useSoftFloat() &&
15074 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15075 Attribute::NoImplicitFloat)) &&
15076 Subtarget->hasSSE1());
15079 // Insert VAARG_64 node into the DAG
15080 // VAARG_64 returns two values: Variable Argument Address, Chain
15081 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15082 DAG.getConstant(ArgMode, dl, MVT::i8),
15083 DAG.getConstant(Align, dl, MVT::i32)};
15084 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15085 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15086 VTs, InstOps, MVT::i64,
15087 MachinePointerInfo(SV),
15089 /*Volatile=*/false,
15091 /*WriteMem=*/true);
15092 Chain = VAARG.getValue(1);
15094 // Load the next argument and return it
15095 return DAG.getLoad(ArgVT, dl,
15098 MachinePointerInfo(),
15099 false, false, false, 0);
15102 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15103 SelectionDAG &DAG) {
15104 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15105 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15106 SDValue Chain = Op.getOperand(0);
15107 SDValue DstPtr = Op.getOperand(1);
15108 SDValue SrcPtr = Op.getOperand(2);
15109 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15110 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15113 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15114 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15116 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15119 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15120 // amount is a constant. Takes immediate version of shift as input.
15121 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15122 SDValue SrcOp, uint64_t ShiftAmt,
15123 SelectionDAG &DAG) {
15124 MVT ElementType = VT.getVectorElementType();
15126 // Fold this packed shift into its first operand if ShiftAmt is 0.
15130 // Check for ShiftAmt >= element width
15131 if (ShiftAmt >= ElementType.getSizeInBits()) {
15132 if (Opc == X86ISD::VSRAI)
15133 ShiftAmt = ElementType.getSizeInBits() - 1;
15135 return DAG.getConstant(0, dl, VT);
15138 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15139 && "Unknown target vector shift-by-constant node");
15141 // Fold this packed vector shift into a build vector if SrcOp is a
15142 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15143 if (VT == SrcOp.getSimpleValueType() &&
15144 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15145 SmallVector<SDValue, 8> Elts;
15146 unsigned NumElts = SrcOp->getNumOperands();
15147 ConstantSDNode *ND;
15150 default: llvm_unreachable(nullptr);
15151 case X86ISD::VSHLI:
15152 for (unsigned i=0; i!=NumElts; ++i) {
15153 SDValue CurrentOp = SrcOp->getOperand(i);
15154 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15155 Elts.push_back(CurrentOp);
15158 ND = cast<ConstantSDNode>(CurrentOp);
15159 const APInt &C = ND->getAPIntValue();
15160 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15163 case X86ISD::VSRLI:
15164 for (unsigned i=0; i!=NumElts; ++i) {
15165 SDValue CurrentOp = SrcOp->getOperand(i);
15166 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15167 Elts.push_back(CurrentOp);
15170 ND = cast<ConstantSDNode>(CurrentOp);
15171 const APInt &C = ND->getAPIntValue();
15172 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15175 case X86ISD::VSRAI:
15176 for (unsigned i=0; i!=NumElts; ++i) {
15177 SDValue CurrentOp = SrcOp->getOperand(i);
15178 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15179 Elts.push_back(CurrentOp);
15182 ND = cast<ConstantSDNode>(CurrentOp);
15183 const APInt &C = ND->getAPIntValue();
15184 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15189 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15192 return DAG.getNode(Opc, dl, VT, SrcOp,
15193 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15196 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15197 // may or may not be a constant. Takes immediate version of shift as input.
15198 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15199 SDValue SrcOp, SDValue ShAmt,
15200 SelectionDAG &DAG) {
15201 MVT SVT = ShAmt.getSimpleValueType();
15202 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15204 // Catch shift-by-constant.
15205 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15206 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15207 CShAmt->getZExtValue(), DAG);
15209 // Change opcode to non-immediate version
15211 default: llvm_unreachable("Unknown target vector shift node");
15212 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15213 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15214 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15217 const X86Subtarget &Subtarget =
15218 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15219 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15220 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15221 // Let the shuffle legalizer expand this shift amount node.
15222 SDValue Op0 = ShAmt.getOperand(0);
15223 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15224 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15226 // Need to build a vector containing shift amount.
15227 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15228 SmallVector<SDValue, 4> ShOps;
15229 ShOps.push_back(ShAmt);
15230 if (SVT == MVT::i32) {
15231 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15232 ShOps.push_back(DAG.getUNDEF(SVT));
15234 ShOps.push_back(DAG.getUNDEF(SVT));
15236 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15237 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15240 // The return type has to be a 128-bit type with the same element
15241 // type as the input type.
15242 MVT EltVT = VT.getVectorElementType();
15243 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15245 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15246 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15249 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15250 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15251 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15252 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15253 SDValue PreservedSrc,
15254 const X86Subtarget *Subtarget,
15255 SelectionDAG &DAG) {
15256 EVT VT = Op.getValueType();
15257 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15258 MVT::i1, VT.getVectorNumElements());
15259 SDValue VMask = SDValue();
15260 unsigned OpcodeSelect = ISD::VSELECT;
15263 assert(MaskVT.isSimple() && "invalid mask type");
15265 if (isAllOnes(Mask))
15268 if (MaskVT.bitsGT(Mask.getValueType())) {
15269 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15270 MaskVT.getSizeInBits());
15271 VMask = DAG.getBitcast(MaskVT,
15272 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15274 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15275 Mask.getValueType().getSizeInBits());
15276 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15277 // are extracted by EXTRACT_SUBVECTOR.
15278 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15279 DAG.getBitcast(BitcastVT, Mask),
15280 DAG.getIntPtrConstant(0, dl));
15283 switch (Op.getOpcode()) {
15285 case X86ISD::PCMPEQM:
15286 case X86ISD::PCMPGTM:
15288 case X86ISD::CMPMU:
15289 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15290 case X86ISD::VTRUNC:
15291 case X86ISD::VTRUNCS:
15292 case X86ISD::VTRUNCUS:
15293 // We can't use ISD::VSELECT here because it is not always "Legal"
15294 // for the destination type. For example vpmovqb require only AVX512
15295 // and vselect that can operate on byte element type require BWI
15296 OpcodeSelect = X86ISD::SELECT;
15299 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15300 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15301 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15304 /// \brief Creates an SDNode for a predicated scalar operation.
15305 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15306 /// The mask is comming as MVT::i8 and it should be truncated
15307 /// to MVT::i1 while lowering masking intrinsics.
15308 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15309 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15310 /// a scalar instruction.
15311 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15312 SDValue PreservedSrc,
15313 const X86Subtarget *Subtarget,
15314 SelectionDAG &DAG) {
15315 if (isAllOnes(Mask))
15318 EVT VT = Op.getValueType();
15320 // The mask should be of type MVT::i1
15321 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15323 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15324 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15325 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15328 static int getSEHRegistrationNodeSize(const Function *Fn) {
15329 if (!Fn->hasPersonalityFn())
15330 report_fatal_error(
15331 "querying registration node size for function without personality");
15332 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15333 // WinEHStatePass for the full struct definition.
15334 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15335 case EHPersonality::MSVC_X86SEH: return 24;
15336 case EHPersonality::MSVC_CXX: return 16;
15339 report_fatal_error("can only recover FP for MSVC EH personality functions");
15342 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15343 /// function or when returning to a parent frame after catching an exception, we
15344 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15345 /// Here's the math:
15346 /// RegNodeBase = EntryEBP - RegNodeSize
15347 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15348 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15349 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15350 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15351 SDValue EntryEBP) {
15352 MachineFunction &MF = DAG.getMachineFunction();
15355 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15356 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15358 // It's possible that the parent function no longer has a personality function
15359 // if the exceptional code was optimized away, in which case we just return
15360 // the incoming EBP.
15361 if (!Fn->hasPersonalityFn())
15364 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15366 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15368 MCSymbol *OffsetSym =
15369 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15370 GlobalValue::getRealLinkageName(Fn->getName()));
15371 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15372 SDValue RegNodeFrameOffset =
15373 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15375 // RegNodeBase = EntryEBP - RegNodeSize
15376 // ParentFP = RegNodeBase - RegNodeFrameOffset
15377 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15378 DAG.getConstant(RegNodeSize, dl, PtrVT));
15379 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15382 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15383 SelectionDAG &DAG) {
15385 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15386 EVT VT = Op.getValueType();
15387 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15389 switch(IntrData->Type) {
15390 case INTR_TYPE_1OP:
15391 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15392 case INTR_TYPE_2OP:
15393 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15395 case INTR_TYPE_3OP:
15396 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15397 Op.getOperand(2), Op.getOperand(3));
15398 case INTR_TYPE_4OP:
15399 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15400 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15401 case INTR_TYPE_1OP_MASK_RM: {
15402 SDValue Src = Op.getOperand(1);
15403 SDValue PassThru = Op.getOperand(2);
15404 SDValue Mask = Op.getOperand(3);
15405 SDValue RoundingMode;
15406 // We allways add rounding mode to the Node.
15407 // If the rounding mode is not specified, we add the
15408 // "current direction" mode.
15409 if (Op.getNumOperands() == 4)
15411 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15413 RoundingMode = Op.getOperand(4);
15414 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15415 if (IntrWithRoundingModeOpcode != 0)
15416 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15417 X86::STATIC_ROUNDING::CUR_DIRECTION)
15418 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15419 dl, Op.getValueType(), Src, RoundingMode),
15420 Mask, PassThru, Subtarget, DAG);
15421 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15423 Mask, PassThru, Subtarget, DAG);
15425 case INTR_TYPE_1OP_MASK: {
15426 SDValue Src = Op.getOperand(1);
15427 SDValue PassThru = Op.getOperand(2);
15428 SDValue Mask = Op.getOperand(3);
15429 // We add rounding mode to the Node when
15430 // - RM Opcode is specified and
15431 // - RM is not "current direction".
15432 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15433 if (IntrWithRoundingModeOpcode != 0) {
15434 SDValue Rnd = Op.getOperand(4);
15435 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15436 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15437 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438 dl, Op.getValueType(),
15440 Mask, PassThru, Subtarget, DAG);
15443 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15444 Mask, PassThru, Subtarget, DAG);
15446 case INTR_TYPE_SCALAR_MASK_RM: {
15447 SDValue Src1 = Op.getOperand(1);
15448 SDValue Src2 = Op.getOperand(2);
15449 SDValue Src0 = Op.getOperand(3);
15450 SDValue Mask = Op.getOperand(4);
15451 // There are 2 kinds of intrinsics in this group:
15452 // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15453 // (2) With rounding mode and sae - 7 operands.
15454 if (Op.getNumOperands() == 6) {
15455 SDValue Sae = Op.getOperand(5);
15456 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15457 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15459 Mask, Src0, Subtarget, DAG);
15461 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15462 SDValue RoundingMode = Op.getOperand(5);
15463 SDValue Sae = Op.getOperand(6);
15464 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15465 RoundingMode, Sae),
15466 Mask, Src0, Subtarget, DAG);
15468 case INTR_TYPE_2OP_MASK: {
15469 SDValue Src1 = Op.getOperand(1);
15470 SDValue Src2 = Op.getOperand(2);
15471 SDValue PassThru = Op.getOperand(3);
15472 SDValue Mask = Op.getOperand(4);
15473 // We specify 2 possible opcodes for intrinsics with rounding modes.
15474 // First, we check if the intrinsic may have non-default rounding mode,
15475 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15476 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15477 if (IntrWithRoundingModeOpcode != 0) {
15478 SDValue Rnd = Op.getOperand(5);
15479 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15480 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15481 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15482 dl, Op.getValueType(),
15484 Mask, PassThru, Subtarget, DAG);
15487 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15489 Mask, PassThru, Subtarget, DAG);
15491 case INTR_TYPE_2OP_MASK_RM: {
15492 SDValue Src1 = Op.getOperand(1);
15493 SDValue Src2 = Op.getOperand(2);
15494 SDValue PassThru = Op.getOperand(3);
15495 SDValue Mask = Op.getOperand(4);
15496 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15497 // First, we check if the intrinsic have rounding mode (6 operands),
15498 // if not, we set rounding mode to "current".
15500 if (Op.getNumOperands() == 6)
15501 Rnd = Op.getOperand(5);
15503 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15504 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15506 Mask, PassThru, Subtarget, DAG);
15508 case INTR_TYPE_3OP_MASK_RM: {
15509 SDValue Src1 = Op.getOperand(1);
15510 SDValue Src2 = Op.getOperand(2);
15511 SDValue Imm = Op.getOperand(3);
15512 SDValue PassThru = Op.getOperand(4);
15513 SDValue Mask = Op.getOperand(5);
15514 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15515 // First, we check if the intrinsic have rounding mode (7 operands),
15516 // if not, we set rounding mode to "current".
15518 if (Op.getNumOperands() == 7)
15519 Rnd = Op.getOperand(6);
15521 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15522 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15523 Src1, Src2, Imm, Rnd),
15524 Mask, PassThru, Subtarget, DAG);
15526 case INTR_TYPE_3OP_MASK: {
15527 SDValue Src1 = Op.getOperand(1);
15528 SDValue Src2 = Op.getOperand(2);
15529 SDValue Src3 = Op.getOperand(3);
15530 SDValue PassThru = Op.getOperand(4);
15531 SDValue Mask = Op.getOperand(5);
15532 // We specify 2 possible opcodes for intrinsics with rounding modes.
15533 // First, we check if the intrinsic may have non-default rounding mode,
15534 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15535 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15536 if (IntrWithRoundingModeOpcode != 0) {
15537 SDValue Rnd = Op.getOperand(6);
15538 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15539 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15540 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15541 dl, Op.getValueType(),
15542 Src1, Src2, Src3, Rnd),
15543 Mask, PassThru, Subtarget, DAG);
15546 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15548 Mask, PassThru, Subtarget, DAG);
15550 case VPERM_3OP_MASKZ:
15551 case VPERM_3OP_MASK:
15554 case FMA_OP_MASK: {
15555 SDValue Src1 = Op.getOperand(1);
15556 SDValue Src2 = Op.getOperand(2);
15557 SDValue Src3 = Op.getOperand(3);
15558 SDValue Mask = Op.getOperand(4);
15559 EVT VT = Op.getValueType();
15560 SDValue PassThru = SDValue();
15562 // set PassThru element
15563 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15564 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15565 else if (IntrData->Type == FMA_OP_MASK3)
15570 // We specify 2 possible opcodes for intrinsics with rounding modes.
15571 // First, we check if the intrinsic may have non-default rounding mode,
15572 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15573 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15574 if (IntrWithRoundingModeOpcode != 0) {
15575 SDValue Rnd = Op.getOperand(5);
15576 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15577 X86::STATIC_ROUNDING::CUR_DIRECTION)
15578 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15579 dl, Op.getValueType(),
15580 Src1, Src2, Src3, Rnd),
15581 Mask, PassThru, Subtarget, DAG);
15583 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15584 dl, Op.getValueType(),
15586 Mask, PassThru, Subtarget, DAG);
15589 case CMP_MASK_CC: {
15590 // Comparison intrinsics with masks.
15591 // Example of transformation:
15592 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15593 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15595 // (v8i1 (insert_subvector undef,
15596 // (v2i1 (and (PCMPEQM %a, %b),
15597 // (extract_subvector
15598 // (v8i1 (bitcast %mask)), 0))), 0))))
15599 EVT VT = Op.getOperand(1).getValueType();
15600 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15601 VT.getVectorNumElements());
15602 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15603 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15604 Mask.getValueType().getSizeInBits());
15606 if (IntrData->Type == CMP_MASK_CC) {
15607 SDValue CC = Op.getOperand(3);
15608 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15609 // We specify 2 possible opcodes for intrinsics with rounding modes.
15610 // First, we check if the intrinsic may have non-default rounding mode,
15611 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15612 if (IntrData->Opc1 != 0) {
15613 SDValue Rnd = Op.getOperand(5);
15614 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15615 X86::STATIC_ROUNDING::CUR_DIRECTION)
15616 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15617 Op.getOperand(2), CC, Rnd);
15619 //default rounding mode
15621 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15622 Op.getOperand(2), CC);
15625 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15626 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15629 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15630 DAG.getTargetConstant(0, dl,
15633 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15634 DAG.getUNDEF(BitcastVT), CmpMask,
15635 DAG.getIntPtrConstant(0, dl));
15636 return DAG.getBitcast(Op.getValueType(), Res);
15638 case COMI: { // Comparison intrinsics
15639 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15640 SDValue LHS = Op.getOperand(1);
15641 SDValue RHS = Op.getOperand(2);
15642 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15643 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15644 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15645 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15646 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15647 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15650 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15651 Op.getOperand(1), Op.getOperand(2), DAG);
15653 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15654 Op.getSimpleValueType(),
15656 Op.getOperand(2), DAG),
15657 Op.getOperand(4), Op.getOperand(3), Subtarget,
15659 case COMPRESS_EXPAND_IN_REG: {
15660 SDValue Mask = Op.getOperand(3);
15661 SDValue DataToCompress = Op.getOperand(1);
15662 SDValue PassThru = Op.getOperand(2);
15663 if (isAllOnes(Mask)) // return data as is
15664 return Op.getOperand(1);
15666 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15668 Mask, PassThru, Subtarget, DAG);
15671 SDValue Mask = Op.getOperand(3);
15672 EVT VT = Op.getValueType();
15673 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15674 VT.getVectorNumElements());
15675 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15676 Mask.getValueType().getSizeInBits());
15678 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15679 DAG.getBitcast(BitcastVT, Mask),
15680 DAG.getIntPtrConstant(0, dl));
15681 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15690 default: return SDValue(); // Don't custom lower most intrinsics.
15692 case Intrinsic::x86_avx2_permd:
15693 case Intrinsic::x86_avx2_permps:
15694 // Operands intentionally swapped. Mask is last operand to intrinsic,
15695 // but second operand for node/instruction.
15696 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15697 Op.getOperand(2), Op.getOperand(1));
15699 // ptest and testp intrinsics. The intrinsic these come from are designed to
15700 // return an integer value, not just an instruction so lower it to the ptest
15701 // or testp pattern and a setcc for the result.
15702 case Intrinsic::x86_sse41_ptestz:
15703 case Intrinsic::x86_sse41_ptestc:
15704 case Intrinsic::x86_sse41_ptestnzc:
15705 case Intrinsic::x86_avx_ptestz_256:
15706 case Intrinsic::x86_avx_ptestc_256:
15707 case Intrinsic::x86_avx_ptestnzc_256:
15708 case Intrinsic::x86_avx_vtestz_ps:
15709 case Intrinsic::x86_avx_vtestc_ps:
15710 case Intrinsic::x86_avx_vtestnzc_ps:
15711 case Intrinsic::x86_avx_vtestz_pd:
15712 case Intrinsic::x86_avx_vtestc_pd:
15713 case Intrinsic::x86_avx_vtestnzc_pd:
15714 case Intrinsic::x86_avx_vtestz_ps_256:
15715 case Intrinsic::x86_avx_vtestc_ps_256:
15716 case Intrinsic::x86_avx_vtestnzc_ps_256:
15717 case Intrinsic::x86_avx_vtestz_pd_256:
15718 case Intrinsic::x86_avx_vtestc_pd_256:
15719 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15720 bool IsTestPacked = false;
15723 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15724 case Intrinsic::x86_avx_vtestz_ps:
15725 case Intrinsic::x86_avx_vtestz_pd:
15726 case Intrinsic::x86_avx_vtestz_ps_256:
15727 case Intrinsic::x86_avx_vtestz_pd_256:
15728 IsTestPacked = true; // Fallthrough
15729 case Intrinsic::x86_sse41_ptestz:
15730 case Intrinsic::x86_avx_ptestz_256:
15732 X86CC = X86::COND_E;
15734 case Intrinsic::x86_avx_vtestc_ps:
15735 case Intrinsic::x86_avx_vtestc_pd:
15736 case Intrinsic::x86_avx_vtestc_ps_256:
15737 case Intrinsic::x86_avx_vtestc_pd_256:
15738 IsTestPacked = true; // Fallthrough
15739 case Intrinsic::x86_sse41_ptestc:
15740 case Intrinsic::x86_avx_ptestc_256:
15742 X86CC = X86::COND_B;
15744 case Intrinsic::x86_avx_vtestnzc_ps:
15745 case Intrinsic::x86_avx_vtestnzc_pd:
15746 case Intrinsic::x86_avx_vtestnzc_ps_256:
15747 case Intrinsic::x86_avx_vtestnzc_pd_256:
15748 IsTestPacked = true; // Fallthrough
15749 case Intrinsic::x86_sse41_ptestnzc:
15750 case Intrinsic::x86_avx_ptestnzc_256:
15752 X86CC = X86::COND_A;
15756 SDValue LHS = Op.getOperand(1);
15757 SDValue RHS = Op.getOperand(2);
15758 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15759 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15760 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15761 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15762 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15764 case Intrinsic::x86_avx512_kortestz_w:
15765 case Intrinsic::x86_avx512_kortestc_w: {
15766 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15767 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15768 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15769 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15770 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15771 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15772 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15775 case Intrinsic::x86_sse42_pcmpistria128:
15776 case Intrinsic::x86_sse42_pcmpestria128:
15777 case Intrinsic::x86_sse42_pcmpistric128:
15778 case Intrinsic::x86_sse42_pcmpestric128:
15779 case Intrinsic::x86_sse42_pcmpistrio128:
15780 case Intrinsic::x86_sse42_pcmpestrio128:
15781 case Intrinsic::x86_sse42_pcmpistris128:
15782 case Intrinsic::x86_sse42_pcmpestris128:
15783 case Intrinsic::x86_sse42_pcmpistriz128:
15784 case Intrinsic::x86_sse42_pcmpestriz128: {
15788 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15789 case Intrinsic::x86_sse42_pcmpistria128:
15790 Opcode = X86ISD::PCMPISTRI;
15791 X86CC = X86::COND_A;
15793 case Intrinsic::x86_sse42_pcmpestria128:
15794 Opcode = X86ISD::PCMPESTRI;
15795 X86CC = X86::COND_A;
15797 case Intrinsic::x86_sse42_pcmpistric128:
15798 Opcode = X86ISD::PCMPISTRI;
15799 X86CC = X86::COND_B;
15801 case Intrinsic::x86_sse42_pcmpestric128:
15802 Opcode = X86ISD::PCMPESTRI;
15803 X86CC = X86::COND_B;
15805 case Intrinsic::x86_sse42_pcmpistrio128:
15806 Opcode = X86ISD::PCMPISTRI;
15807 X86CC = X86::COND_O;
15809 case Intrinsic::x86_sse42_pcmpestrio128:
15810 Opcode = X86ISD::PCMPESTRI;
15811 X86CC = X86::COND_O;
15813 case Intrinsic::x86_sse42_pcmpistris128:
15814 Opcode = X86ISD::PCMPISTRI;
15815 X86CC = X86::COND_S;
15817 case Intrinsic::x86_sse42_pcmpestris128:
15818 Opcode = X86ISD::PCMPESTRI;
15819 X86CC = X86::COND_S;
15821 case Intrinsic::x86_sse42_pcmpistriz128:
15822 Opcode = X86ISD::PCMPISTRI;
15823 X86CC = X86::COND_E;
15825 case Intrinsic::x86_sse42_pcmpestriz128:
15826 Opcode = X86ISD::PCMPESTRI;
15827 X86CC = X86::COND_E;
15830 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15831 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15832 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15833 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15834 DAG.getConstant(X86CC, dl, MVT::i8),
15835 SDValue(PCMP.getNode(), 1));
15836 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15839 case Intrinsic::x86_sse42_pcmpistri128:
15840 case Intrinsic::x86_sse42_pcmpestri128: {
15842 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15843 Opcode = X86ISD::PCMPISTRI;
15845 Opcode = X86ISD::PCMPESTRI;
15847 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15848 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15849 return DAG.getNode(Opcode, dl, VTs, NewOps);
15852 case Intrinsic::x86_seh_lsda: {
15853 // Compute the symbol for the LSDA. We know it'll get emitted later.
15854 MachineFunction &MF = DAG.getMachineFunction();
15855 SDValue Op1 = Op.getOperand(1);
15856 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15857 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15858 GlobalValue::getRealLinkageName(Fn->getName()));
15860 // Generate a simple absolute symbol reference. This intrinsic is only
15861 // supported on 32-bit Windows, which isn't PIC.
15862 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15863 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15866 case Intrinsic::x86_seh_recoverfp: {
15867 SDValue FnOp = Op.getOperand(1);
15868 SDValue IncomingFPOp = Op.getOperand(2);
15869 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15870 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15872 report_fatal_error(
15873 "llvm.x86.seh.recoverfp must take a function as the first argument");
15874 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15877 case Intrinsic::localaddress: {
15878 // Returns one of the stack, base, or frame pointer registers, depending on
15879 // which is used to reference local variables.
15880 MachineFunction &MF = DAG.getMachineFunction();
15881 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15883 if (RegInfo->hasBasePointer(MF))
15884 Reg = RegInfo->getBaseRegister();
15885 else // This function handles the SP or FP case.
15886 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15887 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15892 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15893 SDValue Src, SDValue Mask, SDValue Base,
15894 SDValue Index, SDValue ScaleOp, SDValue Chain,
15895 const X86Subtarget * Subtarget) {
15897 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15899 llvm_unreachable("Invalid scale type");
15900 unsigned ScaleVal = C->getZExtValue();
15901 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15902 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15904 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15905 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15906 Index.getSimpleValueType().getVectorNumElements());
15908 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15910 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15912 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15913 Mask.getValueType().getSizeInBits());
15915 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15916 // are extracted by EXTRACT_SUBVECTOR.
15917 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15918 DAG.getBitcast(BitcastVT, Mask),
15919 DAG.getIntPtrConstant(0, dl));
15921 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15922 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15923 SDValue Segment = DAG.getRegister(0, MVT::i32);
15924 if (Src.getOpcode() == ISD::UNDEF)
15925 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15926 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15927 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15928 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15929 return DAG.getMergeValues(RetOps, dl);
15932 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15933 SDValue Src, SDValue Mask, SDValue Base,
15934 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15936 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15938 llvm_unreachable("Invalid scale type");
15939 unsigned ScaleVal = C->getZExtValue();
15940 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15941 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15943 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15944 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15945 SDValue Segment = DAG.getRegister(0, MVT::i32);
15946 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15947 Index.getSimpleValueType().getVectorNumElements());
15949 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15951 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15953 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15954 Mask.getValueType().getSizeInBits());
15956 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15957 // are extracted by EXTRACT_SUBVECTOR.
15958 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15959 DAG.getBitcast(BitcastVT, Mask),
15960 DAG.getIntPtrConstant(0, dl));
15962 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15963 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15964 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15965 return SDValue(Res, 1);
15968 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15969 SDValue Mask, SDValue Base, SDValue Index,
15970 SDValue ScaleOp, SDValue Chain) {
15972 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15973 assert(C && "Invalid scale type");
15974 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15975 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15976 SDValue Segment = DAG.getRegister(0, MVT::i32);
15978 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15980 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15982 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15984 MaskInReg = DAG.getBitcast(MaskVT, Mask);
15985 //SDVTList VTs = DAG.getVTList(MVT::Other);
15986 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15987 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15988 return SDValue(Res, 0);
15991 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15992 // read performance monitor counters (x86_rdpmc).
15993 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15994 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15995 SmallVectorImpl<SDValue> &Results) {
15996 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15997 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16000 // The ECX register is used to select the index of the performance counter
16002 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16004 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16006 // Reads the content of a 64-bit performance counter and returns it in the
16007 // registers EDX:EAX.
16008 if (Subtarget->is64Bit()) {
16009 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16010 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16013 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16014 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16017 Chain = HI.getValue(1);
16019 if (Subtarget->is64Bit()) {
16020 // The EAX register is loaded with the low-order 32 bits. The EDX register
16021 // is loaded with the supported high-order bits of the counter.
16022 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16023 DAG.getConstant(32, DL, MVT::i8));
16024 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16025 Results.push_back(Chain);
16029 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16030 SDValue Ops[] = { LO, HI };
16031 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16032 Results.push_back(Pair);
16033 Results.push_back(Chain);
16036 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16037 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16038 // also used to custom lower READCYCLECOUNTER nodes.
16039 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16040 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16041 SmallVectorImpl<SDValue> &Results) {
16042 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16043 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16046 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16047 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16048 // and the EAX register is loaded with the low-order 32 bits.
16049 if (Subtarget->is64Bit()) {
16050 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16051 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16054 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16055 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16058 SDValue Chain = HI.getValue(1);
16060 if (Opcode == X86ISD::RDTSCP_DAG) {
16061 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16063 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16064 // the ECX register. Add 'ecx' explicitly to the chain.
16065 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16067 // Explicitly store the content of ECX at the location passed in input
16068 // to the 'rdtscp' intrinsic.
16069 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16070 MachinePointerInfo(), false, false, 0);
16073 if (Subtarget->is64Bit()) {
16074 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16075 // the EAX register is loaded with the low-order 32 bits.
16076 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16077 DAG.getConstant(32, DL, MVT::i8));
16078 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16079 Results.push_back(Chain);
16083 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16084 SDValue Ops[] = { LO, HI };
16085 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16086 Results.push_back(Pair);
16087 Results.push_back(Chain);
16090 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16091 SelectionDAG &DAG) {
16092 SmallVector<SDValue, 2> Results;
16094 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16096 return DAG.getMergeValues(Results, DL);
16099 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16100 SelectionDAG &DAG) {
16101 MachineFunction &MF = DAG.getMachineFunction();
16102 const Function *Fn = MF.getFunction();
16104 SDValue Chain = Op.getOperand(0);
16106 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16107 "using llvm.x86.seh.restoreframe requires a frame pointer");
16109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16110 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16112 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16113 unsigned FrameReg =
16114 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16115 unsigned SPReg = RegInfo->getStackRegister();
16116 unsigned SlotSize = RegInfo->getSlotSize();
16118 // Get incoming EBP.
16119 SDValue IncomingEBP =
16120 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16122 // SP is saved in the first field of every registration node, so load
16123 // [EBP-RegNodeSize] into SP.
16124 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16125 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16126 DAG.getConstant(-RegNodeSize, dl, VT));
16128 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16129 false, VT.getScalarSizeInBits() / 8);
16130 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16132 if (!RegInfo->needsStackRealignment(MF)) {
16133 // Adjust EBP to point back to the original frame position.
16134 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16135 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16137 assert(RegInfo->hasBasePointer(MF) &&
16138 "functions with Win32 EH must use frame or base pointer register");
16140 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16141 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16142 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16144 // Reload the spilled EBP value, now that the stack and base pointers are
16146 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16147 X86FI->setHasSEHFramePtrSave(true);
16148 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16149 X86FI->setSEHFramePtrSaveIndex(FI);
16150 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16151 MachinePointerInfo(), false, false, false,
16152 VT.getScalarSizeInBits() / 8);
16153 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16159 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16160 /// return truncate Store/MaskedStore Node
16161 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16165 SDValue Mask = Op.getOperand(4);
16166 SDValue DataToTruncate = Op.getOperand(3);
16167 SDValue Addr = Op.getOperand(2);
16168 SDValue Chain = Op.getOperand(0);
16170 EVT VT = DataToTruncate.getValueType();
16171 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16172 ElementType, VT.getVectorNumElements());
16174 if (isAllOnes(Mask)) // return just a truncate store
16175 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16176 MachinePointerInfo(), SVT, false, false,
16177 SVT.getScalarSizeInBits()/8);
16179 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16180 MVT::i1, VT.getVectorNumElements());
16181 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16182 Mask.getValueType().getSizeInBits());
16183 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16184 // are extracted by EXTRACT_SUBVECTOR.
16185 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16186 DAG.getBitcast(BitcastVT, Mask),
16187 DAG.getIntPtrConstant(0, dl));
16189 MachineMemOperand *MMO = DAG.getMachineFunction().
16190 getMachineMemOperand(MachinePointerInfo(),
16191 MachineMemOperand::MOStore, SVT.getStoreSize(),
16192 SVT.getScalarSizeInBits()/8);
16194 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16195 VMask, SVT, MMO, true);
16198 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16199 SelectionDAG &DAG) {
16200 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16202 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16204 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16205 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16210 switch(IntrData->Type) {
16212 llvm_unreachable("Unknown Intrinsic Type");
16216 // Emit the node with the right value type.
16217 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16218 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16220 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16221 // Otherwise return the value from Rand, which is always 0, casted to i32.
16222 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16223 DAG.getConstant(1, dl, Op->getValueType(1)),
16224 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16225 SDValue(Result.getNode(), 1) };
16226 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16227 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16230 // Return { result, isValid, chain }.
16231 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16232 SDValue(Result.getNode(), 2));
16235 //gather(v1, mask, index, base, scale);
16236 SDValue Chain = Op.getOperand(0);
16237 SDValue Src = Op.getOperand(2);
16238 SDValue Base = Op.getOperand(3);
16239 SDValue Index = Op.getOperand(4);
16240 SDValue Mask = Op.getOperand(5);
16241 SDValue Scale = Op.getOperand(6);
16242 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16246 //scatter(base, mask, index, v1, scale);
16247 SDValue Chain = Op.getOperand(0);
16248 SDValue Base = Op.getOperand(2);
16249 SDValue Mask = Op.getOperand(3);
16250 SDValue Index = Op.getOperand(4);
16251 SDValue Src = Op.getOperand(5);
16252 SDValue Scale = Op.getOperand(6);
16253 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16257 SDValue Hint = Op.getOperand(6);
16258 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16259 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16260 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16261 SDValue Chain = Op.getOperand(0);
16262 SDValue Mask = Op.getOperand(2);
16263 SDValue Index = Op.getOperand(3);
16264 SDValue Base = Op.getOperand(4);
16265 SDValue Scale = Op.getOperand(5);
16266 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16268 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16270 SmallVector<SDValue, 2> Results;
16271 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16273 return DAG.getMergeValues(Results, dl);
16275 // Read Performance Monitoring Counters.
16277 SmallVector<SDValue, 2> Results;
16278 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16279 return DAG.getMergeValues(Results, dl);
16281 // XTEST intrinsics.
16283 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16284 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16285 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16286 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16288 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16289 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16290 Ret, SDValue(InTrans.getNode(), 1));
16294 SmallVector<SDValue, 2> Results;
16295 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16296 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16297 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16298 DAG.getConstant(-1, dl, MVT::i8));
16299 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16300 Op.getOperand(4), GenCF.getValue(1));
16301 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16302 Op.getOperand(5), MachinePointerInfo(),
16304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16305 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16307 Results.push_back(SetCC);
16308 Results.push_back(Store);
16309 return DAG.getMergeValues(Results, dl);
16311 case COMPRESS_TO_MEM: {
16313 SDValue Mask = Op.getOperand(4);
16314 SDValue DataToCompress = Op.getOperand(3);
16315 SDValue Addr = Op.getOperand(2);
16316 SDValue Chain = Op.getOperand(0);
16318 EVT VT = DataToCompress.getValueType();
16319 if (isAllOnes(Mask)) // return just a store
16320 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16321 MachinePointerInfo(), false, false,
16322 VT.getScalarSizeInBits()/8);
16324 SDValue Compressed =
16325 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16326 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16327 return DAG.getStore(Chain, dl, Compressed, Addr,
16328 MachinePointerInfo(), false, false,
16329 VT.getScalarSizeInBits()/8);
16331 case TRUNCATE_TO_MEM_VI8:
16332 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16333 case TRUNCATE_TO_MEM_VI16:
16334 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16335 case TRUNCATE_TO_MEM_VI32:
16336 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16337 case EXPAND_FROM_MEM: {
16339 SDValue Mask = Op.getOperand(4);
16340 SDValue PassThru = Op.getOperand(3);
16341 SDValue Addr = Op.getOperand(2);
16342 SDValue Chain = Op.getOperand(0);
16343 EVT VT = Op.getValueType();
16345 if (isAllOnes(Mask)) // return just a load
16346 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16347 false, VT.getScalarSizeInBits()/8);
16349 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16350 false, false, false,
16351 VT.getScalarSizeInBits()/8);
16353 SDValue Results[] = {
16354 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16355 Mask, PassThru, Subtarget, DAG), Chain};
16356 return DAG.getMergeValues(Results, dl);
16361 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16362 SelectionDAG &DAG) const {
16363 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16364 MFI->setReturnAddressIsTaken(true);
16366 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16369 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16371 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16374 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16375 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16376 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16377 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16378 DAG.getNode(ISD::ADD, dl, PtrVT,
16379 FrameAddr, Offset),
16380 MachinePointerInfo(), false, false, false, 0);
16383 // Just load the return address.
16384 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16385 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16386 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16389 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16390 MachineFunction &MF = DAG.getMachineFunction();
16391 MachineFrameInfo *MFI = MF.getFrameInfo();
16392 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16393 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16394 EVT VT = Op.getValueType();
16396 MFI->setFrameAddressIsTaken(true);
16398 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16399 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16400 // is not possible to crawl up the stack without looking at the unwind codes
16402 int FrameAddrIndex = FuncInfo->getFAIndex();
16403 if (!FrameAddrIndex) {
16404 // Set up a frame object for the return address.
16405 unsigned SlotSize = RegInfo->getSlotSize();
16406 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16407 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16408 FuncInfo->setFAIndex(FrameAddrIndex);
16410 return DAG.getFrameIndex(FrameAddrIndex, VT);
16413 unsigned FrameReg =
16414 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16415 SDLoc dl(Op); // FIXME probably not meaningful
16416 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16417 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16418 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16419 "Invalid Frame Register!");
16420 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16422 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16423 MachinePointerInfo(),
16424 false, false, false, 0);
16428 // FIXME? Maybe this could be a TableGen attribute on some registers and
16429 // this table could be generated automatically from RegInfo.
16430 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16431 SelectionDAG &DAG) const {
16432 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16433 const MachineFunction &MF = DAG.getMachineFunction();
16435 unsigned Reg = StringSwitch<unsigned>(RegName)
16436 .Case("esp", X86::ESP)
16437 .Case("rsp", X86::RSP)
16438 .Case("ebp", X86::EBP)
16439 .Case("rbp", X86::RBP)
16442 if (Reg == X86::EBP || Reg == X86::RBP) {
16443 if (!TFI.hasFP(MF))
16444 report_fatal_error("register " + StringRef(RegName) +
16445 " is allocatable: function has no frame pointer");
16448 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16449 unsigned FrameReg =
16450 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16451 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16452 "Invalid Frame Register!");
16460 report_fatal_error("Invalid register name global variable");
16463 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16464 SelectionDAG &DAG) const {
16465 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16466 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16469 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16470 SDValue Chain = Op.getOperand(0);
16471 SDValue Offset = Op.getOperand(1);
16472 SDValue Handler = Op.getOperand(2);
16475 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16476 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16477 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16478 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16479 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16480 "Invalid Frame Register!");
16481 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16482 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16484 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16485 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16487 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16488 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16490 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16492 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16493 DAG.getRegister(StoreAddrReg, PtrVT));
16496 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16497 SelectionDAG &DAG) const {
16499 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16500 DAG.getVTList(MVT::i32, MVT::Other),
16501 Op.getOperand(0), Op.getOperand(1));
16504 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16505 SelectionDAG &DAG) const {
16507 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16508 Op.getOperand(0), Op.getOperand(1));
16511 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16512 return Op.getOperand(0);
16515 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16516 SelectionDAG &DAG) const {
16517 SDValue Root = Op.getOperand(0);
16518 SDValue Trmp = Op.getOperand(1); // trampoline
16519 SDValue FPtr = Op.getOperand(2); // nested function
16520 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16523 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16524 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16526 if (Subtarget->is64Bit()) {
16527 SDValue OutChains[6];
16529 // Large code-model.
16530 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16531 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16533 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16534 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16536 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16538 // Load the pointer to the nested function into R11.
16539 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16540 SDValue Addr = Trmp;
16541 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16542 Addr, MachinePointerInfo(TrmpAddr),
16545 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16546 DAG.getConstant(2, dl, MVT::i64));
16547 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16548 MachinePointerInfo(TrmpAddr, 2),
16551 // Load the 'nest' parameter value into R10.
16552 // R10 is specified in X86CallingConv.td
16553 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16554 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16555 DAG.getConstant(10, dl, MVT::i64));
16556 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16557 Addr, MachinePointerInfo(TrmpAddr, 10),
16560 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16561 DAG.getConstant(12, dl, MVT::i64));
16562 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16563 MachinePointerInfo(TrmpAddr, 12),
16566 // Jump to the nested function.
16567 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16568 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16569 DAG.getConstant(20, dl, MVT::i64));
16570 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16571 Addr, MachinePointerInfo(TrmpAddr, 20),
16574 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16575 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16576 DAG.getConstant(22, dl, MVT::i64));
16577 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16578 Addr, MachinePointerInfo(TrmpAddr, 22),
16581 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16583 const Function *Func =
16584 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16585 CallingConv::ID CC = Func->getCallingConv();
16590 llvm_unreachable("Unsupported calling convention");
16591 case CallingConv::C:
16592 case CallingConv::X86_StdCall: {
16593 // Pass 'nest' parameter in ECX.
16594 // Must be kept in sync with X86CallingConv.td
16595 NestReg = X86::ECX;
16597 // Check that ECX wasn't needed by an 'inreg' parameter.
16598 FunctionType *FTy = Func->getFunctionType();
16599 const AttributeSet &Attrs = Func->getAttributes();
16601 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16602 unsigned InRegCount = 0;
16605 for (FunctionType::param_iterator I = FTy->param_begin(),
16606 E = FTy->param_end(); I != E; ++I, ++Idx)
16607 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16608 auto &DL = DAG.getDataLayout();
16609 // FIXME: should only count parameters that are lowered to integers.
16610 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16613 if (InRegCount > 2) {
16614 report_fatal_error("Nest register in use - reduce number of inreg"
16620 case CallingConv::X86_FastCall:
16621 case CallingConv::X86_ThisCall:
16622 case CallingConv::Fast:
16623 // Pass 'nest' parameter in EAX.
16624 // Must be kept in sync with X86CallingConv.td
16625 NestReg = X86::EAX;
16629 SDValue OutChains[4];
16630 SDValue Addr, Disp;
16632 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16633 DAG.getConstant(10, dl, MVT::i32));
16634 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16636 // This is storing the opcode for MOV32ri.
16637 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16638 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16639 OutChains[0] = DAG.getStore(Root, dl,
16640 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16641 Trmp, MachinePointerInfo(TrmpAddr),
16644 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16645 DAG.getConstant(1, dl, MVT::i32));
16646 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16647 MachinePointerInfo(TrmpAddr, 1),
16650 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16652 DAG.getConstant(5, dl, MVT::i32));
16653 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16654 Addr, MachinePointerInfo(TrmpAddr, 5),
16657 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16658 DAG.getConstant(6, dl, MVT::i32));
16659 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16660 MachinePointerInfo(TrmpAddr, 6),
16663 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16667 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16668 SelectionDAG &DAG) const {
16670 The rounding mode is in bits 11:10 of FPSR, and has the following
16672 00 Round to nearest
16677 FLT_ROUNDS, on the other hand, expects the following:
16684 To perform the conversion, we do:
16685 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16688 MachineFunction &MF = DAG.getMachineFunction();
16689 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16690 unsigned StackAlignment = TFI.getStackAlignment();
16691 MVT VT = Op.getSimpleValueType();
16694 // Save FP Control Word to stack slot
16695 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16696 SDValue StackSlot =
16697 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16699 MachineMemOperand *MMO =
16700 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16701 MachineMemOperand::MOStore, 2, 2);
16703 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16704 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16705 DAG.getVTList(MVT::Other),
16706 Ops, MVT::i16, MMO);
16708 // Load FP Control Word from stack slot
16709 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16710 MachinePointerInfo(), false, false, false, 0);
16712 // Transform as necessary
16714 DAG.getNode(ISD::SRL, DL, MVT::i16,
16715 DAG.getNode(ISD::AND, DL, MVT::i16,
16716 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16717 DAG.getConstant(11, DL, MVT::i8));
16719 DAG.getNode(ISD::SRL, DL, MVT::i16,
16720 DAG.getNode(ISD::AND, DL, MVT::i16,
16721 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16722 DAG.getConstant(9, DL, MVT::i8));
16725 DAG.getNode(ISD::AND, DL, MVT::i16,
16726 DAG.getNode(ISD::ADD, DL, MVT::i16,
16727 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16728 DAG.getConstant(1, DL, MVT::i16)),
16729 DAG.getConstant(3, DL, MVT::i16));
16731 return DAG.getNode((VT.getSizeInBits() < 16 ?
16732 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16735 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16736 MVT VT = Op.getSimpleValueType();
16738 unsigned NumBits = VT.getSizeInBits();
16741 Op = Op.getOperand(0);
16742 if (VT == MVT::i8) {
16743 // Zero extend to i32 since there is not an i8 bsr.
16745 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16748 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16749 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16750 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16752 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16755 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16756 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16759 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16761 // Finally xor with NumBits-1.
16762 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16763 DAG.getConstant(NumBits - 1, dl, OpVT));
16766 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16770 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16771 MVT VT = Op.getSimpleValueType();
16773 unsigned NumBits = VT.getSizeInBits();
16776 Op = Op.getOperand(0);
16777 if (VT == MVT::i8) {
16778 // Zero extend to i32 since there is not an i8 bsr.
16780 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16783 // Issue a bsr (scan bits in reverse).
16784 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16785 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16787 // And xor with NumBits-1.
16788 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16789 DAG.getConstant(NumBits - 1, dl, OpVT));
16792 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16796 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16797 MVT VT = Op.getSimpleValueType();
16798 unsigned NumBits = VT.getSizeInBits();
16800 Op = Op.getOperand(0);
16802 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16803 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16804 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16806 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16809 DAG.getConstant(NumBits, dl, VT),
16810 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16813 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16816 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16817 // ones, and then concatenate the result back.
16818 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16819 MVT VT = Op.getSimpleValueType();
16821 assert(VT.is256BitVector() && VT.isInteger() &&
16822 "Unsupported value type for operation");
16824 unsigned NumElems = VT.getVectorNumElements();
16827 // Extract the LHS vectors
16828 SDValue LHS = Op.getOperand(0);
16829 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16830 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16832 // Extract the RHS vectors
16833 SDValue RHS = Op.getOperand(1);
16834 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16835 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16837 MVT EltVT = VT.getVectorElementType();
16838 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16840 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16841 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16842 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16845 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16846 if (Op.getValueType() == MVT::i1)
16847 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16848 Op.getOperand(0), Op.getOperand(1));
16849 assert(Op.getSimpleValueType().is256BitVector() &&
16850 Op.getSimpleValueType().isInteger() &&
16851 "Only handle AVX 256-bit vector integer operation");
16852 return Lower256IntArith(Op, DAG);
16855 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16856 if (Op.getValueType() == MVT::i1)
16857 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16858 Op.getOperand(0), Op.getOperand(1));
16859 assert(Op.getSimpleValueType().is256BitVector() &&
16860 Op.getSimpleValueType().isInteger() &&
16861 "Only handle AVX 256-bit vector integer operation");
16862 return Lower256IntArith(Op, DAG);
16865 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16866 SelectionDAG &DAG) {
16868 MVT VT = Op.getSimpleValueType();
16871 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16873 // Decompose 256-bit ops into smaller 128-bit ops.
16874 if (VT.is256BitVector() && !Subtarget->hasInt256())
16875 return Lower256IntArith(Op, DAG);
16877 SDValue A = Op.getOperand(0);
16878 SDValue B = Op.getOperand(1);
16880 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16881 // pairs, multiply and truncate.
16882 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16883 if (Subtarget->hasInt256()) {
16884 if (VT == MVT::v32i8) {
16885 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16886 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16887 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16888 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16889 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16890 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16891 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16892 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16893 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16894 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16897 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16898 return DAG.getNode(
16899 ISD::TRUNCATE, dl, VT,
16900 DAG.getNode(ISD::MUL, dl, ExVT,
16901 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16902 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16905 assert(VT == MVT::v16i8 &&
16906 "Pre-AVX2 support only supports v16i8 multiplication");
16907 MVT ExVT = MVT::v8i16;
16909 // Extract the lo parts and sign extend to i16
16911 if (Subtarget->hasSSE41()) {
16912 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16913 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16915 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16916 -1, 4, -1, 5, -1, 6, -1, 7};
16917 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16918 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16919 ALo = DAG.getBitcast(ExVT, ALo);
16920 BLo = DAG.getBitcast(ExVT, BLo);
16921 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16922 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16925 // Extract the hi parts and sign extend to i16
16927 if (Subtarget->hasSSE41()) {
16928 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16929 -1, -1, -1, -1, -1, -1, -1, -1};
16930 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16931 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16932 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16933 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16935 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16936 -1, 12, -1, 13, -1, 14, -1, 15};
16937 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16938 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16939 AHi = DAG.getBitcast(ExVT, AHi);
16940 BHi = DAG.getBitcast(ExVT, BHi);
16941 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16942 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16945 // Multiply, mask the lower 8bits of the lo/hi results and pack
16946 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16947 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16948 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16949 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16950 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16953 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16954 if (VT == MVT::v4i32) {
16955 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16956 "Should not custom lower when pmuldq is available!");
16958 // Extract the odd parts.
16959 static const int UnpackMask[] = { 1, -1, 3, -1 };
16960 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16961 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16963 // Multiply the even parts.
16964 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16965 // Now multiply odd parts.
16966 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16968 Evens = DAG.getBitcast(VT, Evens);
16969 Odds = DAG.getBitcast(VT, Odds);
16971 // Merge the two vectors back together with a shuffle. This expands into 2
16973 static const int ShufMask[] = { 0, 4, 2, 6 };
16974 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16977 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16978 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16980 // Ahi = psrlqi(a, 32);
16981 // Bhi = psrlqi(b, 32);
16983 // AloBlo = pmuludq(a, b);
16984 // AloBhi = pmuludq(a, Bhi);
16985 // AhiBlo = pmuludq(Ahi, b);
16987 // AloBhi = psllqi(AloBhi, 32);
16988 // AhiBlo = psllqi(AhiBlo, 32);
16989 // return AloBlo + AloBhi + AhiBlo;
16991 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16992 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16994 SDValue AhiBlo = Ahi;
16995 SDValue AloBhi = Bhi;
16996 // Bit cast to 32-bit vectors for MULUDQ
16997 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16998 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16999 A = DAG.getBitcast(MulVT, A);
17000 B = DAG.getBitcast(MulVT, B);
17001 Ahi = DAG.getBitcast(MulVT, Ahi);
17002 Bhi = DAG.getBitcast(MulVT, Bhi);
17004 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17005 // After shifting right const values the result may be all-zero.
17006 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17007 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17008 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17010 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17011 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17012 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17015 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17016 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17019 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17020 assert(Subtarget->isTargetWin64() && "Unexpected target");
17021 EVT VT = Op.getValueType();
17022 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17023 "Unexpected return type for lowering");
17027 switch (Op->getOpcode()) {
17028 default: llvm_unreachable("Unexpected request for libcall!");
17029 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17030 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17031 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17032 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17033 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17034 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17038 SDValue InChain = DAG.getEntryNode();
17040 TargetLowering::ArgListTy Args;
17041 TargetLowering::ArgListEntry Entry;
17042 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17043 EVT ArgVT = Op->getOperand(i).getValueType();
17044 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17045 "Unexpected argument type for lowering");
17046 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17047 Entry.Node = StackPtr;
17048 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17050 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17051 Entry.Ty = PointerType::get(ArgTy,0);
17052 Entry.isSExt = false;
17053 Entry.isZExt = false;
17054 Args.push_back(Entry);
17057 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17058 getPointerTy(DAG.getDataLayout()));
17060 TargetLowering::CallLoweringInfo CLI(DAG);
17061 CLI.setDebugLoc(dl).setChain(InChain)
17062 .setCallee(getLibcallCallingConv(LC),
17063 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17064 Callee, std::move(Args), 0)
17065 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17067 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17068 return DAG.getBitcast(VT, CallInfo.first);
17071 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17072 SelectionDAG &DAG) {
17073 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17074 EVT VT = Op0.getValueType();
17077 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17078 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17080 // PMULxD operations multiply each even value (starting at 0) of LHS with
17081 // the related value of RHS and produce a widen result.
17082 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17083 // => <2 x i64> <ae|cg>
17085 // In other word, to have all the results, we need to perform two PMULxD:
17086 // 1. one with the even values.
17087 // 2. one with the odd values.
17088 // To achieve #2, with need to place the odd values at an even position.
17090 // Place the odd value at an even position (basically, shift all values 1
17091 // step to the left):
17092 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17093 // <a|b|c|d> => <b|undef|d|undef>
17094 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17095 // <e|f|g|h> => <f|undef|h|undef>
17096 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17098 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17100 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17101 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17103 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17104 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17105 // => <2 x i64> <ae|cg>
17106 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17107 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17108 // => <2 x i64> <bf|dh>
17109 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17111 // Shuffle it back into the right order.
17112 SDValue Highs, Lows;
17113 if (VT == MVT::v8i32) {
17114 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17115 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17116 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17117 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17119 const int HighMask[] = {1, 5, 3, 7};
17120 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17121 const int LowMask[] = {0, 4, 2, 6};
17122 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17125 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17126 // unsigned multiply.
17127 if (IsSigned && !Subtarget->hasSSE41()) {
17128 SDValue ShAmt = DAG.getConstant(
17130 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17131 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17132 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17133 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17134 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17136 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17137 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17140 // The first result of MUL_LOHI is actually the low value, followed by the
17142 SDValue Ops[] = {Lows, Highs};
17143 return DAG.getMergeValues(Ops, dl);
17146 // Return true if the required (according to Opcode) shift-imm form is natively
17147 // supported by the Subtarget
17148 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17150 if (VT.getScalarSizeInBits() < 16)
17153 if (VT.is512BitVector() &&
17154 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17157 bool LShift = VT.is128BitVector() ||
17158 (VT.is256BitVector() && Subtarget->hasInt256());
17160 bool AShift = LShift && (Subtarget->hasVLX() ||
17161 (VT != MVT::v2i64 && VT != MVT::v4i64));
17162 return (Opcode == ISD::SRA) ? AShift : LShift;
17165 // The shift amount is a variable, but it is the same for all vector lanes.
17166 // These instructions are defined together with shift-immediate.
17168 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17170 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17173 // Return true if the required (according to Opcode) variable-shift form is
17174 // natively supported by the Subtarget
17175 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17178 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17181 // vXi16 supported only on AVX-512, BWI
17182 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17185 if (VT.is512BitVector() || Subtarget->hasVLX())
17188 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17189 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17190 return (Opcode == ISD::SRA) ? AShift : LShift;
17193 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17194 const X86Subtarget *Subtarget) {
17195 MVT VT = Op.getSimpleValueType();
17197 SDValue R = Op.getOperand(0);
17198 SDValue Amt = Op.getOperand(1);
17200 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17201 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17203 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17204 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17205 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17206 SDValue Ex = DAG.getBitcast(ExVT, R);
17208 if (ShiftAmt >= 32) {
17209 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17211 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17212 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17213 ShiftAmt - 32, DAG);
17214 if (VT == MVT::v2i64)
17215 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17216 if (VT == MVT::v4i64)
17217 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17218 {9, 1, 11, 3, 13, 5, 15, 7});
17220 // SRA upper i32, SHL whole i64 and select lower i32.
17221 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17224 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17225 Lower = DAG.getBitcast(ExVT, Lower);
17226 if (VT == MVT::v2i64)
17227 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17228 if (VT == MVT::v4i64)
17229 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17230 {8, 1, 10, 3, 12, 5, 14, 7});
17232 return DAG.getBitcast(VT, Ex);
17235 // Optimize shl/srl/sra with constant shift amount.
17236 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17237 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17238 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17240 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17241 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17243 // i64 SRA needs to be performed as partial shifts.
17244 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17245 Op.getOpcode() == ISD::SRA)
17246 return ArithmeticShiftRight64(ShiftAmt);
17248 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17249 unsigned NumElts = VT.getVectorNumElements();
17250 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17252 if (Op.getOpcode() == ISD::SHL) {
17253 // Simple i8 add case
17255 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17257 // Make a large shift.
17258 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17260 SHL = DAG.getBitcast(VT, SHL);
17261 // Zero out the rightmost bits.
17262 SmallVector<SDValue, 32> V(
17263 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17264 return DAG.getNode(ISD::AND, dl, VT, SHL,
17265 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17267 if (Op.getOpcode() == ISD::SRL) {
17268 // Make a large shift.
17269 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17271 SRL = DAG.getBitcast(VT, SRL);
17272 // Zero out the leftmost bits.
17273 SmallVector<SDValue, 32> V(
17274 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17275 return DAG.getNode(ISD::AND, dl, VT, SRL,
17276 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17278 if (Op.getOpcode() == ISD::SRA) {
17279 if (ShiftAmt == 7) {
17280 // R s>> 7 === R s< 0
17281 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17282 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17285 // R s>> a === ((R u>> a) ^ m) - m
17286 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17287 SmallVector<SDValue, 32> V(NumElts,
17288 DAG.getConstant(128 >> ShiftAmt, dl,
17290 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17291 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17292 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17295 llvm_unreachable("Unknown shift opcode.");
17300 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17301 if (!Subtarget->is64Bit() &&
17302 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17303 Amt.getOpcode() == ISD::BITCAST &&
17304 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17305 Amt = Amt.getOperand(0);
17306 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17307 VT.getVectorNumElements();
17308 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17309 uint64_t ShiftAmt = 0;
17310 for (unsigned i = 0; i != Ratio; ++i) {
17311 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17315 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17317 // Check remaining shift amounts.
17318 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17319 uint64_t ShAmt = 0;
17320 for (unsigned j = 0; j != Ratio; ++j) {
17321 ConstantSDNode *C =
17322 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17326 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17328 if (ShAmt != ShiftAmt)
17332 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17333 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17335 if (Op.getOpcode() == ISD::SRA)
17336 return ArithmeticShiftRight64(ShiftAmt);
17342 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17343 const X86Subtarget* Subtarget) {
17344 MVT VT = Op.getSimpleValueType();
17346 SDValue R = Op.getOperand(0);
17347 SDValue Amt = Op.getOperand(1);
17349 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17350 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17352 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17353 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17355 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17357 EVT EltVT = VT.getVectorElementType();
17359 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17360 // Check if this build_vector node is doing a splat.
17361 // If so, then set BaseShAmt equal to the splat value.
17362 BaseShAmt = BV->getSplatValue();
17363 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17364 BaseShAmt = SDValue();
17366 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17367 Amt = Amt.getOperand(0);
17369 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17370 if (SVN && SVN->isSplat()) {
17371 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17372 SDValue InVec = Amt.getOperand(0);
17373 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17374 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17375 "Unexpected shuffle index found!");
17376 BaseShAmt = InVec.getOperand(SplatIdx);
17377 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17378 if (ConstantSDNode *C =
17379 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17380 if (C->getZExtValue() == SplatIdx)
17381 BaseShAmt = InVec.getOperand(1);
17386 // Avoid introducing an extract element from a shuffle.
17387 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17388 DAG.getIntPtrConstant(SplatIdx, dl));
17392 if (BaseShAmt.getNode()) {
17393 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17394 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17395 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17396 else if (EltVT.bitsLT(MVT::i32))
17397 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17399 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17403 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17404 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17405 Amt.getOpcode() == ISD::BITCAST &&
17406 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17407 Amt = Amt.getOperand(0);
17408 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17409 VT.getVectorNumElements();
17410 std::vector<SDValue> Vals(Ratio);
17411 for (unsigned i = 0; i != Ratio; ++i)
17412 Vals[i] = Amt.getOperand(i);
17413 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17414 for (unsigned j = 0; j != Ratio; ++j)
17415 if (Vals[j] != Amt.getOperand(i + j))
17419 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17420 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17425 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17426 SelectionDAG &DAG) {
17427 MVT VT = Op.getSimpleValueType();
17429 SDValue R = Op.getOperand(0);
17430 SDValue Amt = Op.getOperand(1);
17432 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17433 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17435 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17438 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17441 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17444 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17445 // shifts per-lane and then shuffle the partial results back together.
17446 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17447 // Splat the shift amounts so the scalar shifts above will catch it.
17448 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17449 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17450 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17451 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17452 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17455 // If possible, lower this packed shift into a vector multiply instead of
17456 // expanding it into a sequence of scalar shifts.
17457 // Do this only if the vector shift count is a constant build_vector.
17458 if (Op.getOpcode() == ISD::SHL &&
17459 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17460 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17461 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17462 SmallVector<SDValue, 8> Elts;
17463 EVT SVT = VT.getScalarType();
17464 unsigned SVTBits = SVT.getSizeInBits();
17465 const APInt &One = APInt(SVTBits, 1);
17466 unsigned NumElems = VT.getVectorNumElements();
17468 for (unsigned i=0; i !=NumElems; ++i) {
17469 SDValue Op = Amt->getOperand(i);
17470 if (Op->getOpcode() == ISD::UNDEF) {
17471 Elts.push_back(Op);
17475 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17476 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17477 uint64_t ShAmt = C.getZExtValue();
17478 if (ShAmt >= SVTBits) {
17479 Elts.push_back(DAG.getUNDEF(SVT));
17482 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17484 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17485 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17488 // Lower SHL with variable shift amount.
17489 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17490 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17492 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17493 DAG.getConstant(0x3f800000U, dl, VT));
17494 Op = DAG.getBitcast(MVT::v4f32, Op);
17495 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17496 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17499 // If possible, lower this shift as a sequence of two shifts by
17500 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17502 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17504 // Could be rewritten as:
17505 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17507 // The advantage is that the two shifts from the example would be
17508 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17509 // the vector shift into four scalar shifts plus four pairs of vector
17511 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17512 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17513 unsigned TargetOpcode = X86ISD::MOVSS;
17514 bool CanBeSimplified;
17515 // The splat value for the first packed shift (the 'X' from the example).
17516 SDValue Amt1 = Amt->getOperand(0);
17517 // The splat value for the second packed shift (the 'Y' from the example).
17518 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17519 Amt->getOperand(2);
17521 // See if it is possible to replace this node with a sequence of
17522 // two shifts followed by a MOVSS/MOVSD
17523 if (VT == MVT::v4i32) {
17524 // Check if it is legal to use a MOVSS.
17525 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17526 Amt2 == Amt->getOperand(3);
17527 if (!CanBeSimplified) {
17528 // Otherwise, check if we can still simplify this node using a MOVSD.
17529 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17530 Amt->getOperand(2) == Amt->getOperand(3);
17531 TargetOpcode = X86ISD::MOVSD;
17532 Amt2 = Amt->getOperand(2);
17535 // Do similar checks for the case where the machine value type
17537 CanBeSimplified = Amt1 == Amt->getOperand(1);
17538 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17539 CanBeSimplified = Amt2 == Amt->getOperand(i);
17541 if (!CanBeSimplified) {
17542 TargetOpcode = X86ISD::MOVSD;
17543 CanBeSimplified = true;
17544 Amt2 = Amt->getOperand(4);
17545 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17546 CanBeSimplified = Amt1 == Amt->getOperand(i);
17547 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17548 CanBeSimplified = Amt2 == Amt->getOperand(j);
17552 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17553 isa<ConstantSDNode>(Amt2)) {
17554 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17555 EVT CastVT = MVT::v4i32;
17557 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17558 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17560 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17561 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17562 if (TargetOpcode == X86ISD::MOVSD)
17563 CastVT = MVT::v2i64;
17564 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17565 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17566 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17568 return DAG.getBitcast(VT, Result);
17572 // v4i32 Non Uniform Shifts.
17573 // If the shift amount is constant we can shift each lane using the SSE2
17574 // immediate shifts, else we need to zero-extend each lane to the lower i64
17575 // and shift using the SSE2 variable shifts.
17576 // The separate results can then be blended together.
17577 if (VT == MVT::v4i32) {
17578 unsigned Opc = Op.getOpcode();
17579 SDValue Amt0, Amt1, Amt2, Amt3;
17580 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17581 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17582 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17583 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17584 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17586 // ISD::SHL is handled above but we include it here for completeness.
17589 llvm_unreachable("Unknown target vector shift node");
17591 Opc = X86ISD::VSHL;
17594 Opc = X86ISD::VSRL;
17597 Opc = X86ISD::VSRA;
17600 // The SSE2 shifts use the lower i64 as the same shift amount for
17601 // all lanes and the upper i64 is ignored. These shuffle masks
17602 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17603 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17604 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17605 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17606 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17607 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17610 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17611 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17612 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17613 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17614 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17615 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17616 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17619 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17620 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17621 unsigned ShiftOpcode = Op->getOpcode();
17623 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17624 // On SSE41 targets we make use of the fact that VSELECT lowers
17625 // to PBLENDVB which selects bytes based just on the sign bit.
17626 if (Subtarget->hasSSE41()) {
17627 V0 = DAG.getBitcast(VT, V0);
17628 V1 = DAG.getBitcast(VT, V1);
17629 Sel = DAG.getBitcast(VT, Sel);
17630 return DAG.getBitcast(SelVT,
17631 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17633 // On pre-SSE41 targets we test for the sign bit by comparing to
17634 // zero - a negative value will set all bits of the lanes to true
17635 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17636 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17637 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17638 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17641 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17642 // We can safely do this using i16 shifts as we're only interested in
17643 // the 3 lower bits of each byte.
17644 Amt = DAG.getBitcast(ExtVT, Amt);
17645 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17646 Amt = DAG.getBitcast(VT, Amt);
17648 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17649 // r = VSELECT(r, shift(r, 4), a);
17651 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17652 R = SignBitSelect(VT, Amt, M, R);
17655 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17657 // r = VSELECT(r, shift(r, 2), a);
17658 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17659 R = SignBitSelect(VT, Amt, M, R);
17662 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17664 // return VSELECT(r, shift(r, 1), a);
17665 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17666 R = SignBitSelect(VT, Amt, M, R);
17670 if (Op->getOpcode() == ISD::SRA) {
17671 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17672 // so we can correctly sign extend. We don't care what happens to the
17674 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17675 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17676 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17677 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17678 ALo = DAG.getBitcast(ExtVT, ALo);
17679 AHi = DAG.getBitcast(ExtVT, AHi);
17680 RLo = DAG.getBitcast(ExtVT, RLo);
17681 RHi = DAG.getBitcast(ExtVT, RHi);
17683 // r = VSELECT(r, shift(r, 4), a);
17684 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17685 DAG.getConstant(4, dl, ExtVT));
17686 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17687 DAG.getConstant(4, dl, ExtVT));
17688 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17689 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17692 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17693 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17695 // r = VSELECT(r, shift(r, 2), a);
17696 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17697 DAG.getConstant(2, dl, ExtVT));
17698 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17699 DAG.getConstant(2, dl, ExtVT));
17700 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17701 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17704 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17705 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17707 // r = VSELECT(r, shift(r, 1), a);
17708 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17709 DAG.getConstant(1, dl, ExtVT));
17710 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17711 DAG.getConstant(1, dl, ExtVT));
17712 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17713 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17715 // Logical shift the result back to the lower byte, leaving a zero upper
17717 // meaning that we can safely pack with PACKUSWB.
17719 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17721 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17722 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17726 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17727 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17728 // solution better.
17729 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17730 MVT ExtVT = MVT::v8i32;
17732 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17733 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17734 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17735 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17736 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17739 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17740 MVT ExtVT = MVT::v8i32;
17741 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17742 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17743 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17744 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17745 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17746 ALo = DAG.getBitcast(ExtVT, ALo);
17747 AHi = DAG.getBitcast(ExtVT, AHi);
17748 RLo = DAG.getBitcast(ExtVT, RLo);
17749 RHi = DAG.getBitcast(ExtVT, RHi);
17750 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17751 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17752 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17753 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17754 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17757 if (VT == MVT::v8i16) {
17758 unsigned ShiftOpcode = Op->getOpcode();
17760 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17761 // On SSE41 targets we make use of the fact that VSELECT lowers
17762 // to PBLENDVB which selects bytes based just on the sign bit.
17763 if (Subtarget->hasSSE41()) {
17764 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17765 V0 = DAG.getBitcast(ExtVT, V0);
17766 V1 = DAG.getBitcast(ExtVT, V1);
17767 Sel = DAG.getBitcast(ExtVT, Sel);
17768 return DAG.getBitcast(
17769 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17771 // On pre-SSE41 targets we splat the sign bit - a negative value will
17772 // set all bits of the lanes to true and VSELECT uses that in
17773 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17775 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17776 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17779 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17780 if (Subtarget->hasSSE41()) {
17781 // On SSE41 targets we need to replicate the shift mask in both
17782 // bytes for PBLENDVB.
17785 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17786 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17788 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17791 // r = VSELECT(r, shift(r, 8), a);
17792 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17793 R = SignBitSelect(Amt, M, R);
17796 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17798 // r = VSELECT(r, shift(r, 4), a);
17799 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17800 R = SignBitSelect(Amt, M, R);
17803 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17805 // r = VSELECT(r, shift(r, 2), a);
17806 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17807 R = SignBitSelect(Amt, M, R);
17810 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17812 // return VSELECT(r, shift(r, 1), a);
17813 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17814 R = SignBitSelect(Amt, M, R);
17818 // Decompose 256-bit shifts into smaller 128-bit shifts.
17819 if (VT.is256BitVector()) {
17820 unsigned NumElems = VT.getVectorNumElements();
17821 MVT EltVT = VT.getVectorElementType();
17822 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17824 // Extract the two vectors
17825 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17826 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17828 // Recreate the shift amount vectors
17829 SDValue Amt1, Amt2;
17830 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17831 // Constant shift amount
17832 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17833 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17834 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17836 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17837 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17839 // Variable shift amount
17840 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17841 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17844 // Issue new vector shifts for the smaller types
17845 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17846 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17848 // Concatenate the result back
17849 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17855 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17856 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17857 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17858 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17859 // has only one use.
17860 SDNode *N = Op.getNode();
17861 SDValue LHS = N->getOperand(0);
17862 SDValue RHS = N->getOperand(1);
17863 unsigned BaseOp = 0;
17866 switch (Op.getOpcode()) {
17867 default: llvm_unreachable("Unknown ovf instruction!");
17869 // A subtract of one will be selected as a INC. Note that INC doesn't
17870 // set CF, so we can't do this for UADDO.
17871 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17873 BaseOp = X86ISD::INC;
17874 Cond = X86::COND_O;
17877 BaseOp = X86ISD::ADD;
17878 Cond = X86::COND_O;
17881 BaseOp = X86ISD::ADD;
17882 Cond = X86::COND_B;
17885 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17886 // set CF, so we can't do this for USUBO.
17887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17889 BaseOp = X86ISD::DEC;
17890 Cond = X86::COND_O;
17893 BaseOp = X86ISD::SUB;
17894 Cond = X86::COND_O;
17897 BaseOp = X86ISD::SUB;
17898 Cond = X86::COND_B;
17901 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17902 Cond = X86::COND_O;
17904 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17905 if (N->getValueType(0) == MVT::i8) {
17906 BaseOp = X86ISD::UMUL8;
17907 Cond = X86::COND_O;
17910 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17912 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17915 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17916 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17917 SDValue(Sum.getNode(), 2));
17919 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17923 // Also sets EFLAGS.
17924 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17925 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17928 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17929 DAG.getConstant(Cond, DL, MVT::i32),
17930 SDValue(Sum.getNode(), 1));
17932 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17935 /// Returns true if the operand type is exactly twice the native width, and
17936 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17937 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17938 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17939 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17940 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17943 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17944 else if (OpWidth == 128)
17945 return Subtarget->hasCmpxchg16b();
17950 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17951 return needsCmpXchgNb(SI->getValueOperand()->getType());
17954 // Note: this turns large loads into lock cmpxchg8b/16b.
17955 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17956 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17957 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17958 return needsCmpXchgNb(PTy->getElementType());
17961 TargetLoweringBase::AtomicRMWExpansionKind
17962 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17963 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17964 const Type *MemType = AI->getType();
17966 // If the operand is too big, we must see if cmpxchg8/16b is available
17967 // and default to library calls otherwise.
17968 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17969 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17970 : AtomicRMWExpansionKind::None;
17973 AtomicRMWInst::BinOp Op = AI->getOperation();
17976 llvm_unreachable("Unknown atomic operation");
17977 case AtomicRMWInst::Xchg:
17978 case AtomicRMWInst::Add:
17979 case AtomicRMWInst::Sub:
17980 // It's better to use xadd, xsub or xchg for these in all cases.
17981 return AtomicRMWExpansionKind::None;
17982 case AtomicRMWInst::Or:
17983 case AtomicRMWInst::And:
17984 case AtomicRMWInst::Xor:
17985 // If the atomicrmw's result isn't actually used, we can just add a "lock"
17986 // prefix to a normal instruction for these operations.
17987 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17988 : AtomicRMWExpansionKind::None;
17989 case AtomicRMWInst::Nand:
17990 case AtomicRMWInst::Max:
17991 case AtomicRMWInst::Min:
17992 case AtomicRMWInst::UMax:
17993 case AtomicRMWInst::UMin:
17994 // These always require a non-trivial set of data operations on x86. We must
17995 // use a cmpxchg loop.
17996 return AtomicRMWExpansionKind::CmpXChg;
18000 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18001 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18002 // no-sse2). There isn't any reason to disable it if the target processor
18004 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18008 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18009 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18010 const Type *MemType = AI->getType();
18011 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18012 // there is no benefit in turning such RMWs into loads, and it is actually
18013 // harmful as it introduces a mfence.
18014 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18017 auto Builder = IRBuilder<>(AI);
18018 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18019 auto SynchScope = AI->getSynchScope();
18020 // We must restrict the ordering to avoid generating loads with Release or
18021 // ReleaseAcquire orderings.
18022 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18023 auto Ptr = AI->getPointerOperand();
18025 // Before the load we need a fence. Here is an example lifted from
18026 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18029 // x.store(1, relaxed);
18030 // r1 = y.fetch_add(0, release);
18032 // y.fetch_add(42, acquire);
18033 // r2 = x.load(relaxed);
18034 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18035 // lowered to just a load without a fence. A mfence flushes the store buffer,
18036 // making the optimization clearly correct.
18037 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18038 // otherwise, we might be able to be more agressive on relaxed idempotent
18039 // rmw. In practice, they do not look useful, so we don't try to be
18040 // especially clever.
18041 if (SynchScope == SingleThread)
18042 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18043 // the IR level, so we must wrap it in an intrinsic.
18046 if (!hasMFENCE(*Subtarget))
18047 // FIXME: it might make sense to use a locked operation here but on a
18048 // different cache-line to prevent cache-line bouncing. In practice it
18049 // is probably a small win, and x86 processors without mfence are rare
18050 // enough that we do not bother.
18054 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18055 Builder.CreateCall(MFence, {});
18057 // Finally we can emit the atomic load.
18058 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18059 AI->getType()->getPrimitiveSizeInBits());
18060 Loaded->setAtomic(Order, SynchScope);
18061 AI->replaceAllUsesWith(Loaded);
18062 AI->eraseFromParent();
18066 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18067 SelectionDAG &DAG) {
18069 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18070 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18071 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18072 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18074 // The only fence that needs an instruction is a sequentially-consistent
18075 // cross-thread fence.
18076 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18077 if (hasMFENCE(*Subtarget))
18078 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18080 SDValue Chain = Op.getOperand(0);
18081 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18083 DAG.getRegister(X86::ESP, MVT::i32), // Base
18084 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18085 DAG.getRegister(0, MVT::i32), // Index
18086 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18087 DAG.getRegister(0, MVT::i32), // Segment.
18091 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18092 return SDValue(Res, 0);
18095 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18096 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18099 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18100 SelectionDAG &DAG) {
18101 MVT T = Op.getSimpleValueType();
18105 switch(T.SimpleTy) {
18106 default: llvm_unreachable("Invalid value type!");
18107 case MVT::i8: Reg = X86::AL; size = 1; break;
18108 case MVT::i16: Reg = X86::AX; size = 2; break;
18109 case MVT::i32: Reg = X86::EAX; size = 4; break;
18111 assert(Subtarget->is64Bit() && "Node not type legal!");
18112 Reg = X86::RAX; size = 8;
18115 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18116 Op.getOperand(2), SDValue());
18117 SDValue Ops[] = { cpIn.getValue(0),
18120 DAG.getTargetConstant(size, DL, MVT::i8),
18121 cpIn.getValue(1) };
18122 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18123 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18124 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18128 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18129 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18130 MVT::i32, cpOut.getValue(2));
18131 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18132 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18135 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18136 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18137 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18141 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18142 SelectionDAG &DAG) {
18143 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18144 MVT DstVT = Op.getSimpleValueType();
18146 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18147 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18148 if (DstVT != MVT::f64)
18149 // This conversion needs to be expanded.
18152 SDValue InVec = Op->getOperand(0);
18154 unsigned NumElts = SrcVT.getVectorNumElements();
18155 EVT SVT = SrcVT.getVectorElementType();
18157 // Widen the vector in input in the case of MVT::v2i32.
18158 // Example: from MVT::v2i32 to MVT::v4i32.
18159 SmallVector<SDValue, 16> Elts;
18160 for (unsigned i = 0, e = NumElts; i != e; ++i)
18161 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18162 DAG.getIntPtrConstant(i, dl)));
18164 // Explicitly mark the extra elements as Undef.
18165 Elts.append(NumElts, DAG.getUNDEF(SVT));
18167 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18168 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18169 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18170 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18171 DAG.getIntPtrConstant(0, dl));
18174 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18175 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18176 assert((DstVT == MVT::i64 ||
18177 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18178 "Unexpected custom BITCAST");
18179 // i64 <=> MMX conversions are Legal.
18180 if (SrcVT==MVT::i64 && DstVT.isVector())
18182 if (DstVT==MVT::i64 && SrcVT.isVector())
18184 // MMX <=> MMX conversions are Legal.
18185 if (SrcVT.isVector() && DstVT.isVector())
18187 // All other conversions need to be expanded.
18191 /// Compute the horizontal sum of bytes in V for the elements of VT.
18193 /// Requires V to be a byte vector and VT to be an integer vector type with
18194 /// wider elements than V's type. The width of the elements of VT determines
18195 /// how many bytes of V are summed horizontally to produce each element of the
18197 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18198 const X86Subtarget *Subtarget,
18199 SelectionDAG &DAG) {
18201 MVT ByteVecVT = V.getSimpleValueType();
18202 MVT EltVT = VT.getVectorElementType();
18203 int NumElts = VT.getVectorNumElements();
18204 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18205 "Expected value to have byte element type.");
18206 assert(EltVT != MVT::i8 &&
18207 "Horizontal byte sum only makes sense for wider elements!");
18208 unsigned VecSize = VT.getSizeInBits();
18209 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18211 // PSADBW instruction horizontally add all bytes and leave the result in i64
18212 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18213 if (EltVT == MVT::i64) {
18214 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18215 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18216 return DAG.getBitcast(VT, V);
18219 if (EltVT == MVT::i32) {
18220 // We unpack the low half and high half into i32s interleaved with zeros so
18221 // that we can use PSADBW to horizontally sum them. The most useful part of
18222 // this is that it lines up the results of two PSADBW instructions to be
18223 // two v2i64 vectors which concatenated are the 4 population counts. We can
18224 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18225 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18226 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18227 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18229 // Do the horizontal sums into two v2i64s.
18230 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18231 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18232 DAG.getBitcast(ByteVecVT, Low), Zeros);
18233 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18234 DAG.getBitcast(ByteVecVT, High), Zeros);
18236 // Merge them together.
18237 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18238 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18239 DAG.getBitcast(ShortVecVT, Low),
18240 DAG.getBitcast(ShortVecVT, High));
18242 return DAG.getBitcast(VT, V);
18245 // The only element type left is i16.
18246 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18248 // To obtain pop count for each i16 element starting from the pop count for
18249 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18250 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18251 // directly supported.
18252 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18253 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18254 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18255 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18256 DAG.getBitcast(ByteVecVT, V));
18257 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18260 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18261 const X86Subtarget *Subtarget,
18262 SelectionDAG &DAG) {
18263 MVT VT = Op.getSimpleValueType();
18264 MVT EltVT = VT.getVectorElementType();
18265 unsigned VecSize = VT.getSizeInBits();
18267 // Implement a lookup table in register by using an algorithm based on:
18268 // http://wm.ite.pl/articles/sse-popcount.html
18270 // The general idea is that every lower byte nibble in the input vector is an
18271 // index into a in-register pre-computed pop count table. We then split up the
18272 // input vector in two new ones: (1) a vector with only the shifted-right
18273 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18274 // masked out higher ones) for each byte. PSHUB is used separately with both
18275 // to index the in-register table. Next, both are added and the result is a
18276 // i8 vector where each element contains the pop count for input byte.
18278 // To obtain the pop count for elements != i8, we follow up with the same
18279 // approach and use additional tricks as described below.
18281 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18282 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18283 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18284 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18286 int NumByteElts = VecSize / 8;
18287 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18288 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18289 SmallVector<SDValue, 16> LUTVec;
18290 for (int i = 0; i < NumByteElts; ++i)
18291 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18292 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18293 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18294 DAG.getConstant(0x0F, DL, MVT::i8));
18295 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18298 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18299 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18300 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18303 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18305 // The input vector is used as the shuffle mask that index elements into the
18306 // LUT. After counting low and high nibbles, add the vector to obtain the
18307 // final pop count per i8 element.
18308 SDValue HighPopCnt =
18309 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18310 SDValue LowPopCnt =
18311 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18312 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18314 if (EltVT == MVT::i8)
18317 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18320 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18321 const X86Subtarget *Subtarget,
18322 SelectionDAG &DAG) {
18323 MVT VT = Op.getSimpleValueType();
18324 assert(VT.is128BitVector() &&
18325 "Only 128-bit vector bitmath lowering supported.");
18327 int VecSize = VT.getSizeInBits();
18328 MVT EltVT = VT.getVectorElementType();
18329 int Len = EltVT.getSizeInBits();
18331 // This is the vectorized version of the "best" algorithm from
18332 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18333 // with a minor tweak to use a series of adds + shifts instead of vector
18334 // multiplications. Implemented for all integer vector types. We only use
18335 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18336 // much faster, even faster than using native popcnt instructions.
18338 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18339 MVT VT = V.getSimpleValueType();
18340 SmallVector<SDValue, 32> Shifters(
18341 VT.getVectorNumElements(),
18342 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18343 return DAG.getNode(OpCode, DL, VT, V,
18344 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18346 auto GetMask = [&](SDValue V, APInt Mask) {
18347 MVT VT = V.getSimpleValueType();
18348 SmallVector<SDValue, 32> Masks(
18349 VT.getVectorNumElements(),
18350 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18351 return DAG.getNode(ISD::AND, DL, VT, V,
18352 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18355 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18356 // x86, so set the SRL type to have elements at least i16 wide. This is
18357 // correct because all of our SRLs are followed immediately by a mask anyways
18358 // that handles any bits that sneak into the high bits of the byte elements.
18359 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18363 // v = v - ((v >> 1) & 0x55555555...)
18365 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18366 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18367 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18369 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18370 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18371 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18372 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18373 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18375 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18376 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18377 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18378 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18380 // At this point, V contains the byte-wise population count, and we are
18381 // merely doing a horizontal sum if necessary to get the wider element
18383 if (EltVT == MVT::i8)
18386 return LowerHorizontalByteSum(
18387 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18391 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18392 SelectionDAG &DAG) {
18393 MVT VT = Op.getSimpleValueType();
18394 // FIXME: Need to add AVX-512 support here!
18395 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18396 "Unknown CTPOP type to handle");
18397 SDLoc DL(Op.getNode());
18398 SDValue Op0 = Op.getOperand(0);
18400 if (!Subtarget->hasSSSE3()) {
18401 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18402 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18403 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18406 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18407 unsigned NumElems = VT.getVectorNumElements();
18409 // Extract each 128-bit vector, compute pop count and concat the result.
18410 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18411 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18413 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18414 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18415 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18418 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18421 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18422 SelectionDAG &DAG) {
18423 assert(Op.getValueType().isVector() &&
18424 "We only do custom lowering for vector population count.");
18425 return LowerVectorCTPOP(Op, Subtarget, DAG);
18428 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18429 SDNode *Node = Op.getNode();
18431 EVT T = Node->getValueType(0);
18432 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18433 DAG.getConstant(0, dl, T), Node->getOperand(2));
18434 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18435 cast<AtomicSDNode>(Node)->getMemoryVT(),
18436 Node->getOperand(0),
18437 Node->getOperand(1), negOp,
18438 cast<AtomicSDNode>(Node)->getMemOperand(),
18439 cast<AtomicSDNode>(Node)->getOrdering(),
18440 cast<AtomicSDNode>(Node)->getSynchScope());
18443 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18444 SDNode *Node = Op.getNode();
18446 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18448 // Convert seq_cst store -> xchg
18449 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18450 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18451 // (The only way to get a 16-byte store is cmpxchg16b)
18452 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18453 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18454 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18455 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18456 cast<AtomicSDNode>(Node)->getMemoryVT(),
18457 Node->getOperand(0),
18458 Node->getOperand(1), Node->getOperand(2),
18459 cast<AtomicSDNode>(Node)->getMemOperand(),
18460 cast<AtomicSDNode>(Node)->getOrdering(),
18461 cast<AtomicSDNode>(Node)->getSynchScope());
18462 return Swap.getValue(1);
18464 // Other atomic stores have a simple pattern.
18468 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18469 EVT VT = Op.getNode()->getSimpleValueType(0);
18471 // Let legalize expand this if it isn't a legal type yet.
18472 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18475 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18478 bool ExtraOp = false;
18479 switch (Op.getOpcode()) {
18480 default: llvm_unreachable("Invalid code");
18481 case ISD::ADDC: Opc = X86ISD::ADD; break;
18482 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18483 case ISD::SUBC: Opc = X86ISD::SUB; break;
18484 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18488 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18490 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18491 Op.getOperand(1), Op.getOperand(2));
18494 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18495 SelectionDAG &DAG) {
18496 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18498 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18499 // which returns the values as { float, float } (in XMM0) or
18500 // { double, double } (which is returned in XMM0, XMM1).
18502 SDValue Arg = Op.getOperand(0);
18503 EVT ArgVT = Arg.getValueType();
18504 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18506 TargetLowering::ArgListTy Args;
18507 TargetLowering::ArgListEntry Entry;
18511 Entry.isSExt = false;
18512 Entry.isZExt = false;
18513 Args.push_back(Entry);
18515 bool isF64 = ArgVT == MVT::f64;
18516 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18517 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18518 // the results are returned via SRet in memory.
18519 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18520 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18522 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18524 Type *RetTy = isF64
18525 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18526 : (Type*)VectorType::get(ArgTy, 4);
18528 TargetLowering::CallLoweringInfo CLI(DAG);
18529 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18530 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18532 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18535 // Returned in xmm0 and xmm1.
18536 return CallResult.first;
18538 // Returned in bits 0:31 and 32:64 xmm0.
18539 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18540 CallResult.first, DAG.getIntPtrConstant(0, dl));
18541 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18542 CallResult.first, DAG.getIntPtrConstant(1, dl));
18543 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18544 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18547 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18548 SelectionDAG &DAG) {
18549 assert(Subtarget->hasAVX512() &&
18550 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18552 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18553 EVT VT = N->getValue().getValueType();
18554 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18557 // X86 scatter kills mask register, so its type should be added to
18558 // the list of return values
18559 if (N->getNumValues() == 1) {
18560 SDValue Index = N->getIndex();
18561 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18562 !Index.getValueType().is512BitVector())
18563 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18565 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18566 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18567 N->getOperand(3), Index };
18569 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18570 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18571 return SDValue(NewScatter.getNode(), 0);
18576 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18577 SelectionDAG &DAG) {
18578 assert(Subtarget->hasAVX512() &&
18579 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18581 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18582 EVT VT = Op.getValueType();
18583 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18586 SDValue Index = N->getIndex();
18587 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18588 !Index.getValueType().is512BitVector()) {
18589 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18590 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18591 N->getOperand(3), Index };
18592 DAG.UpdateNodeOperands(N, Ops);
18597 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18598 SelectionDAG &DAG) const {
18599 // TODO: Eventually, the lowering of these nodes should be informed by or
18600 // deferred to the GC strategy for the function in which they appear. For
18601 // now, however, they must be lowered to something. Since they are logically
18602 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18603 // require special handling for these nodes), lower them as literal NOOPs for
18605 SmallVector<SDValue, 2> Ops;
18607 Ops.push_back(Op.getOperand(0));
18608 if (Op->getGluedNode())
18609 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18612 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18613 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18618 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18619 SelectionDAG &DAG) const {
18620 // TODO: Eventually, the lowering of these nodes should be informed by or
18621 // deferred to the GC strategy for the function in which they appear. For
18622 // now, however, they must be lowered to something. Since they are logically
18623 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18624 // require special handling for these nodes), lower them as literal NOOPs for
18626 SmallVector<SDValue, 2> Ops;
18628 Ops.push_back(Op.getOperand(0));
18629 if (Op->getGluedNode())
18630 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18633 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18634 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18639 /// LowerOperation - Provide custom lowering hooks for some operations.
18641 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18642 switch (Op.getOpcode()) {
18643 default: llvm_unreachable("Should not custom lower this!");
18644 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18645 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18646 return LowerCMP_SWAP(Op, Subtarget, DAG);
18647 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18648 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18649 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18650 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18651 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18652 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18653 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18654 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18655 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18656 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18657 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18658 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18659 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18660 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18661 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18662 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18663 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18664 case ISD::SHL_PARTS:
18665 case ISD::SRA_PARTS:
18666 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18667 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18668 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18669 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18670 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18671 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18672 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18673 case ISD::SIGN_EXTEND_VECTOR_INREG:
18674 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18675 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18676 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18677 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18678 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18680 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18681 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18682 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18683 case ISD::SETCC: return LowerSETCC(Op, DAG);
18684 case ISD::SELECT: return LowerSELECT(Op, DAG);
18685 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18686 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18687 case ISD::VASTART: return LowerVASTART(Op, DAG);
18688 case ISD::VAARG: return LowerVAARG(Op, DAG);
18689 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18690 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18691 case ISD::INTRINSIC_VOID:
18692 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18693 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18694 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18695 case ISD::FRAME_TO_ARGS_OFFSET:
18696 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18697 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18698 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18699 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18700 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18701 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18702 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18703 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18704 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18705 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18706 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18707 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18708 case ISD::UMUL_LOHI:
18709 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18712 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18718 case ISD::UMULO: return LowerXALUO(Op, DAG);
18719 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18720 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18724 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18725 case ISD::ADD: return LowerADD(Op, DAG);
18726 case ISD::SUB: return LowerSUB(Op, DAG);
18727 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18728 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18729 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18730 case ISD::GC_TRANSITION_START:
18731 return LowerGC_TRANSITION_START(Op, DAG);
18732 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18736 /// ReplaceNodeResults - Replace a node with an illegal result type
18737 /// with a new node built out of custom code.
18738 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18739 SmallVectorImpl<SDValue>&Results,
18740 SelectionDAG &DAG) const {
18742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18743 switch (N->getOpcode()) {
18745 llvm_unreachable("Do not know how to custom type legalize this operation!");
18746 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18747 case X86ISD::FMINC:
18749 case X86ISD::FMAXC:
18750 case X86ISD::FMAX: {
18751 EVT VT = N->getValueType(0);
18752 if (VT != MVT::v2f32)
18753 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18754 SDValue UNDEF = DAG.getUNDEF(VT);
18755 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18756 N->getOperand(0), UNDEF);
18757 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18758 N->getOperand(1), UNDEF);
18759 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18762 case ISD::SIGN_EXTEND_INREG:
18767 // We don't want to expand or promote these.
18774 case ISD::UDIVREM: {
18775 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18776 Results.push_back(V);
18779 case ISD::FP_TO_SINT:
18780 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18781 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18782 if (N->getOperand(0).getValueType() == MVT::f16)
18785 case ISD::FP_TO_UINT: {
18786 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18788 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18791 std::pair<SDValue,SDValue> Vals =
18792 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18793 SDValue FIST = Vals.first, StackSlot = Vals.second;
18794 if (FIST.getNode()) {
18795 EVT VT = N->getValueType(0);
18796 // Return a load from the stack slot.
18797 if (StackSlot.getNode())
18798 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18799 MachinePointerInfo(),
18800 false, false, false, 0));
18802 Results.push_back(FIST);
18806 case ISD::UINT_TO_FP: {
18807 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18808 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18809 N->getValueType(0) != MVT::v2f32)
18811 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18813 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18815 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18816 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18817 DAG.getBitcast(MVT::v2i64, VBias));
18818 Or = DAG.getBitcast(MVT::v2f64, Or);
18819 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18820 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18823 case ISD::FP_ROUND: {
18824 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18826 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18827 Results.push_back(V);
18830 case ISD::FP_EXTEND: {
18831 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18832 // No other ValueType for FP_EXTEND should reach this point.
18833 assert(N->getValueType(0) == MVT::v2f32 &&
18834 "Do not know how to legalize this Node");
18837 case ISD::INTRINSIC_W_CHAIN: {
18838 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18840 default : llvm_unreachable("Do not know how to custom type "
18841 "legalize this intrinsic operation!");
18842 case Intrinsic::x86_rdtsc:
18843 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18845 case Intrinsic::x86_rdtscp:
18846 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18848 case Intrinsic::x86_rdpmc:
18849 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18852 case ISD::READCYCLECOUNTER: {
18853 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18856 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18857 EVT T = N->getValueType(0);
18858 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18859 bool Regs64bit = T == MVT::i128;
18860 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18861 SDValue cpInL, cpInH;
18862 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18863 DAG.getConstant(0, dl, HalfT));
18864 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18865 DAG.getConstant(1, dl, HalfT));
18866 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18867 Regs64bit ? X86::RAX : X86::EAX,
18869 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18870 Regs64bit ? X86::RDX : X86::EDX,
18871 cpInH, cpInL.getValue(1));
18872 SDValue swapInL, swapInH;
18873 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18874 DAG.getConstant(0, dl, HalfT));
18875 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18876 DAG.getConstant(1, dl, HalfT));
18877 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18878 Regs64bit ? X86::RBX : X86::EBX,
18879 swapInL, cpInH.getValue(1));
18880 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18881 Regs64bit ? X86::RCX : X86::ECX,
18882 swapInH, swapInL.getValue(1));
18883 SDValue Ops[] = { swapInH.getValue(0),
18885 swapInH.getValue(1) };
18886 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18887 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18888 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18889 X86ISD::LCMPXCHG8_DAG;
18890 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18891 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18892 Regs64bit ? X86::RAX : X86::EAX,
18893 HalfT, Result.getValue(1));
18894 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18895 Regs64bit ? X86::RDX : X86::EDX,
18896 HalfT, cpOutL.getValue(2));
18897 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18899 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18900 MVT::i32, cpOutH.getValue(2));
18902 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18903 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18904 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18906 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18907 Results.push_back(Success);
18908 Results.push_back(EFLAGS.getValue(1));
18911 case ISD::ATOMIC_SWAP:
18912 case ISD::ATOMIC_LOAD_ADD:
18913 case ISD::ATOMIC_LOAD_SUB:
18914 case ISD::ATOMIC_LOAD_AND:
18915 case ISD::ATOMIC_LOAD_OR:
18916 case ISD::ATOMIC_LOAD_XOR:
18917 case ISD::ATOMIC_LOAD_NAND:
18918 case ISD::ATOMIC_LOAD_MIN:
18919 case ISD::ATOMIC_LOAD_MAX:
18920 case ISD::ATOMIC_LOAD_UMIN:
18921 case ISD::ATOMIC_LOAD_UMAX:
18922 case ISD::ATOMIC_LOAD: {
18923 // Delegate to generic TypeLegalization. Situations we can really handle
18924 // should have already been dealt with by AtomicExpandPass.cpp.
18927 case ISD::BITCAST: {
18928 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18929 EVT DstVT = N->getValueType(0);
18930 EVT SrcVT = N->getOperand(0)->getValueType(0);
18932 if (SrcVT != MVT::f64 ||
18933 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18936 unsigned NumElts = DstVT.getVectorNumElements();
18937 EVT SVT = DstVT.getVectorElementType();
18938 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18939 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18940 MVT::v2f64, N->getOperand(0));
18941 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18943 if (ExperimentalVectorWideningLegalization) {
18944 // If we are legalizing vectors by widening, we already have the desired
18945 // legal vector type, just return it.
18946 Results.push_back(ToVecInt);
18950 SmallVector<SDValue, 8> Elts;
18951 for (unsigned i = 0, e = NumElts; i != e; ++i)
18952 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18953 ToVecInt, DAG.getIntPtrConstant(i, dl)));
18955 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18960 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18961 switch ((X86ISD::NodeType)Opcode) {
18962 case X86ISD::FIRST_NUMBER: break;
18963 case X86ISD::BSF: return "X86ISD::BSF";
18964 case X86ISD::BSR: return "X86ISD::BSR";
18965 case X86ISD::SHLD: return "X86ISD::SHLD";
18966 case X86ISD::SHRD: return "X86ISD::SHRD";
18967 case X86ISD::FAND: return "X86ISD::FAND";
18968 case X86ISD::FANDN: return "X86ISD::FANDN";
18969 case X86ISD::FOR: return "X86ISD::FOR";
18970 case X86ISD::FXOR: return "X86ISD::FXOR";
18971 case X86ISD::FILD: return "X86ISD::FILD";
18972 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
18973 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18974 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18975 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18976 case X86ISD::FLD: return "X86ISD::FLD";
18977 case X86ISD::FST: return "X86ISD::FST";
18978 case X86ISD::CALL: return "X86ISD::CALL";
18979 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
18980 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
18981 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
18982 case X86ISD::BT: return "X86ISD::BT";
18983 case X86ISD::CMP: return "X86ISD::CMP";
18984 case X86ISD::COMI: return "X86ISD::COMI";
18985 case X86ISD::UCOMI: return "X86ISD::UCOMI";
18986 case X86ISD::CMPM: return "X86ISD::CMPM";
18987 case X86ISD::CMPMU: return "X86ISD::CMPMU";
18988 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
18989 case X86ISD::SETCC: return "X86ISD::SETCC";
18990 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
18991 case X86ISD::FSETCC: return "X86ISD::FSETCC";
18992 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
18993 case X86ISD::CMOV: return "X86ISD::CMOV";
18994 case X86ISD::BRCOND: return "X86ISD::BRCOND";
18995 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
18996 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
18997 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
18998 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
18999 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19000 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19001 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19002 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19003 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19004 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19005 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19006 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19007 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19008 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19009 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19010 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19011 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19012 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19013 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19014 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19015 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19016 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19017 case X86ISD::HADD: return "X86ISD::HADD";
19018 case X86ISD::HSUB: return "X86ISD::HSUB";
19019 case X86ISD::FHADD: return "X86ISD::FHADD";
19020 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19021 case X86ISD::ABS: return "X86ISD::ABS";
19022 case X86ISD::FMAX: return "X86ISD::FMAX";
19023 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19024 case X86ISD::FMIN: return "X86ISD::FMIN";
19025 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19026 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19027 case X86ISD::FMINC: return "X86ISD::FMINC";
19028 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19029 case X86ISD::FRCP: return "X86ISD::FRCP";
19030 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19031 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19032 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19033 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19034 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19035 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19036 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19037 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19038 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19039 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19040 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19041 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19042 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19043 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19044 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19045 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19046 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19047 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19048 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19049 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19050 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19051 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19052 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19053 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19054 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19055 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19056 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19057 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19058 case X86ISD::VSHL: return "X86ISD::VSHL";
19059 case X86ISD::VSRL: return "X86ISD::VSRL";
19060 case X86ISD::VSRA: return "X86ISD::VSRA";
19061 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19062 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19063 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19064 case X86ISD::CMPP: return "X86ISD::CMPP";
19065 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19066 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19067 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19068 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19069 case X86ISD::ADD: return "X86ISD::ADD";
19070 case X86ISD::SUB: return "X86ISD::SUB";
19071 case X86ISD::ADC: return "X86ISD::ADC";
19072 case X86ISD::SBB: return "X86ISD::SBB";
19073 case X86ISD::SMUL: return "X86ISD::SMUL";
19074 case X86ISD::UMUL: return "X86ISD::UMUL";
19075 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19076 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19077 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19078 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19079 case X86ISD::INC: return "X86ISD::INC";
19080 case X86ISD::DEC: return "X86ISD::DEC";
19081 case X86ISD::OR: return "X86ISD::OR";
19082 case X86ISD::XOR: return "X86ISD::XOR";
19083 case X86ISD::AND: return "X86ISD::AND";
19084 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19085 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19086 case X86ISD::PTEST: return "X86ISD::PTEST";
19087 case X86ISD::TESTP: return "X86ISD::TESTP";
19088 case X86ISD::TESTM: return "X86ISD::TESTM";
19089 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19090 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19091 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19092 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19093 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19094 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19095 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19096 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19097 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19098 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19099 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19100 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19101 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19102 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19103 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19104 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19105 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19106 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19107 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19108 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19109 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19110 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19111 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19112 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19113 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19114 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19115 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19116 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19117 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19118 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19119 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19120 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19121 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19122 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19123 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19124 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19125 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19126 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19127 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19128 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19129 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19130 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19131 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19132 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19133 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19134 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19135 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19136 case X86ISD::SAHF: return "X86ISD::SAHF";
19137 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19138 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19139 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19140 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19141 case X86ISD::FMADD: return "X86ISD::FMADD";
19142 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19143 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19144 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19145 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19146 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19147 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19148 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19149 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19150 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19151 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19152 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19153 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19154 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19155 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19156 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19157 case X86ISD::XTEST: return "X86ISD::XTEST";
19158 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19159 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19160 case X86ISD::SELECT: return "X86ISD::SELECT";
19161 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19162 case X86ISD::RCP28: return "X86ISD::RCP28";
19163 case X86ISD::EXP2: return "X86ISD::EXP2";
19164 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19165 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19166 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19167 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19168 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19169 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19170 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19171 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19172 case X86ISD::ADDS: return "X86ISD::ADDS";
19173 case X86ISD::SUBS: return "X86ISD::SUBS";
19174 case X86ISD::AVG: return "X86ISD::AVG";
19175 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19176 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19177 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19178 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19179 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19184 // isLegalAddressingMode - Return true if the addressing mode represented
19185 // by AM is legal for this target, for a load/store of the specified type.
19186 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19187 const AddrMode &AM, Type *Ty,
19188 unsigned AS) const {
19189 // X86 supports extremely general addressing modes.
19190 CodeModel::Model M = getTargetMachine().getCodeModel();
19191 Reloc::Model R = getTargetMachine().getRelocationModel();
19193 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19194 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19199 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19201 // If a reference to this global requires an extra load, we can't fold it.
19202 if (isGlobalStubReference(GVFlags))
19205 // If BaseGV requires a register for the PIC base, we cannot also have a
19206 // BaseReg specified.
19207 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19210 // If lower 4G is not available, then we must use rip-relative addressing.
19211 if ((M != CodeModel::Small || R != Reloc::Static) &&
19212 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19216 switch (AM.Scale) {
19222 // These scales always work.
19227 // These scales are formed with basereg+scalereg. Only accept if there is
19232 default: // Other stuff never works.
19239 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19240 unsigned Bits = Ty->getScalarSizeInBits();
19242 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19243 // particularly cheaper than those without.
19247 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19248 // variable shifts just as cheap as scalar ones.
19249 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19252 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19253 // fully general vector.
19257 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19258 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19260 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19261 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19262 return NumBits1 > NumBits2;
19265 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19266 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19269 if (!isTypeLegal(EVT::getEVT(Ty1)))
19272 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19274 // Assuming the caller doesn't have a zeroext or signext return parameter,
19275 // truncation all the way down to i1 is valid.
19279 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19280 return isInt<32>(Imm);
19283 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19284 // Can also use sub to handle negated immediates.
19285 return isInt<32>(Imm);
19288 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19289 if (!VT1.isInteger() || !VT2.isInteger())
19291 unsigned NumBits1 = VT1.getSizeInBits();
19292 unsigned NumBits2 = VT2.getSizeInBits();
19293 return NumBits1 > NumBits2;
19296 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19297 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19298 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19301 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19302 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19303 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19306 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19307 EVT VT1 = Val.getValueType();
19308 if (isZExtFree(VT1, VT2))
19311 if (Val.getOpcode() != ISD::LOAD)
19314 if (!VT1.isSimple() || !VT1.isInteger() ||
19315 !VT2.isSimple() || !VT2.isInteger())
19318 switch (VT1.getSimpleVT().SimpleTy) {
19323 // X86 has 8, 16, and 32-bit zero-extending loads.
19330 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19333 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19334 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19337 VT = VT.getScalarType();
19339 if (!VT.isSimple())
19342 switch (VT.getSimpleVT().SimpleTy) {
19353 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19354 // i16 instructions are longer (0x66 prefix) and potentially slower.
19355 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19358 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19359 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19360 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19361 /// are assumed to be legal.
19363 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19365 if (!VT.isSimple())
19368 // Not for i1 vectors
19369 if (VT.getScalarType() == MVT::i1)
19372 // Very little shuffling can be done for 64-bit vectors right now.
19373 if (VT.getSizeInBits() == 64)
19376 // We only care that the types being shuffled are legal. The lowering can
19377 // handle any possible shuffle mask that results.
19378 return isTypeLegal(VT.getSimpleVT());
19382 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19384 // Just delegate to the generic legality, clear masks aren't special.
19385 return isShuffleMaskLegal(Mask, VT);
19388 //===----------------------------------------------------------------------===//
19389 // X86 Scheduler Hooks
19390 //===----------------------------------------------------------------------===//
19392 /// Utility function to emit xbegin specifying the start of an RTM region.
19393 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19394 const TargetInstrInfo *TII) {
19395 DebugLoc DL = MI->getDebugLoc();
19397 const BasicBlock *BB = MBB->getBasicBlock();
19398 MachineFunction::iterator I = MBB;
19401 // For the v = xbegin(), we generate
19412 MachineBasicBlock *thisMBB = MBB;
19413 MachineFunction *MF = MBB->getParent();
19414 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19415 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19416 MF->insert(I, mainMBB);
19417 MF->insert(I, sinkMBB);
19419 // Transfer the remainder of BB and its successor edges to sinkMBB.
19420 sinkMBB->splice(sinkMBB->begin(), MBB,
19421 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19422 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19426 // # fallthrough to mainMBB
19427 // # abortion to sinkMBB
19428 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19429 thisMBB->addSuccessor(mainMBB);
19430 thisMBB->addSuccessor(sinkMBB);
19434 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19435 mainMBB->addSuccessor(sinkMBB);
19438 // EAX is live into the sinkMBB
19439 sinkMBB->addLiveIn(X86::EAX);
19440 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19441 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19444 MI->eraseFromParent();
19448 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19449 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19450 // in the .td file.
19451 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19452 const TargetInstrInfo *TII) {
19454 switch (MI->getOpcode()) {
19455 default: llvm_unreachable("illegal opcode!");
19456 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19457 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19458 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19459 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19460 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19461 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19462 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19463 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19466 DebugLoc dl = MI->getDebugLoc();
19467 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19469 unsigned NumArgs = MI->getNumOperands();
19470 for (unsigned i = 1; i < NumArgs; ++i) {
19471 MachineOperand &Op = MI->getOperand(i);
19472 if (!(Op.isReg() && Op.isImplicit()))
19473 MIB.addOperand(Op);
19475 if (MI->hasOneMemOperand())
19476 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19478 BuildMI(*BB, MI, dl,
19479 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19480 .addReg(X86::XMM0);
19482 MI->eraseFromParent();
19486 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19487 // defs in an instruction pattern
19488 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19489 const TargetInstrInfo *TII) {
19491 switch (MI->getOpcode()) {
19492 default: llvm_unreachable("illegal opcode!");
19493 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19494 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19495 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19496 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19497 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19498 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19499 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19500 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19503 DebugLoc dl = MI->getDebugLoc();
19504 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19506 unsigned NumArgs = MI->getNumOperands(); // remove the results
19507 for (unsigned i = 1; i < NumArgs; ++i) {
19508 MachineOperand &Op = MI->getOperand(i);
19509 if (!(Op.isReg() && Op.isImplicit()))
19510 MIB.addOperand(Op);
19512 if (MI->hasOneMemOperand())
19513 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19515 BuildMI(*BB, MI, dl,
19516 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19519 MI->eraseFromParent();
19523 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19524 const X86Subtarget *Subtarget) {
19525 DebugLoc dl = MI->getDebugLoc();
19526 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19527 // Address into RAX/EAX, other two args into ECX, EDX.
19528 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19529 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19530 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19531 for (int i = 0; i < X86::AddrNumOperands; ++i)
19532 MIB.addOperand(MI->getOperand(i));
19534 unsigned ValOps = X86::AddrNumOperands;
19535 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19536 .addReg(MI->getOperand(ValOps).getReg());
19537 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19538 .addReg(MI->getOperand(ValOps+1).getReg());
19540 // The instruction doesn't actually take any operands though.
19541 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19543 MI->eraseFromParent(); // The pseudo is gone now.
19547 MachineBasicBlock *
19548 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19549 MachineBasicBlock *MBB) const {
19550 // Emit va_arg instruction on X86-64.
19552 // Operands to this pseudo-instruction:
19553 // 0 ) Output : destination address (reg)
19554 // 1-5) Input : va_list address (addr, i64mem)
19555 // 6 ) ArgSize : Size (in bytes) of vararg type
19556 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19557 // 8 ) Align : Alignment of type
19558 // 9 ) EFLAGS (implicit-def)
19560 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19561 static_assert(X86::AddrNumOperands == 5,
19562 "VAARG_64 assumes 5 address operands");
19564 unsigned DestReg = MI->getOperand(0).getReg();
19565 MachineOperand &Base = MI->getOperand(1);
19566 MachineOperand &Scale = MI->getOperand(2);
19567 MachineOperand &Index = MI->getOperand(3);
19568 MachineOperand &Disp = MI->getOperand(4);
19569 MachineOperand &Segment = MI->getOperand(5);
19570 unsigned ArgSize = MI->getOperand(6).getImm();
19571 unsigned ArgMode = MI->getOperand(7).getImm();
19572 unsigned Align = MI->getOperand(8).getImm();
19574 // Memory Reference
19575 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19576 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19577 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19579 // Machine Information
19580 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19581 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19582 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19583 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19584 DebugLoc DL = MI->getDebugLoc();
19586 // struct va_list {
19589 // i64 overflow_area (address)
19590 // i64 reg_save_area (address)
19592 // sizeof(va_list) = 24
19593 // alignment(va_list) = 8
19595 unsigned TotalNumIntRegs = 6;
19596 unsigned TotalNumXMMRegs = 8;
19597 bool UseGPOffset = (ArgMode == 1);
19598 bool UseFPOffset = (ArgMode == 2);
19599 unsigned MaxOffset = TotalNumIntRegs * 8 +
19600 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19602 /* Align ArgSize to a multiple of 8 */
19603 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19604 bool NeedsAlign = (Align > 8);
19606 MachineBasicBlock *thisMBB = MBB;
19607 MachineBasicBlock *overflowMBB;
19608 MachineBasicBlock *offsetMBB;
19609 MachineBasicBlock *endMBB;
19611 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19612 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19613 unsigned OffsetReg = 0;
19615 if (!UseGPOffset && !UseFPOffset) {
19616 // If we only pull from the overflow region, we don't create a branch.
19617 // We don't need to alter control flow.
19618 OffsetDestReg = 0; // unused
19619 OverflowDestReg = DestReg;
19621 offsetMBB = nullptr;
19622 overflowMBB = thisMBB;
19625 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19626 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19627 // If not, pull from overflow_area. (branch to overflowMBB)
19632 // offsetMBB overflowMBB
19637 // Registers for the PHI in endMBB
19638 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19639 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19641 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19642 MachineFunction *MF = MBB->getParent();
19643 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19644 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19645 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19647 MachineFunction::iterator MBBIter = MBB;
19650 // Insert the new basic blocks
19651 MF->insert(MBBIter, offsetMBB);
19652 MF->insert(MBBIter, overflowMBB);
19653 MF->insert(MBBIter, endMBB);
19655 // Transfer the remainder of MBB and its successor edges to endMBB.
19656 endMBB->splice(endMBB->begin(), thisMBB,
19657 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19658 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19660 // Make offsetMBB and overflowMBB successors of thisMBB
19661 thisMBB->addSuccessor(offsetMBB);
19662 thisMBB->addSuccessor(overflowMBB);
19664 // endMBB is a successor of both offsetMBB and overflowMBB
19665 offsetMBB->addSuccessor(endMBB);
19666 overflowMBB->addSuccessor(endMBB);
19668 // Load the offset value into a register
19669 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19670 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19674 .addDisp(Disp, UseFPOffset ? 4 : 0)
19675 .addOperand(Segment)
19676 .setMemRefs(MMOBegin, MMOEnd);
19678 // Check if there is enough room left to pull this argument.
19679 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19681 .addImm(MaxOffset + 8 - ArgSizeA8);
19683 // Branch to "overflowMBB" if offset >= max
19684 // Fall through to "offsetMBB" otherwise
19685 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19686 .addMBB(overflowMBB);
19689 // In offsetMBB, emit code to use the reg_save_area.
19691 assert(OffsetReg != 0);
19693 // Read the reg_save_area address.
19694 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19695 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19700 .addOperand(Segment)
19701 .setMemRefs(MMOBegin, MMOEnd);
19703 // Zero-extend the offset
19704 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19705 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19708 .addImm(X86::sub_32bit);
19710 // Add the offset to the reg_save_area to get the final address.
19711 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19712 .addReg(OffsetReg64)
19713 .addReg(RegSaveReg);
19715 // Compute the offset for the next argument
19716 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19717 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19719 .addImm(UseFPOffset ? 16 : 8);
19721 // Store it back into the va_list.
19722 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19726 .addDisp(Disp, UseFPOffset ? 4 : 0)
19727 .addOperand(Segment)
19728 .addReg(NextOffsetReg)
19729 .setMemRefs(MMOBegin, MMOEnd);
19732 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19737 // Emit code to use overflow area
19740 // Load the overflow_area address into a register.
19741 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19742 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19747 .addOperand(Segment)
19748 .setMemRefs(MMOBegin, MMOEnd);
19750 // If we need to align it, do so. Otherwise, just copy the address
19751 // to OverflowDestReg.
19753 // Align the overflow address
19754 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19755 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19757 // aligned_addr = (addr + (align-1)) & ~(align-1)
19758 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19759 .addReg(OverflowAddrReg)
19762 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19764 .addImm(~(uint64_t)(Align-1));
19766 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19767 .addReg(OverflowAddrReg);
19770 // Compute the next overflow address after this argument.
19771 // (the overflow address should be kept 8-byte aligned)
19772 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19773 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19774 .addReg(OverflowDestReg)
19775 .addImm(ArgSizeA8);
19777 // Store the new overflow address.
19778 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19783 .addOperand(Segment)
19784 .addReg(NextAddrReg)
19785 .setMemRefs(MMOBegin, MMOEnd);
19787 // If we branched, emit the PHI to the front of endMBB.
19789 BuildMI(*endMBB, endMBB->begin(), DL,
19790 TII->get(X86::PHI), DestReg)
19791 .addReg(OffsetDestReg).addMBB(offsetMBB)
19792 .addReg(OverflowDestReg).addMBB(overflowMBB);
19795 // Erase the pseudo instruction
19796 MI->eraseFromParent();
19801 MachineBasicBlock *
19802 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19804 MachineBasicBlock *MBB) const {
19805 // Emit code to save XMM registers to the stack. The ABI says that the
19806 // number of registers to save is given in %al, so it's theoretically
19807 // possible to do an indirect jump trick to avoid saving all of them,
19808 // however this code takes a simpler approach and just executes all
19809 // of the stores if %al is non-zero. It's less code, and it's probably
19810 // easier on the hardware branch predictor, and stores aren't all that
19811 // expensive anyway.
19813 // Create the new basic blocks. One block contains all the XMM stores,
19814 // and one block is the final destination regardless of whether any
19815 // stores were performed.
19816 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19817 MachineFunction *F = MBB->getParent();
19818 MachineFunction::iterator MBBIter = MBB;
19820 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19821 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19822 F->insert(MBBIter, XMMSaveMBB);
19823 F->insert(MBBIter, EndMBB);
19825 // Transfer the remainder of MBB and its successor edges to EndMBB.
19826 EndMBB->splice(EndMBB->begin(), MBB,
19827 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19828 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19830 // The original block will now fall through to the XMM save block.
19831 MBB->addSuccessor(XMMSaveMBB);
19832 // The XMMSaveMBB will fall through to the end block.
19833 XMMSaveMBB->addSuccessor(EndMBB);
19835 // Now add the instructions.
19836 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19837 DebugLoc DL = MI->getDebugLoc();
19839 unsigned CountReg = MI->getOperand(0).getReg();
19840 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19841 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19843 if (!Subtarget->isTargetWin64()) {
19844 // If %al is 0, branch around the XMM save block.
19845 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19846 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19847 MBB->addSuccessor(EndMBB);
19850 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19851 // that was just emitted, but clearly shouldn't be "saved".
19852 assert((MI->getNumOperands() <= 3 ||
19853 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19854 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19855 && "Expected last argument to be EFLAGS");
19856 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19857 // In the XMM save block, save all the XMM argument registers.
19858 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19859 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19860 MachineMemOperand *MMO =
19861 F->getMachineMemOperand(
19862 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19863 MachineMemOperand::MOStore,
19864 /*Size=*/16, /*Align=*/16);
19865 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19866 .addFrameIndex(RegSaveFrameIndex)
19867 .addImm(/*Scale=*/1)
19868 .addReg(/*IndexReg=*/0)
19869 .addImm(/*Disp=*/Offset)
19870 .addReg(/*Segment=*/0)
19871 .addReg(MI->getOperand(i).getReg())
19872 .addMemOperand(MMO);
19875 MI->eraseFromParent(); // The pseudo instruction is gone now.
19880 // The EFLAGS operand of SelectItr might be missing a kill marker
19881 // because there were multiple uses of EFLAGS, and ISel didn't know
19882 // which to mark. Figure out whether SelectItr should have had a
19883 // kill marker, and set it if it should. Returns the correct kill
19885 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19886 MachineBasicBlock* BB,
19887 const TargetRegisterInfo* TRI) {
19888 // Scan forward through BB for a use/def of EFLAGS.
19889 MachineBasicBlock::iterator miI(std::next(SelectItr));
19890 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19891 const MachineInstr& mi = *miI;
19892 if (mi.readsRegister(X86::EFLAGS))
19894 if (mi.definesRegister(X86::EFLAGS))
19895 break; // Should have kill-flag - update below.
19898 // If we hit the end of the block, check whether EFLAGS is live into a
19900 if (miI == BB->end()) {
19901 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19902 sEnd = BB->succ_end();
19903 sItr != sEnd; ++sItr) {
19904 MachineBasicBlock* succ = *sItr;
19905 if (succ->isLiveIn(X86::EFLAGS))
19910 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19911 // out. SelectMI should have a kill flag on EFLAGS.
19912 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19916 MachineBasicBlock *
19917 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19918 MachineBasicBlock *BB) const {
19919 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19920 DebugLoc DL = MI->getDebugLoc();
19922 // To "insert" a SELECT_CC instruction, we actually have to insert the
19923 // diamond control-flow pattern. The incoming instruction knows the
19924 // destination vreg to set, the condition code register to branch on, the
19925 // true/false values to select between, and a branch opcode to use.
19926 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19927 MachineFunction::iterator It = BB;
19933 // cmpTY ccX, r1, r2
19935 // fallthrough --> copy0MBB
19936 MachineBasicBlock *thisMBB = BB;
19937 MachineFunction *F = BB->getParent();
19939 // We also lower double CMOVs:
19940 // (CMOV (CMOV F, T, cc1), T, cc2)
19941 // to two successives branches. For that, we look for another CMOV as the
19942 // following instruction.
19944 // Without this, we would add a PHI between the two jumps, which ends up
19945 // creating a few copies all around. For instance, for
19947 // (sitofp (zext (fcmp une)))
19949 // we would generate:
19951 // ucomiss %xmm1, %xmm0
19952 // movss <1.0f>, %xmm0
19953 // movaps %xmm0, %xmm1
19955 // xorps %xmm1, %xmm1
19958 // movaps %xmm1, %xmm0
19962 // because this custom-inserter would have generated:
19974 // A: X = ...; Y = ...
19976 // C: Z = PHI [X, A], [Y, B]
19978 // E: PHI [X, C], [Z, D]
19980 // If we lower both CMOVs in a single step, we can instead generate:
19992 // A: X = ...; Y = ...
19994 // E: PHI [X, A], [X, C], [Y, D]
19996 // Which, in our sitofp/fcmp example, gives us something like:
19998 // ucomiss %xmm1, %xmm0
19999 // movss <1.0f>, %xmm0
20002 // xorps %xmm0, %xmm0
20006 MachineInstr *NextCMOV = nullptr;
20007 MachineBasicBlock::iterator NextMIIt =
20008 std::next(MachineBasicBlock::iterator(MI));
20009 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20010 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20011 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20012 NextCMOV = &*NextMIIt;
20014 MachineBasicBlock *jcc1MBB = nullptr;
20016 // If we have a double CMOV, we lower it to two successive branches to
20017 // the same block. EFLAGS is used by both, so mark it as live in the second.
20019 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20020 F->insert(It, jcc1MBB);
20021 jcc1MBB->addLiveIn(X86::EFLAGS);
20024 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20025 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20026 F->insert(It, copy0MBB);
20027 F->insert(It, sinkMBB);
20029 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20030 // live into the sink and copy blocks.
20031 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20033 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20034 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20035 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20036 copy0MBB->addLiveIn(X86::EFLAGS);
20037 sinkMBB->addLiveIn(X86::EFLAGS);
20040 // Transfer the remainder of BB and its successor edges to sinkMBB.
20041 sinkMBB->splice(sinkMBB->begin(), BB,
20042 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20043 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20045 // Add the true and fallthrough blocks as its successors.
20047 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20048 BB->addSuccessor(jcc1MBB);
20050 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20051 // jump to the sinkMBB.
20052 jcc1MBB->addSuccessor(copy0MBB);
20053 jcc1MBB->addSuccessor(sinkMBB);
20055 BB->addSuccessor(copy0MBB);
20058 // The true block target of the first (or only) branch is always sinkMBB.
20059 BB->addSuccessor(sinkMBB);
20061 // Create the conditional branch instruction.
20063 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20064 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20067 unsigned Opc2 = X86::GetCondBranchFromCond(
20068 (X86::CondCode)NextCMOV->getOperand(3).getImm());
20069 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20073 // %FalseValue = ...
20074 // # fallthrough to sinkMBB
20075 copy0MBB->addSuccessor(sinkMBB);
20078 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20080 MachineInstrBuilder MIB =
20081 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20082 MI->getOperand(0).getReg())
20083 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20084 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20086 // If we have a double CMOV, the second Jcc provides the same incoming
20087 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20089 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20090 // Copy the PHI result to the register defined by the second CMOV.
20091 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20092 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20093 .addReg(MI->getOperand(0).getReg());
20094 NextCMOV->eraseFromParent();
20097 MI->eraseFromParent(); // The pseudo instruction is gone now.
20101 MachineBasicBlock *
20102 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20103 MachineBasicBlock *BB) const {
20104 MachineFunction *MF = BB->getParent();
20105 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20106 DebugLoc DL = MI->getDebugLoc();
20107 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20109 assert(MF->shouldSplitStack());
20111 const bool Is64Bit = Subtarget->is64Bit();
20112 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20114 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20115 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20118 // ... [Till the alloca]
20119 // If stacklet is not large enough, jump to mallocMBB
20122 // Allocate by subtracting from RSP
20123 // Jump to continueMBB
20126 // Allocate by call to runtime
20130 // [rest of original BB]
20133 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20134 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20135 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20137 MachineRegisterInfo &MRI = MF->getRegInfo();
20138 const TargetRegisterClass *AddrRegClass =
20139 getRegClassFor(getPointerTy(MF->getDataLayout()));
20141 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20142 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20143 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20144 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20145 sizeVReg = MI->getOperand(1).getReg(),
20146 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20148 MachineFunction::iterator MBBIter = BB;
20151 MF->insert(MBBIter, bumpMBB);
20152 MF->insert(MBBIter, mallocMBB);
20153 MF->insert(MBBIter, continueMBB);
20155 continueMBB->splice(continueMBB->begin(), BB,
20156 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20157 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20159 // Add code to the main basic block to check if the stack limit has been hit,
20160 // and if so, jump to mallocMBB otherwise to bumpMBB.
20161 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20162 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20163 .addReg(tmpSPVReg).addReg(sizeVReg);
20164 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20165 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20166 .addReg(SPLimitVReg);
20167 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20169 // bumpMBB simply decreases the stack pointer, since we know the current
20170 // stacklet has enough space.
20171 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20172 .addReg(SPLimitVReg);
20173 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20174 .addReg(SPLimitVReg);
20175 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20177 // Calls into a routine in libgcc to allocate more space from the heap.
20178 const uint32_t *RegMask =
20179 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20181 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20183 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20184 .addExternalSymbol("__morestack_allocate_stack_space")
20185 .addRegMask(RegMask)
20186 .addReg(X86::RDI, RegState::Implicit)
20187 .addReg(X86::RAX, RegState::ImplicitDefine);
20188 } else if (Is64Bit) {
20189 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20191 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20192 .addExternalSymbol("__morestack_allocate_stack_space")
20193 .addRegMask(RegMask)
20194 .addReg(X86::EDI, RegState::Implicit)
20195 .addReg(X86::EAX, RegState::ImplicitDefine);
20197 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20199 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20200 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20201 .addExternalSymbol("__morestack_allocate_stack_space")
20202 .addRegMask(RegMask)
20203 .addReg(X86::EAX, RegState::ImplicitDefine);
20207 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20210 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20211 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20212 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20214 // Set up the CFG correctly.
20215 BB->addSuccessor(bumpMBB);
20216 BB->addSuccessor(mallocMBB);
20217 mallocMBB->addSuccessor(continueMBB);
20218 bumpMBB->addSuccessor(continueMBB);
20220 // Take care of the PHI nodes.
20221 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20222 MI->getOperand(0).getReg())
20223 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20224 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20226 // Delete the original pseudo instruction.
20227 MI->eraseFromParent();
20230 return continueMBB;
20233 MachineBasicBlock *
20234 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20235 MachineBasicBlock *BB) const {
20236 DebugLoc DL = MI->getDebugLoc();
20238 assert(!Subtarget->isTargetMachO());
20240 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20243 MI->eraseFromParent(); // The pseudo instruction is gone now.
20247 MachineBasicBlock *
20248 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20249 MachineBasicBlock *BB) const {
20250 // This is pretty easy. We're taking the value that we received from
20251 // our load from the relocation, sticking it in either RDI (x86-64)
20252 // or EAX and doing an indirect call. The return value will then
20253 // be in the normal return register.
20254 MachineFunction *F = BB->getParent();
20255 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20256 DebugLoc DL = MI->getDebugLoc();
20258 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20259 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20261 // Get a register mask for the lowered call.
20262 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20263 // proper register mask.
20264 const uint32_t *RegMask =
20265 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20266 if (Subtarget->is64Bit()) {
20267 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20268 TII->get(X86::MOV64rm), X86::RDI)
20270 .addImm(0).addReg(0)
20271 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20272 MI->getOperand(3).getTargetFlags())
20274 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20275 addDirectMem(MIB, X86::RDI);
20276 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20277 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20278 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20279 TII->get(X86::MOV32rm), X86::EAX)
20281 .addImm(0).addReg(0)
20282 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20283 MI->getOperand(3).getTargetFlags())
20285 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20286 addDirectMem(MIB, X86::EAX);
20287 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20289 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20290 TII->get(X86::MOV32rm), X86::EAX)
20291 .addReg(TII->getGlobalBaseReg(F))
20292 .addImm(0).addReg(0)
20293 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20294 MI->getOperand(3).getTargetFlags())
20296 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20297 addDirectMem(MIB, X86::EAX);
20298 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20301 MI->eraseFromParent(); // The pseudo instruction is gone now.
20305 MachineBasicBlock *
20306 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20307 MachineBasicBlock *MBB) const {
20308 DebugLoc DL = MI->getDebugLoc();
20309 MachineFunction *MF = MBB->getParent();
20310 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20311 MachineRegisterInfo &MRI = MF->getRegInfo();
20313 const BasicBlock *BB = MBB->getBasicBlock();
20314 MachineFunction::iterator I = MBB;
20317 // Memory Reference
20318 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20319 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20322 unsigned MemOpndSlot = 0;
20324 unsigned CurOp = 0;
20326 DstReg = MI->getOperand(CurOp++).getReg();
20327 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20328 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20329 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20330 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20332 MemOpndSlot = CurOp;
20334 MVT PVT = getPointerTy(MF->getDataLayout());
20335 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20336 "Invalid Pointer Size!");
20338 // For v = setjmp(buf), we generate
20341 // buf[LabelOffset] = restoreMBB
20342 // SjLjSetup restoreMBB
20348 // v = phi(main, restore)
20351 // if base pointer being used, load it from frame
20354 MachineBasicBlock *thisMBB = MBB;
20355 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20356 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20357 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20358 MF->insert(I, mainMBB);
20359 MF->insert(I, sinkMBB);
20360 MF->push_back(restoreMBB);
20362 MachineInstrBuilder MIB;
20364 // Transfer the remainder of BB and its successor edges to sinkMBB.
20365 sinkMBB->splice(sinkMBB->begin(), MBB,
20366 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20367 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20370 unsigned PtrStoreOpc = 0;
20371 unsigned LabelReg = 0;
20372 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20373 Reloc::Model RM = MF->getTarget().getRelocationModel();
20374 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20375 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20377 // Prepare IP either in reg or imm.
20378 if (!UseImmLabel) {
20379 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20380 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20381 LabelReg = MRI.createVirtualRegister(PtrRC);
20382 if (Subtarget->is64Bit()) {
20383 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20387 .addMBB(restoreMBB)
20390 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20391 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20392 .addReg(XII->getGlobalBaseReg(MF))
20395 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20399 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20401 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20402 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20403 if (i == X86::AddrDisp)
20404 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20406 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20409 MIB.addReg(LabelReg);
20411 MIB.addMBB(restoreMBB);
20412 MIB.setMemRefs(MMOBegin, MMOEnd);
20414 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20415 .addMBB(restoreMBB);
20417 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20418 MIB.addRegMask(RegInfo->getNoPreservedMask());
20419 thisMBB->addSuccessor(mainMBB);
20420 thisMBB->addSuccessor(restoreMBB);
20424 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20425 mainMBB->addSuccessor(sinkMBB);
20428 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20429 TII->get(X86::PHI), DstReg)
20430 .addReg(mainDstReg).addMBB(mainMBB)
20431 .addReg(restoreDstReg).addMBB(restoreMBB);
20434 if (RegInfo->hasBasePointer(*MF)) {
20435 const bool Uses64BitFramePtr =
20436 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20437 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20438 X86FI->setRestoreBasePointer(MF);
20439 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20440 unsigned BasePtr = RegInfo->getBaseRegister();
20441 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20442 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20443 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20444 .setMIFlag(MachineInstr::FrameSetup);
20446 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20447 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20448 restoreMBB->addSuccessor(sinkMBB);
20450 MI->eraseFromParent();
20454 MachineBasicBlock *
20455 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20456 MachineBasicBlock *MBB) const {
20457 DebugLoc DL = MI->getDebugLoc();
20458 MachineFunction *MF = MBB->getParent();
20459 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20460 MachineRegisterInfo &MRI = MF->getRegInfo();
20462 // Memory Reference
20463 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20464 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20466 MVT PVT = getPointerTy(MF->getDataLayout());
20467 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20468 "Invalid Pointer Size!");
20470 const TargetRegisterClass *RC =
20471 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20472 unsigned Tmp = MRI.createVirtualRegister(RC);
20473 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20474 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20475 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20476 unsigned SP = RegInfo->getStackRegister();
20478 MachineInstrBuilder MIB;
20480 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20481 const int64_t SPOffset = 2 * PVT.getStoreSize();
20483 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20484 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20487 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20488 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20489 MIB.addOperand(MI->getOperand(i));
20490 MIB.setMemRefs(MMOBegin, MMOEnd);
20492 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20493 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20494 if (i == X86::AddrDisp)
20495 MIB.addDisp(MI->getOperand(i), LabelOffset);
20497 MIB.addOperand(MI->getOperand(i));
20499 MIB.setMemRefs(MMOBegin, MMOEnd);
20501 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20502 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20503 if (i == X86::AddrDisp)
20504 MIB.addDisp(MI->getOperand(i), SPOffset);
20506 MIB.addOperand(MI->getOperand(i));
20508 MIB.setMemRefs(MMOBegin, MMOEnd);
20510 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20512 MI->eraseFromParent();
20516 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20517 // accumulator loops. Writing back to the accumulator allows the coalescer
20518 // to remove extra copies in the loop.
20519 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20520 MachineBasicBlock *
20521 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20522 MachineBasicBlock *MBB) const {
20523 MachineOperand &AddendOp = MI->getOperand(3);
20525 // Bail out early if the addend isn't a register - we can't switch these.
20526 if (!AddendOp.isReg())
20529 MachineFunction &MF = *MBB->getParent();
20530 MachineRegisterInfo &MRI = MF.getRegInfo();
20532 // Check whether the addend is defined by a PHI:
20533 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20534 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20535 if (!AddendDef.isPHI())
20538 // Look for the following pattern:
20540 // %addend = phi [%entry, 0], [%loop, %result]
20542 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20546 // %addend = phi [%entry, 0], [%loop, %result]
20548 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20550 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20551 assert(AddendDef.getOperand(i).isReg());
20552 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20553 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20554 if (&PHISrcInst == MI) {
20555 // Found a matching instruction.
20556 unsigned NewFMAOpc = 0;
20557 switch (MI->getOpcode()) {
20558 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20559 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20560 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20561 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20562 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20563 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20564 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20565 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20566 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20567 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20568 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20569 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20570 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20571 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20572 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20573 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20574 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20575 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20576 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20577 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20579 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20580 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20581 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20582 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20583 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20584 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20585 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20586 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20587 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20588 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20589 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20590 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20591 default: llvm_unreachable("Unrecognized FMA variant.");
20594 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20595 MachineInstrBuilder MIB =
20596 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20597 .addOperand(MI->getOperand(0))
20598 .addOperand(MI->getOperand(3))
20599 .addOperand(MI->getOperand(2))
20600 .addOperand(MI->getOperand(1));
20601 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20602 MI->eraseFromParent();
20609 MachineBasicBlock *
20610 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20611 MachineBasicBlock *BB) const {
20612 switch (MI->getOpcode()) {
20613 default: llvm_unreachable("Unexpected instr type to insert");
20614 case X86::TAILJMPd64:
20615 case X86::TAILJMPr64:
20616 case X86::TAILJMPm64:
20617 case X86::TAILJMPd64_REX:
20618 case X86::TAILJMPr64_REX:
20619 case X86::TAILJMPm64_REX:
20620 llvm_unreachable("TAILJMP64 would not be touched here.");
20621 case X86::TCRETURNdi64:
20622 case X86::TCRETURNri64:
20623 case X86::TCRETURNmi64:
20625 case X86::WIN_ALLOCA:
20626 return EmitLoweredWinAlloca(MI, BB);
20627 case X86::SEG_ALLOCA_32:
20628 case X86::SEG_ALLOCA_64:
20629 return EmitLoweredSegAlloca(MI, BB);
20630 case X86::TLSCall_32:
20631 case X86::TLSCall_64:
20632 return EmitLoweredTLSCall(MI, BB);
20633 case X86::CMOV_GR8:
20634 case X86::CMOV_FR32:
20635 case X86::CMOV_FR64:
20636 case X86::CMOV_V4F32:
20637 case X86::CMOV_V2F64:
20638 case X86::CMOV_V2I64:
20639 case X86::CMOV_V8F32:
20640 case X86::CMOV_V4F64:
20641 case X86::CMOV_V4I64:
20642 case X86::CMOV_V16F32:
20643 case X86::CMOV_V8F64:
20644 case X86::CMOV_V8I64:
20645 case X86::CMOV_GR16:
20646 case X86::CMOV_GR32:
20647 case X86::CMOV_RFP32:
20648 case X86::CMOV_RFP64:
20649 case X86::CMOV_RFP80:
20650 case X86::CMOV_V8I1:
20651 case X86::CMOV_V16I1:
20652 case X86::CMOV_V32I1:
20653 case X86::CMOV_V64I1:
20654 return EmitLoweredSelect(MI, BB);
20656 case X86::FP32_TO_INT16_IN_MEM:
20657 case X86::FP32_TO_INT32_IN_MEM:
20658 case X86::FP32_TO_INT64_IN_MEM:
20659 case X86::FP64_TO_INT16_IN_MEM:
20660 case X86::FP64_TO_INT32_IN_MEM:
20661 case X86::FP64_TO_INT64_IN_MEM:
20662 case X86::FP80_TO_INT16_IN_MEM:
20663 case X86::FP80_TO_INT32_IN_MEM:
20664 case X86::FP80_TO_INT64_IN_MEM: {
20665 MachineFunction *F = BB->getParent();
20666 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20667 DebugLoc DL = MI->getDebugLoc();
20669 // Change the floating point control register to use "round towards zero"
20670 // mode when truncating to an integer value.
20671 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20672 addFrameReference(BuildMI(*BB, MI, DL,
20673 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20675 // Load the old value of the high byte of the control word...
20677 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20678 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20681 // Set the high part to be round to zero...
20682 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20685 // Reload the modified control word now...
20686 addFrameReference(BuildMI(*BB, MI, DL,
20687 TII->get(X86::FLDCW16m)), CWFrameIdx);
20689 // Restore the memory image of control word to original value
20690 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20693 // Get the X86 opcode to use.
20695 switch (MI->getOpcode()) {
20696 default: llvm_unreachable("illegal opcode!");
20697 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20698 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20699 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20700 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20701 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20702 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20703 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20704 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20705 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20709 MachineOperand &Op = MI->getOperand(0);
20711 AM.BaseType = X86AddressMode::RegBase;
20712 AM.Base.Reg = Op.getReg();
20714 AM.BaseType = X86AddressMode::FrameIndexBase;
20715 AM.Base.FrameIndex = Op.getIndex();
20717 Op = MI->getOperand(1);
20719 AM.Scale = Op.getImm();
20720 Op = MI->getOperand(2);
20722 AM.IndexReg = Op.getImm();
20723 Op = MI->getOperand(3);
20724 if (Op.isGlobal()) {
20725 AM.GV = Op.getGlobal();
20727 AM.Disp = Op.getImm();
20729 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20730 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20732 // Reload the original control word now.
20733 addFrameReference(BuildMI(*BB, MI, DL,
20734 TII->get(X86::FLDCW16m)), CWFrameIdx);
20736 MI->eraseFromParent(); // The pseudo instruction is gone now.
20739 // String/text processing lowering.
20740 case X86::PCMPISTRM128REG:
20741 case X86::VPCMPISTRM128REG:
20742 case X86::PCMPISTRM128MEM:
20743 case X86::VPCMPISTRM128MEM:
20744 case X86::PCMPESTRM128REG:
20745 case X86::VPCMPESTRM128REG:
20746 case X86::PCMPESTRM128MEM:
20747 case X86::VPCMPESTRM128MEM:
20748 assert(Subtarget->hasSSE42() &&
20749 "Target must have SSE4.2 or AVX features enabled");
20750 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20752 // String/text processing lowering.
20753 case X86::PCMPISTRIREG:
20754 case X86::VPCMPISTRIREG:
20755 case X86::PCMPISTRIMEM:
20756 case X86::VPCMPISTRIMEM:
20757 case X86::PCMPESTRIREG:
20758 case X86::VPCMPESTRIREG:
20759 case X86::PCMPESTRIMEM:
20760 case X86::VPCMPESTRIMEM:
20761 assert(Subtarget->hasSSE42() &&
20762 "Target must have SSE4.2 or AVX features enabled");
20763 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20765 // Thread synchronization.
20767 return EmitMonitor(MI, BB, Subtarget);
20771 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20773 case X86::VASTART_SAVE_XMM_REGS:
20774 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20776 case X86::VAARG_64:
20777 return EmitVAARG64WithCustomInserter(MI, BB);
20779 case X86::EH_SjLj_SetJmp32:
20780 case X86::EH_SjLj_SetJmp64:
20781 return emitEHSjLjSetJmp(MI, BB);
20783 case X86::EH_SjLj_LongJmp32:
20784 case X86::EH_SjLj_LongJmp64:
20785 return emitEHSjLjLongJmp(MI, BB);
20787 case TargetOpcode::STATEPOINT:
20788 // As an implementation detail, STATEPOINT shares the STACKMAP format at
20789 // this point in the process. We diverge later.
20790 return emitPatchPoint(MI, BB);
20792 case TargetOpcode::STACKMAP:
20793 case TargetOpcode::PATCHPOINT:
20794 return emitPatchPoint(MI, BB);
20796 case X86::VFMADDPDr213r:
20797 case X86::VFMADDPSr213r:
20798 case X86::VFMADDSDr213r:
20799 case X86::VFMADDSSr213r:
20800 case X86::VFMSUBPDr213r:
20801 case X86::VFMSUBPSr213r:
20802 case X86::VFMSUBSDr213r:
20803 case X86::VFMSUBSSr213r:
20804 case X86::VFNMADDPDr213r:
20805 case X86::VFNMADDPSr213r:
20806 case X86::VFNMADDSDr213r:
20807 case X86::VFNMADDSSr213r:
20808 case X86::VFNMSUBPDr213r:
20809 case X86::VFNMSUBPSr213r:
20810 case X86::VFNMSUBSDr213r:
20811 case X86::VFNMSUBSSr213r:
20812 case X86::VFMADDSUBPDr213r:
20813 case X86::VFMADDSUBPSr213r:
20814 case X86::VFMSUBADDPDr213r:
20815 case X86::VFMSUBADDPSr213r:
20816 case X86::VFMADDPDr213rY:
20817 case X86::VFMADDPSr213rY:
20818 case X86::VFMSUBPDr213rY:
20819 case X86::VFMSUBPSr213rY:
20820 case X86::VFNMADDPDr213rY:
20821 case X86::VFNMADDPSr213rY:
20822 case X86::VFNMSUBPDr213rY:
20823 case X86::VFNMSUBPSr213rY:
20824 case X86::VFMADDSUBPDr213rY:
20825 case X86::VFMADDSUBPSr213rY:
20826 case X86::VFMSUBADDPDr213rY:
20827 case X86::VFMSUBADDPSr213rY:
20828 return emitFMA3Instr(MI, BB);
20832 //===----------------------------------------------------------------------===//
20833 // X86 Optimization Hooks
20834 //===----------------------------------------------------------------------===//
20836 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20839 const SelectionDAG &DAG,
20840 unsigned Depth) const {
20841 unsigned BitWidth = KnownZero.getBitWidth();
20842 unsigned Opc = Op.getOpcode();
20843 assert((Opc >= ISD::BUILTIN_OP_END ||
20844 Opc == ISD::INTRINSIC_WO_CHAIN ||
20845 Opc == ISD::INTRINSIC_W_CHAIN ||
20846 Opc == ISD::INTRINSIC_VOID) &&
20847 "Should use MaskedValueIsZero if you don't know whether Op"
20848 " is a target node!");
20850 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
20864 // These nodes' second result is a boolean.
20865 if (Op.getResNo() == 0)
20868 case X86ISD::SETCC:
20869 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20871 case ISD::INTRINSIC_WO_CHAIN: {
20872 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20873 unsigned NumLoBits = 0;
20876 case Intrinsic::x86_sse_movmsk_ps:
20877 case Intrinsic::x86_avx_movmsk_ps_256:
20878 case Intrinsic::x86_sse2_movmsk_pd:
20879 case Intrinsic::x86_avx_movmsk_pd_256:
20880 case Intrinsic::x86_mmx_pmovmskb:
20881 case Intrinsic::x86_sse2_pmovmskb_128:
20882 case Intrinsic::x86_avx2_pmovmskb: {
20883 // High bits of movmskp{s|d}, pmovmskb are known zero.
20885 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
20886 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
20887 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
20888 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
20889 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
20890 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
20891 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
20892 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
20894 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20903 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20905 const SelectionDAG &,
20906 unsigned Depth) const {
20907 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20908 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20909 return Op.getValueType().getScalarType().getSizeInBits();
20915 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20916 /// node is a GlobalAddress + offset.
20917 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20918 const GlobalValue* &GA,
20919 int64_t &Offset) const {
20920 if (N->getOpcode() == X86ISD::Wrapper) {
20921 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20922 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20923 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20927 return TargetLowering::isGAPlusOffset(N, GA, Offset);
20930 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20931 /// same as extracting the high 128-bit part of 256-bit vector and then
20932 /// inserting the result into the low part of a new 256-bit vector
20933 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20934 EVT VT = SVOp->getValueType(0);
20935 unsigned NumElems = VT.getVectorNumElements();
20937 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20938 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20939 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20940 SVOp->getMaskElt(j) >= 0)
20946 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20947 /// same as extracting the low 128-bit part of 256-bit vector and then
20948 /// inserting the result into the high part of a new 256-bit vector
20949 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20950 EVT VT = SVOp->getValueType(0);
20951 unsigned NumElems = VT.getVectorNumElements();
20953 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20954 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20955 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20956 SVOp->getMaskElt(j) >= 0)
20962 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20963 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20964 TargetLowering::DAGCombinerInfo &DCI,
20965 const X86Subtarget* Subtarget) {
20967 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20968 SDValue V1 = SVOp->getOperand(0);
20969 SDValue V2 = SVOp->getOperand(1);
20970 EVT VT = SVOp->getValueType(0);
20971 unsigned NumElems = VT.getVectorNumElements();
20973 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20974 V2.getOpcode() == ISD::CONCAT_VECTORS) {
20978 // V UNDEF BUILD_VECTOR UNDEF
20980 // CONCAT_VECTOR CONCAT_VECTOR
20983 // RESULT: V + zero extended
20985 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20986 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20987 V1.getOperand(1).getOpcode() != ISD::UNDEF)
20990 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20993 // To match the shuffle mask, the first half of the mask should
20994 // be exactly the first vector, and all the rest a splat with the
20995 // first element of the second one.
20996 for (unsigned i = 0; i != NumElems/2; ++i)
20997 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20998 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21001 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21002 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21003 if (Ld->hasNUsesOfValue(1, 0)) {
21004 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21005 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21007 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21009 Ld->getPointerInfo(),
21010 Ld->getAlignment(),
21011 false/*isVolatile*/, true/*ReadMem*/,
21012 false/*WriteMem*/);
21014 // Make sure the newly-created LOAD is in the same position as Ld in
21015 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21016 // and update uses of Ld's output chain to use the TokenFactor.
21017 if (Ld->hasAnyUseOfValue(1)) {
21018 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21019 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21020 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21021 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21022 SDValue(ResNode.getNode(), 1));
21025 return DAG.getBitcast(VT, ResNode);
21029 // Emit a zeroed vector and insert the desired subvector on its
21031 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21032 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21033 return DCI.CombineTo(N, InsV);
21036 //===--------------------------------------------------------------------===//
21037 // Combine some shuffles into subvector extracts and inserts:
21040 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21041 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21042 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21043 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21044 return DCI.CombineTo(N, InsV);
21047 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21048 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21049 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21050 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21051 return DCI.CombineTo(N, InsV);
21057 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21060 /// This is the leaf of the recursive combinine below. When we have found some
21061 /// chain of single-use x86 shuffle instructions and accumulated the combined
21062 /// shuffle mask represented by them, this will try to pattern match that mask
21063 /// into either a single instruction if there is a special purpose instruction
21064 /// for this operation, or into a PSHUFB instruction which is a fully general
21065 /// instruction but should only be used to replace chains over a certain depth.
21066 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21067 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21068 TargetLowering::DAGCombinerInfo &DCI,
21069 const X86Subtarget *Subtarget) {
21070 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21072 // Find the operand that enters the chain. Note that multiple uses are OK
21073 // here, we're not going to remove the operand we find.
21074 SDValue Input = Op.getOperand(0);
21075 while (Input.getOpcode() == ISD::BITCAST)
21076 Input = Input.getOperand(0);
21078 MVT VT = Input.getSimpleValueType();
21079 MVT RootVT = Root.getSimpleValueType();
21082 // Just remove no-op shuffle masks.
21083 if (Mask.size() == 1) {
21084 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21089 // Use the float domain if the operand type is a floating point type.
21090 bool FloatDomain = VT.isFloatingPoint();
21092 // For floating point shuffles, we don't have free copies in the shuffle
21093 // instructions or the ability to load as part of the instruction, so
21094 // canonicalize their shuffles to UNPCK or MOV variants.
21096 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21097 // vectors because it can have a load folded into it that UNPCK cannot. This
21098 // doesn't preclude something switching to the shorter encoding post-RA.
21100 // FIXME: Should teach these routines about AVX vector widths.
21101 if (FloatDomain && VT.getSizeInBits() == 128) {
21102 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21103 bool Lo = Mask.equals({0, 0});
21106 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21107 // is no slower than UNPCKLPD but has the option to fold the input operand
21108 // into even an unaligned memory load.
21109 if (Lo && Subtarget->hasSSE3()) {
21110 Shuffle = X86ISD::MOVDDUP;
21111 ShuffleVT = MVT::v2f64;
21113 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21114 // than the UNPCK variants.
21115 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21116 ShuffleVT = MVT::v4f32;
21118 if (Depth == 1 && Root->getOpcode() == Shuffle)
21119 return false; // Nothing to do!
21120 Op = DAG.getBitcast(ShuffleVT, Input);
21121 DCI.AddToWorklist(Op.getNode());
21122 if (Shuffle == X86ISD::MOVDDUP)
21123 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21125 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21126 DCI.AddToWorklist(Op.getNode());
21127 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21131 if (Subtarget->hasSSE3() &&
21132 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21133 bool Lo = Mask.equals({0, 0, 2, 2});
21134 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21135 MVT ShuffleVT = MVT::v4f32;
21136 if (Depth == 1 && Root->getOpcode() == Shuffle)
21137 return false; // Nothing to do!
21138 Op = DAG.getBitcast(ShuffleVT, Input);
21139 DCI.AddToWorklist(Op.getNode());
21140 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21141 DCI.AddToWorklist(Op.getNode());
21142 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21146 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21147 bool Lo = Mask.equals({0, 0, 1, 1});
21148 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21149 MVT ShuffleVT = MVT::v4f32;
21150 if (Depth == 1 && Root->getOpcode() == Shuffle)
21151 return false; // Nothing to do!
21152 Op = DAG.getBitcast(ShuffleVT, Input);
21153 DCI.AddToWorklist(Op.getNode());
21154 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21155 DCI.AddToWorklist(Op.getNode());
21156 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21162 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21163 // variants as none of these have single-instruction variants that are
21164 // superior to the UNPCK formulation.
21165 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21166 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21167 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21168 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21170 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21171 bool Lo = Mask[0] == 0;
21172 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21173 if (Depth == 1 && Root->getOpcode() == Shuffle)
21174 return false; // Nothing to do!
21176 switch (Mask.size()) {
21178 ShuffleVT = MVT::v8i16;
21181 ShuffleVT = MVT::v16i8;
21184 llvm_unreachable("Impossible mask size!");
21186 Op = DAG.getBitcast(ShuffleVT, Input);
21187 DCI.AddToWorklist(Op.getNode());
21188 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21189 DCI.AddToWorklist(Op.getNode());
21190 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21195 // Don't try to re-form single instruction chains under any circumstances now
21196 // that we've done encoding canonicalization for them.
21200 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21201 // can replace them with a single PSHUFB instruction profitably. Intel's
21202 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21203 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21204 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21205 SmallVector<SDValue, 16> PSHUFBMask;
21206 int NumBytes = VT.getSizeInBits() / 8;
21207 int Ratio = NumBytes / Mask.size();
21208 for (int i = 0; i < NumBytes; ++i) {
21209 if (Mask[i / Ratio] == SM_SentinelUndef) {
21210 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21213 int M = Mask[i / Ratio] != SM_SentinelZero
21214 ? Ratio * Mask[i / Ratio] + i % Ratio
21216 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21218 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21219 Op = DAG.getBitcast(ByteVT, Input);
21220 DCI.AddToWorklist(Op.getNode());
21221 SDValue PSHUFBMaskOp =
21222 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21223 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21224 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21225 DCI.AddToWorklist(Op.getNode());
21226 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21231 // Failed to find any combines.
21235 /// \brief Fully generic combining of x86 shuffle instructions.
21237 /// This should be the last combine run over the x86 shuffle instructions. Once
21238 /// they have been fully optimized, this will recursively consider all chains
21239 /// of single-use shuffle instructions, build a generic model of the cumulative
21240 /// shuffle operation, and check for simpler instructions which implement this
21241 /// operation. We use this primarily for two purposes:
21243 /// 1) Collapse generic shuffles to specialized single instructions when
21244 /// equivalent. In most cases, this is just an encoding size win, but
21245 /// sometimes we will collapse multiple generic shuffles into a single
21246 /// special-purpose shuffle.
21247 /// 2) Look for sequences of shuffle instructions with 3 or more total
21248 /// instructions, and replace them with the slightly more expensive SSSE3
21249 /// PSHUFB instruction if available. We do this as the last combining step
21250 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21251 /// a suitable short sequence of other instructions. The PHUFB will either
21252 /// use a register or have to read from memory and so is slightly (but only
21253 /// slightly) more expensive than the other shuffle instructions.
21255 /// Because this is inherently a quadratic operation (for each shuffle in
21256 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21257 /// This should never be an issue in practice as the shuffle lowering doesn't
21258 /// produce sequences of more than 8 instructions.
21260 /// FIXME: We will currently miss some cases where the redundant shuffling
21261 /// would simplify under the threshold for PSHUFB formation because of
21262 /// combine-ordering. To fix this, we should do the redundant instruction
21263 /// combining in this recursive walk.
21264 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21265 ArrayRef<int> RootMask,
21266 int Depth, bool HasPSHUFB,
21268 TargetLowering::DAGCombinerInfo &DCI,
21269 const X86Subtarget *Subtarget) {
21270 // Bound the depth of our recursive combine because this is ultimately
21271 // quadratic in nature.
21275 // Directly rip through bitcasts to find the underlying operand.
21276 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21277 Op = Op.getOperand(0);
21279 MVT VT = Op.getSimpleValueType();
21280 if (!VT.isVector())
21281 return false; // Bail if we hit a non-vector.
21283 assert(Root.getSimpleValueType().isVector() &&
21284 "Shuffles operate on vector types!");
21285 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21286 "Can only combine shuffles of the same vector register size.");
21288 if (!isTargetShuffle(Op.getOpcode()))
21290 SmallVector<int, 16> OpMask;
21292 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21293 // We only can combine unary shuffles which we can decode the mask for.
21294 if (!HaveMask || !IsUnary)
21297 assert(VT.getVectorNumElements() == OpMask.size() &&
21298 "Different mask size from vector size!");
21299 assert(((RootMask.size() > OpMask.size() &&
21300 RootMask.size() % OpMask.size() == 0) ||
21301 (OpMask.size() > RootMask.size() &&
21302 OpMask.size() % RootMask.size() == 0) ||
21303 OpMask.size() == RootMask.size()) &&
21304 "The smaller number of elements must divide the larger.");
21305 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21306 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21307 assert(((RootRatio == 1 && OpRatio == 1) ||
21308 (RootRatio == 1) != (OpRatio == 1)) &&
21309 "Must not have a ratio for both incoming and op masks!");
21311 SmallVector<int, 16> Mask;
21312 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21314 // Merge this shuffle operation's mask into our accumulated mask. Note that
21315 // this shuffle's mask will be the first applied to the input, followed by the
21316 // root mask to get us all the way to the root value arrangement. The reason
21317 // for this order is that we are recursing up the operation chain.
21318 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21319 int RootIdx = i / RootRatio;
21320 if (RootMask[RootIdx] < 0) {
21321 // This is a zero or undef lane, we're done.
21322 Mask.push_back(RootMask[RootIdx]);
21326 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21327 int OpIdx = RootMaskedIdx / OpRatio;
21328 if (OpMask[OpIdx] < 0) {
21329 // The incoming lanes are zero or undef, it doesn't matter which ones we
21331 Mask.push_back(OpMask[OpIdx]);
21335 // Ok, we have non-zero lanes, map them through.
21336 Mask.push_back(OpMask[OpIdx] * OpRatio +
21337 RootMaskedIdx % OpRatio);
21340 // See if we can recurse into the operand to combine more things.
21341 switch (Op.getOpcode()) {
21342 case X86ISD::PSHUFB:
21344 case X86ISD::PSHUFD:
21345 case X86ISD::PSHUFHW:
21346 case X86ISD::PSHUFLW:
21347 if (Op.getOperand(0).hasOneUse() &&
21348 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21349 HasPSHUFB, DAG, DCI, Subtarget))
21353 case X86ISD::UNPCKL:
21354 case X86ISD::UNPCKH:
21355 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21356 // We can't check for single use, we have to check that this shuffle is the only user.
21357 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21358 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21359 HasPSHUFB, DAG, DCI, Subtarget))
21364 // Minor canonicalization of the accumulated shuffle mask to make it easier
21365 // to match below. All this does is detect masks with squential pairs of
21366 // elements, and shrink them to the half-width mask. It does this in a loop
21367 // so it will reduce the size of the mask to the minimal width mask which
21368 // performs an equivalent shuffle.
21369 SmallVector<int, 16> WidenedMask;
21370 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21371 Mask = std::move(WidenedMask);
21372 WidenedMask.clear();
21375 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21379 /// \brief Get the PSHUF-style mask from PSHUF node.
21381 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21382 /// PSHUF-style masks that can be reused with such instructions.
21383 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21384 MVT VT = N.getSimpleValueType();
21385 SmallVector<int, 4> Mask;
21387 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21391 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21392 // matter. Check that the upper masks are repeats and remove them.
21393 if (VT.getSizeInBits() > 128) {
21394 int LaneElts = 128 / VT.getScalarSizeInBits();
21396 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21397 for (int j = 0; j < LaneElts; ++j)
21398 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21399 "Mask doesn't repeat in high 128-bit lanes!");
21401 Mask.resize(LaneElts);
21404 switch (N.getOpcode()) {
21405 case X86ISD::PSHUFD:
21407 case X86ISD::PSHUFLW:
21410 case X86ISD::PSHUFHW:
21411 Mask.erase(Mask.begin(), Mask.begin() + 4);
21412 for (int &M : Mask)
21416 llvm_unreachable("No valid shuffle instruction found!");
21420 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21422 /// We walk up the chain and look for a combinable shuffle, skipping over
21423 /// shuffles that we could hoist this shuffle's transformation past without
21424 /// altering anything.
21426 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21428 TargetLowering::DAGCombinerInfo &DCI) {
21429 assert(N.getOpcode() == X86ISD::PSHUFD &&
21430 "Called with something other than an x86 128-bit half shuffle!");
21433 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21434 // of the shuffles in the chain so that we can form a fresh chain to replace
21436 SmallVector<SDValue, 8> Chain;
21437 SDValue V = N.getOperand(0);
21438 for (; V.hasOneUse(); V = V.getOperand(0)) {
21439 switch (V.getOpcode()) {
21441 return SDValue(); // Nothing combined!
21444 // Skip bitcasts as we always know the type for the target specific
21448 case X86ISD::PSHUFD:
21449 // Found another dword shuffle.
21452 case X86ISD::PSHUFLW:
21453 // Check that the low words (being shuffled) are the identity in the
21454 // dword shuffle, and the high words are self-contained.
21455 if (Mask[0] != 0 || Mask[1] != 1 ||
21456 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21459 Chain.push_back(V);
21462 case X86ISD::PSHUFHW:
21463 // Check that the high words (being shuffled) are the identity in the
21464 // dword shuffle, and the low words are self-contained.
21465 if (Mask[2] != 2 || Mask[3] != 3 ||
21466 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21469 Chain.push_back(V);
21472 case X86ISD::UNPCKL:
21473 case X86ISD::UNPCKH:
21474 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21475 // shuffle into a preceding word shuffle.
21476 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21477 V.getSimpleValueType().getScalarType() != MVT::i16)
21480 // Search for a half-shuffle which we can combine with.
21481 unsigned CombineOp =
21482 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21483 if (V.getOperand(0) != V.getOperand(1) ||
21484 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21486 Chain.push_back(V);
21487 V = V.getOperand(0);
21489 switch (V.getOpcode()) {
21491 return SDValue(); // Nothing to combine.
21493 case X86ISD::PSHUFLW:
21494 case X86ISD::PSHUFHW:
21495 if (V.getOpcode() == CombineOp)
21498 Chain.push_back(V);
21502 V = V.getOperand(0);
21506 } while (V.hasOneUse());
21509 // Break out of the loop if we break out of the switch.
21513 if (!V.hasOneUse())
21514 // We fell out of the loop without finding a viable combining instruction.
21517 // Merge this node's mask and our incoming mask.
21518 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21519 for (int &M : Mask)
21521 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21522 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21524 // Rebuild the chain around this new shuffle.
21525 while (!Chain.empty()) {
21526 SDValue W = Chain.pop_back_val();
21528 if (V.getValueType() != W.getOperand(0).getValueType())
21529 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21531 switch (W.getOpcode()) {
21533 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21535 case X86ISD::UNPCKL:
21536 case X86ISD::UNPCKH:
21537 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21540 case X86ISD::PSHUFD:
21541 case X86ISD::PSHUFLW:
21542 case X86ISD::PSHUFHW:
21543 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21547 if (V.getValueType() != N.getValueType())
21548 V = DAG.getBitcast(N.getValueType(), V);
21550 // Return the new chain to replace N.
21554 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21556 /// We walk up the chain, skipping shuffles of the other half and looking
21557 /// through shuffles which switch halves trying to find a shuffle of the same
21558 /// pair of dwords.
21559 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21561 TargetLowering::DAGCombinerInfo &DCI) {
21563 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21564 "Called with something other than an x86 128-bit half shuffle!");
21566 unsigned CombineOpcode = N.getOpcode();
21568 // Walk up a single-use chain looking for a combinable shuffle.
21569 SDValue V = N.getOperand(0);
21570 for (; V.hasOneUse(); V = V.getOperand(0)) {
21571 switch (V.getOpcode()) {
21573 return false; // Nothing combined!
21576 // Skip bitcasts as we always know the type for the target specific
21580 case X86ISD::PSHUFLW:
21581 case X86ISD::PSHUFHW:
21582 if (V.getOpcode() == CombineOpcode)
21585 // Other-half shuffles are no-ops.
21588 // Break out of the loop if we break out of the switch.
21592 if (!V.hasOneUse())
21593 // We fell out of the loop without finding a viable combining instruction.
21596 // Combine away the bottom node as its shuffle will be accumulated into
21597 // a preceding shuffle.
21598 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21600 // Record the old value.
21603 // Merge this node's mask and our incoming mask (adjusted to account for all
21604 // the pshufd instructions encountered).
21605 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21606 for (int &M : Mask)
21608 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21609 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21611 // Check that the shuffles didn't cancel each other out. If not, we need to
21612 // combine to the new one.
21614 // Replace the combinable shuffle with the combined one, updating all users
21615 // so that we re-evaluate the chain here.
21616 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21621 /// \brief Try to combine x86 target specific shuffles.
21622 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21623 TargetLowering::DAGCombinerInfo &DCI,
21624 const X86Subtarget *Subtarget) {
21626 MVT VT = N.getSimpleValueType();
21627 SmallVector<int, 4> Mask;
21629 switch (N.getOpcode()) {
21630 case X86ISD::PSHUFD:
21631 case X86ISD::PSHUFLW:
21632 case X86ISD::PSHUFHW:
21633 Mask = getPSHUFShuffleMask(N);
21634 assert(Mask.size() == 4);
21640 // Nuke no-op shuffles that show up after combining.
21641 if (isNoopShuffleMask(Mask))
21642 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21644 // Look for simplifications involving one or two shuffle instructions.
21645 SDValue V = N.getOperand(0);
21646 switch (N.getOpcode()) {
21649 case X86ISD::PSHUFLW:
21650 case X86ISD::PSHUFHW:
21651 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21653 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21654 return SDValue(); // We combined away this shuffle, so we're done.
21656 // See if this reduces to a PSHUFD which is no more expensive and can
21657 // combine with more operations. Note that it has to at least flip the
21658 // dwords as otherwise it would have been removed as a no-op.
21659 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21660 int DMask[] = {0, 1, 2, 3};
21661 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21662 DMask[DOffset + 0] = DOffset + 1;
21663 DMask[DOffset + 1] = DOffset + 0;
21664 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21665 V = DAG.getBitcast(DVT, V);
21666 DCI.AddToWorklist(V.getNode());
21667 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21668 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21669 DCI.AddToWorklist(V.getNode());
21670 return DAG.getBitcast(VT, V);
21673 // Look for shuffle patterns which can be implemented as a single unpack.
21674 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21675 // only works when we have a PSHUFD followed by two half-shuffles.
21676 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21677 (V.getOpcode() == X86ISD::PSHUFLW ||
21678 V.getOpcode() == X86ISD::PSHUFHW) &&
21679 V.getOpcode() != N.getOpcode() &&
21681 SDValue D = V.getOperand(0);
21682 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21683 D = D.getOperand(0);
21684 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21685 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21686 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21687 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21688 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21690 for (int i = 0; i < 4; ++i) {
21691 WordMask[i + NOffset] = Mask[i] + NOffset;
21692 WordMask[i + VOffset] = VMask[i] + VOffset;
21694 // Map the word mask through the DWord mask.
21696 for (int i = 0; i < 8; ++i)
21697 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21698 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21699 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21700 // We can replace all three shuffles with an unpack.
21701 V = DAG.getBitcast(VT, D.getOperand(0));
21702 DCI.AddToWorklist(V.getNode());
21703 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21712 case X86ISD::PSHUFD:
21713 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21722 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21724 /// We combine this directly on the abstract vector shuffle nodes so it is
21725 /// easier to generically match. We also insert dummy vector shuffle nodes for
21726 /// the operands which explicitly discard the lanes which are unused by this
21727 /// operation to try to flow through the rest of the combiner the fact that
21728 /// they're unused.
21729 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21731 EVT VT = N->getValueType(0);
21733 // We only handle target-independent shuffles.
21734 // FIXME: It would be easy and harmless to use the target shuffle mask
21735 // extraction tool to support more.
21736 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21739 auto *SVN = cast<ShuffleVectorSDNode>(N);
21740 ArrayRef<int> Mask = SVN->getMask();
21741 SDValue V1 = N->getOperand(0);
21742 SDValue V2 = N->getOperand(1);
21744 // We require the first shuffle operand to be the SUB node, and the second to
21745 // be the ADD node.
21746 // FIXME: We should support the commuted patterns.
21747 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21750 // If there are other uses of these operations we can't fold them.
21751 if (!V1->hasOneUse() || !V2->hasOneUse())
21754 // Ensure that both operations have the same operands. Note that we can
21755 // commute the FADD operands.
21756 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21757 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21758 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21761 // We're looking for blends between FADD and FSUB nodes. We insist on these
21762 // nodes being lined up in a specific expected pattern.
21763 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21764 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21765 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21768 // Only specific types are legal at this point, assert so we notice if and
21769 // when these change.
21770 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21771 VT == MVT::v4f64) &&
21772 "Unknown vector type encountered!");
21774 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21777 /// PerformShuffleCombine - Performs several different shuffle combines.
21778 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21779 TargetLowering::DAGCombinerInfo &DCI,
21780 const X86Subtarget *Subtarget) {
21782 SDValue N0 = N->getOperand(0);
21783 SDValue N1 = N->getOperand(1);
21784 EVT VT = N->getValueType(0);
21786 // Don't create instructions with illegal types after legalize types has run.
21787 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21788 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21791 // If we have legalized the vector types, look for blends of FADD and FSUB
21792 // nodes that we can fuse into an ADDSUB node.
21793 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21794 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21797 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21798 if (Subtarget->hasFp256() && VT.is256BitVector() &&
21799 N->getOpcode() == ISD::VECTOR_SHUFFLE)
21800 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21802 // During Type Legalization, when promoting illegal vector types,
21803 // the backend might introduce new shuffle dag nodes and bitcasts.
21805 // This code performs the following transformation:
21806 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21807 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21809 // We do this only if both the bitcast and the BINOP dag nodes have
21810 // one use. Also, perform this transformation only if the new binary
21811 // operation is legal. This is to avoid introducing dag nodes that
21812 // potentially need to be further expanded (or custom lowered) into a
21813 // less optimal sequence of dag nodes.
21814 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21815 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21816 N0.getOpcode() == ISD::BITCAST) {
21817 SDValue BC0 = N0.getOperand(0);
21818 EVT SVT = BC0.getValueType();
21819 unsigned Opcode = BC0.getOpcode();
21820 unsigned NumElts = VT.getVectorNumElements();
21822 if (BC0.hasOneUse() && SVT.isVector() &&
21823 SVT.getVectorNumElements() * 2 == NumElts &&
21824 TLI.isOperationLegal(Opcode, VT)) {
21825 bool CanFold = false;
21837 unsigned SVTNumElts = SVT.getVectorNumElements();
21838 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21839 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21840 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21841 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21842 CanFold = SVOp->getMaskElt(i) < 0;
21845 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21846 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21847 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21848 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21853 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21854 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21855 // consecutive, non-overlapping, and in the right order.
21856 SmallVector<SDValue, 16> Elts;
21857 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21858 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21860 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21863 if (isTargetShuffle(N->getOpcode())) {
21865 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21866 if (Shuffle.getNode())
21869 // Try recursively combining arbitrary sequences of x86 shuffle
21870 // instructions into higher-order shuffles. We do this after combining
21871 // specific PSHUF instruction sequences into their minimal form so that we
21872 // can evaluate how many specialized shuffle instructions are involved in
21873 // a particular chain.
21874 SmallVector<int, 1> NonceMask; // Just a placeholder.
21875 NonceMask.push_back(0);
21876 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21877 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21879 return SDValue(); // This routine will use CombineTo to replace N.
21885 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21886 /// specific shuffle of a load can be folded into a single element load.
21887 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21888 /// shuffles have been custom lowered so we need to handle those here.
21889 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21890 TargetLowering::DAGCombinerInfo &DCI) {
21891 if (DCI.isBeforeLegalizeOps())
21894 SDValue InVec = N->getOperand(0);
21895 SDValue EltNo = N->getOperand(1);
21897 if (!isa<ConstantSDNode>(EltNo))
21900 EVT OriginalVT = InVec.getValueType();
21902 if (InVec.getOpcode() == ISD::BITCAST) {
21903 // Don't duplicate a load with other uses.
21904 if (!InVec.hasOneUse())
21906 EVT BCVT = InVec.getOperand(0).getValueType();
21907 if (!BCVT.isVector() ||
21908 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21910 InVec = InVec.getOperand(0);
21913 EVT CurrentVT = InVec.getValueType();
21915 if (!isTargetShuffle(InVec.getOpcode()))
21918 // Don't duplicate a load with other uses.
21919 if (!InVec.hasOneUse())
21922 SmallVector<int, 16> ShuffleMask;
21924 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21925 ShuffleMask, UnaryShuffle))
21928 // Select the input vector, guarding against out of range extract vector.
21929 unsigned NumElems = CurrentVT.getVectorNumElements();
21930 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21931 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21932 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21933 : InVec.getOperand(1);
21935 // If inputs to shuffle are the same for both ops, then allow 2 uses
21936 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21937 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21939 if (LdNode.getOpcode() == ISD::BITCAST) {
21940 // Don't duplicate a load with other uses.
21941 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21944 AllowedUses = 1; // only allow 1 load use if we have a bitcast
21945 LdNode = LdNode.getOperand(0);
21948 if (!ISD::isNormalLoad(LdNode.getNode()))
21951 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21953 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21956 EVT EltVT = N->getValueType(0);
21957 // If there's a bitcast before the shuffle, check if the load type and
21958 // alignment is valid.
21959 unsigned Align = LN0->getAlignment();
21960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21961 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21962 EltVT.getTypeForEVT(*DAG.getContext()));
21964 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21967 // All checks match so transform back to vector_shuffle so that DAG combiner
21968 // can finish the job
21971 // Create shuffle node taking into account the case that its a unary shuffle
21972 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21973 : InVec.getOperand(1);
21974 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21975 InVec.getOperand(0), Shuffle,
21977 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21978 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21982 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21983 /// special and don't usually play with other vector types, it's better to
21984 /// handle them early to be sure we emit efficient code by avoiding
21985 /// store-load conversions.
21986 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21987 if (N->getValueType(0) != MVT::x86mmx ||
21988 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21989 N->getOperand(0)->getValueType(0) != MVT::v2i32)
21992 SDValue V = N->getOperand(0);
21993 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21994 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21995 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21996 N->getValueType(0), V.getOperand(0));
22001 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22002 /// generation and convert it from being a bunch of shuffles and extracts
22003 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22004 /// storing the value and loading scalars back, while for x64 we should
22005 /// use 64-bit extracts and shifts.
22006 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22007 TargetLowering::DAGCombinerInfo &DCI) {
22008 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22011 SDValue InputVector = N->getOperand(0);
22012 SDLoc dl(InputVector);
22013 // Detect mmx to i32 conversion through a v2i32 elt extract.
22014 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22015 N->getValueType(0) == MVT::i32 &&
22016 InputVector.getValueType() == MVT::v2i32) {
22018 // The bitcast source is a direct mmx result.
22019 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22020 if (MMXSrc.getValueType() == MVT::x86mmx)
22021 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22022 N->getValueType(0),
22023 InputVector.getNode()->getOperand(0));
22025 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22026 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22027 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22028 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22029 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22030 MMXSrcOp.getValueType() == MVT::v1i64 &&
22031 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22032 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22033 N->getValueType(0),
22034 MMXSrcOp.getOperand(0));
22037 EVT VT = N->getValueType(0);
22039 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22040 InputVector.getOpcode() == ISD::BITCAST &&
22041 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22042 uint64_t ExtractedElt =
22043 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22044 uint64_t InputValue =
22045 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22046 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22047 return DAG.getConstant(Res, dl, MVT::i1);
22049 // Only operate on vectors of 4 elements, where the alternative shuffling
22050 // gets to be more expensive.
22051 if (InputVector.getValueType() != MVT::v4i32)
22054 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22055 // single use which is a sign-extend or zero-extend, and all elements are
22057 SmallVector<SDNode *, 4> Uses;
22058 unsigned ExtractedElements = 0;
22059 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22060 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22061 if (UI.getUse().getResNo() != InputVector.getResNo())
22064 SDNode *Extract = *UI;
22065 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22068 if (Extract->getValueType(0) != MVT::i32)
22070 if (!Extract->hasOneUse())
22072 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22073 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22075 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22078 // Record which element was extracted.
22079 ExtractedElements |=
22080 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22082 Uses.push_back(Extract);
22085 // If not all the elements were used, this may not be worthwhile.
22086 if (ExtractedElements != 15)
22089 // Ok, we've now decided to do the transformation.
22090 // If 64-bit shifts are legal, use the extract-shift sequence,
22091 // otherwise bounce the vector off the cache.
22092 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22095 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22096 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22097 auto &DL = DAG.getDataLayout();
22098 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22099 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22100 DAG.getConstant(0, dl, VecIdxTy));
22101 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22102 DAG.getConstant(1, dl, VecIdxTy));
22104 SDValue ShAmt = DAG.getConstant(
22105 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22106 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22107 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22108 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22109 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22110 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22111 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22113 // Store the value to a temporary stack slot.
22114 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22115 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22116 MachinePointerInfo(), false, false, 0);
22118 EVT ElementType = InputVector.getValueType().getVectorElementType();
22119 unsigned EltSize = ElementType.getSizeInBits() / 8;
22121 // Replace each use (extract) with a load of the appropriate element.
22122 for (unsigned i = 0; i < 4; ++i) {
22123 uint64_t Offset = EltSize * i;
22124 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22125 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22127 SDValue ScalarAddr =
22128 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22130 // Load the scalar.
22131 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22132 ScalarAddr, MachinePointerInfo(),
22133 false, false, false, 0);
22138 // Replace the extracts
22139 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22140 UE = Uses.end(); UI != UE; ++UI) {
22141 SDNode *Extract = *UI;
22143 SDValue Idx = Extract->getOperand(1);
22144 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22145 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22148 // The replacement was made in place; don't return anything.
22152 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22153 static std::pair<unsigned, bool>
22154 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22155 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22156 if (!VT.isVector())
22157 return std::make_pair(0, false);
22159 bool NeedSplit = false;
22160 switch (VT.getSimpleVT().SimpleTy) {
22161 default: return std::make_pair(0, false);
22164 if (!Subtarget->hasVLX())
22165 return std::make_pair(0, false);
22169 if (!Subtarget->hasBWI())
22170 return std::make_pair(0, false);
22174 if (!Subtarget->hasAVX512())
22175 return std::make_pair(0, false);
22180 if (!Subtarget->hasAVX2())
22182 if (!Subtarget->hasAVX())
22183 return std::make_pair(0, false);
22188 if (!Subtarget->hasSSE2())
22189 return std::make_pair(0, false);
22192 // SSE2 has only a small subset of the operations.
22193 bool hasUnsigned = Subtarget->hasSSE41() ||
22194 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22195 bool hasSigned = Subtarget->hasSSE41() ||
22196 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22198 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22201 // Check for x CC y ? x : y.
22202 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22203 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22208 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22211 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22214 Opc = hasSigned ? ISD::SMIN : 0; break;
22217 Opc = hasSigned ? ISD::SMAX : 0; break;
22219 // Check for x CC y ? y : x -- a min/max with reversed arms.
22220 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22221 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22226 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22229 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22232 Opc = hasSigned ? ISD::SMAX : 0; break;
22235 Opc = hasSigned ? ISD::SMIN : 0; break;
22239 return std::make_pair(Opc, NeedSplit);
22243 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22244 const X86Subtarget *Subtarget) {
22246 SDValue Cond = N->getOperand(0);
22247 SDValue LHS = N->getOperand(1);
22248 SDValue RHS = N->getOperand(2);
22250 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22251 SDValue CondSrc = Cond->getOperand(0);
22252 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22253 Cond = CondSrc->getOperand(0);
22256 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22259 // A vselect where all conditions and data are constants can be optimized into
22260 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22261 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22262 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22265 unsigned MaskValue = 0;
22266 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22269 MVT VT = N->getSimpleValueType(0);
22270 unsigned NumElems = VT.getVectorNumElements();
22271 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22272 for (unsigned i = 0; i < NumElems; ++i) {
22273 // Be sure we emit undef where we can.
22274 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22275 ShuffleMask[i] = -1;
22277 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22281 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22283 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22286 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22288 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22289 TargetLowering::DAGCombinerInfo &DCI,
22290 const X86Subtarget *Subtarget) {
22292 SDValue Cond = N->getOperand(0);
22293 // Get the LHS/RHS of the select.
22294 SDValue LHS = N->getOperand(1);
22295 SDValue RHS = N->getOperand(2);
22296 EVT VT = LHS.getValueType();
22297 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22299 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22300 // instructions match the semantics of the common C idiom x<y?x:y but not
22301 // x<=y?x:y, because of how they handle negative zero (which can be
22302 // ignored in unsafe-math mode).
22303 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22304 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22305 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22306 (Subtarget->hasSSE2() ||
22307 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22308 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22310 unsigned Opcode = 0;
22311 // Check for x CC y ? x : y.
22312 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22313 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22317 // Converting this to a min would handle NaNs incorrectly, and swapping
22318 // the operands would cause it to handle comparisons between positive
22319 // and negative zero incorrectly.
22320 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22321 if (!DAG.getTarget().Options.UnsafeFPMath &&
22322 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22324 std::swap(LHS, RHS);
22326 Opcode = X86ISD::FMIN;
22329 // Converting this to a min would handle comparisons between positive
22330 // and negative zero incorrectly.
22331 if (!DAG.getTarget().Options.UnsafeFPMath &&
22332 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22334 Opcode = X86ISD::FMIN;
22337 // Converting this to a min would handle both negative zeros and NaNs
22338 // incorrectly, but we can swap the operands to fix both.
22339 std::swap(LHS, RHS);
22343 Opcode = X86ISD::FMIN;
22347 // Converting this to a max would handle comparisons between positive
22348 // and negative zero incorrectly.
22349 if (!DAG.getTarget().Options.UnsafeFPMath &&
22350 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22352 Opcode = X86ISD::FMAX;
22355 // Converting this to a max would handle NaNs incorrectly, and swapping
22356 // the operands would cause it to handle comparisons between positive
22357 // and negative zero incorrectly.
22358 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22359 if (!DAG.getTarget().Options.UnsafeFPMath &&
22360 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22362 std::swap(LHS, RHS);
22364 Opcode = X86ISD::FMAX;
22367 // Converting this to a max would handle both negative zeros and NaNs
22368 // incorrectly, but we can swap the operands to fix both.
22369 std::swap(LHS, RHS);
22373 Opcode = X86ISD::FMAX;
22376 // Check for x CC y ? y : x -- a min/max with reversed arms.
22377 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22378 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22382 // Converting this to a min would handle comparisons between positive
22383 // and negative zero incorrectly, and swapping the operands would
22384 // cause it to handle NaNs incorrectly.
22385 if (!DAG.getTarget().Options.UnsafeFPMath &&
22386 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22387 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22389 std::swap(LHS, RHS);
22391 Opcode = X86ISD::FMIN;
22394 // Converting this to a min would handle NaNs incorrectly.
22395 if (!DAG.getTarget().Options.UnsafeFPMath &&
22396 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22398 Opcode = X86ISD::FMIN;
22401 // Converting this to a min would handle both negative zeros and NaNs
22402 // incorrectly, but we can swap the operands to fix both.
22403 std::swap(LHS, RHS);
22407 Opcode = X86ISD::FMIN;
22411 // Converting this to a max would handle NaNs incorrectly.
22412 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22414 Opcode = X86ISD::FMAX;
22417 // Converting this to a max would handle comparisons between positive
22418 // and negative zero incorrectly, and swapping the operands would
22419 // cause it to handle NaNs incorrectly.
22420 if (!DAG.getTarget().Options.UnsafeFPMath &&
22421 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22422 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22424 std::swap(LHS, RHS);
22426 Opcode = X86ISD::FMAX;
22429 // Converting this to a max would handle both negative zeros and NaNs
22430 // incorrectly, but we can swap the operands to fix both.
22431 std::swap(LHS, RHS);
22435 Opcode = X86ISD::FMAX;
22441 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22444 EVT CondVT = Cond.getValueType();
22445 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22446 CondVT.getVectorElementType() == MVT::i1) {
22447 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22448 // lowering on KNL. In this case we convert it to
22449 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22450 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22451 // Since SKX these selects have a proper lowering.
22452 EVT OpVT = LHS.getValueType();
22453 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22454 (OpVT.getVectorElementType() == MVT::i8 ||
22455 OpVT.getVectorElementType() == MVT::i16) &&
22456 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22457 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22458 DCI.AddToWorklist(Cond.getNode());
22459 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22462 // If this is a select between two integer constants, try to do some
22464 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22465 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22466 // Don't do this for crazy integer types.
22467 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22468 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22469 // so that TrueC (the true value) is larger than FalseC.
22470 bool NeedsCondInvert = false;
22472 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22473 // Efficiently invertible.
22474 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22475 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22476 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22477 NeedsCondInvert = true;
22478 std::swap(TrueC, FalseC);
22481 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22482 if (FalseC->getAPIntValue() == 0 &&
22483 TrueC->getAPIntValue().isPowerOf2()) {
22484 if (NeedsCondInvert) // Invert the condition if needed.
22485 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22486 DAG.getConstant(1, DL, Cond.getValueType()));
22488 // Zero extend the condition if needed.
22489 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22491 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22492 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22493 DAG.getConstant(ShAmt, DL, MVT::i8));
22496 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22497 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22498 if (NeedsCondInvert) // Invert the condition if needed.
22499 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22500 DAG.getConstant(1, DL, Cond.getValueType()));
22502 // Zero extend the condition if needed.
22503 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22504 FalseC->getValueType(0), Cond);
22505 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22506 SDValue(FalseC, 0));
22509 // Optimize cases that will turn into an LEA instruction. This requires
22510 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22511 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22512 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22513 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22515 bool isFastMultiplier = false;
22517 switch ((unsigned char)Diff) {
22519 case 1: // result = add base, cond
22520 case 2: // result = lea base( , cond*2)
22521 case 3: // result = lea base(cond, cond*2)
22522 case 4: // result = lea base( , cond*4)
22523 case 5: // result = lea base(cond, cond*4)
22524 case 8: // result = lea base( , cond*8)
22525 case 9: // result = lea base(cond, cond*8)
22526 isFastMultiplier = true;
22531 if (isFastMultiplier) {
22532 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22533 if (NeedsCondInvert) // Invert the condition if needed.
22534 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22535 DAG.getConstant(1, DL, Cond.getValueType()));
22537 // Zero extend the condition if needed.
22538 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22540 // Scale the condition by the difference.
22542 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22543 DAG.getConstant(Diff, DL,
22544 Cond.getValueType()));
22546 // Add the base if non-zero.
22547 if (FalseC->getAPIntValue() != 0)
22548 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22549 SDValue(FalseC, 0));
22556 // Canonicalize max and min:
22557 // (x > y) ? x : y -> (x >= y) ? x : y
22558 // (x < y) ? x : y -> (x <= y) ? x : y
22559 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22560 // the need for an extra compare
22561 // against zero. e.g.
22562 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22564 // testl %edi, %edi
22566 // cmovgl %edi, %eax
22570 // cmovsl %eax, %edi
22571 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22572 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22573 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22574 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22579 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22580 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22581 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22582 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22587 // Early exit check
22588 if (!TLI.isTypeLegal(VT))
22591 // Match VSELECTs into subs with unsigned saturation.
22592 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22593 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22594 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22595 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22596 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22598 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22599 // left side invert the predicate to simplify logic below.
22601 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22603 CC = ISD::getSetCCInverse(CC, true);
22604 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22608 if (Other.getNode() && Other->getNumOperands() == 2 &&
22609 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22610 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22611 SDValue CondRHS = Cond->getOperand(1);
22613 // Look for a general sub with unsigned saturation first.
22614 // x >= y ? x-y : 0 --> subus x, y
22615 // x > y ? x-y : 0 --> subus x, y
22616 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22617 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22618 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22620 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22621 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22622 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22623 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22624 // If the RHS is a constant we have to reverse the const
22625 // canonicalization.
22626 // x > C-1 ? x+-C : 0 --> subus x, C
22627 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22628 CondRHSConst->getAPIntValue() ==
22629 (-OpRHSConst->getAPIntValue() - 1))
22630 return DAG.getNode(
22631 X86ISD::SUBUS, DL, VT, OpLHS,
22632 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22634 // Another special case: If C was a sign bit, the sub has been
22635 // canonicalized into a xor.
22636 // FIXME: Would it be better to use computeKnownBits to determine
22637 // whether it's safe to decanonicalize the xor?
22638 // x s< 0 ? x^C : 0 --> subus x, C
22639 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22640 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22641 OpRHSConst->getAPIntValue().isSignBit())
22642 // Note that we have to rebuild the RHS constant here to ensure we
22643 // don't rely on particular values of undef lanes.
22644 return DAG.getNode(
22645 X86ISD::SUBUS, DL, VT, OpLHS,
22646 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22651 // Try to match a min/max vector operation.
22652 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22653 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22654 unsigned Opc = ret.first;
22655 bool NeedSplit = ret.second;
22657 if (Opc && NeedSplit) {
22658 unsigned NumElems = VT.getVectorNumElements();
22659 // Extract the LHS vectors
22660 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22661 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22663 // Extract the RHS vectors
22664 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22665 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22667 // Create min/max for each subvector
22668 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22669 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22671 // Merge the result
22672 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22674 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22677 // Simplify vector selection if condition value type matches vselect
22679 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22680 assert(Cond.getValueType().isVector() &&
22681 "vector select expects a vector selector!");
22683 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22684 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22686 // Try invert the condition if true value is not all 1s and false value
22688 if (!TValIsAllOnes && !FValIsAllZeros &&
22689 // Check if the selector will be produced by CMPP*/PCMP*
22690 Cond.getOpcode() == ISD::SETCC &&
22691 // Check if SETCC has already been promoted
22692 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22694 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22695 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22697 if (TValIsAllZeros || FValIsAllOnes) {
22698 SDValue CC = Cond.getOperand(2);
22699 ISD::CondCode NewCC =
22700 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22701 Cond.getOperand(0).getValueType().isInteger());
22702 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22703 std::swap(LHS, RHS);
22704 TValIsAllOnes = FValIsAllOnes;
22705 FValIsAllZeros = TValIsAllZeros;
22709 if (TValIsAllOnes || FValIsAllZeros) {
22712 if (TValIsAllOnes && FValIsAllZeros)
22714 else if (TValIsAllOnes)
22716 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22717 else if (FValIsAllZeros)
22718 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22719 DAG.getBitcast(CondVT, LHS));
22721 return DAG.getBitcast(VT, Ret);
22725 // We should generate an X86ISD::BLENDI from a vselect if its argument
22726 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22727 // constants. This specific pattern gets generated when we split a
22728 // selector for a 512 bit vector in a machine without AVX512 (but with
22729 // 256-bit vectors), during legalization:
22731 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22733 // Iff we find this pattern and the build_vectors are built from
22734 // constants, we translate the vselect into a shuffle_vector that we
22735 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22736 if ((N->getOpcode() == ISD::VSELECT ||
22737 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22738 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22739 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22740 if (Shuffle.getNode())
22744 // If this is a *dynamic* select (non-constant condition) and we can match
22745 // this node with one of the variable blend instructions, restructure the
22746 // condition so that the blends can use the high bit of each element and use
22747 // SimplifyDemandedBits to simplify the condition operand.
22748 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22749 !DCI.isBeforeLegalize() &&
22750 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22751 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22753 // Don't optimize vector selects that map to mask-registers.
22757 // We can only handle the cases where VSELECT is directly legal on the
22758 // subtarget. We custom lower VSELECT nodes with constant conditions and
22759 // this makes it hard to see whether a dynamic VSELECT will correctly
22760 // lower, so we both check the operation's status and explicitly handle the
22761 // cases where a *dynamic* blend will fail even though a constant-condition
22762 // blend could be custom lowered.
22763 // FIXME: We should find a better way to handle this class of problems.
22764 // Potentially, we should combine constant-condition vselect nodes
22765 // pre-legalization into shuffles and not mark as many types as custom
22767 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22769 // FIXME: We don't support i16-element blends currently. We could and
22770 // should support them by making *all* the bits in the condition be set
22771 // rather than just the high bit and using an i8-element blend.
22772 if (VT.getScalarType() == MVT::i16)
22774 // Dynamic blending was only available from SSE4.1 onward.
22775 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22777 // Byte blends are only available in AVX2
22778 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22779 !Subtarget->hasAVX2())
22782 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22783 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22785 APInt KnownZero, KnownOne;
22786 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22787 DCI.isBeforeLegalizeOps());
22788 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22789 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22791 // If we changed the computation somewhere in the DAG, this change
22792 // will affect all users of Cond.
22793 // Make sure it is fine and update all the nodes so that we do not
22794 // use the generic VSELECT anymore. Otherwise, we may perform
22795 // wrong optimizations as we messed up with the actual expectation
22796 // for the vector boolean values.
22797 if (Cond != TLO.Old) {
22798 // Check all uses of that condition operand to check whether it will be
22799 // consumed by non-BLEND instructions, which may depend on all bits are
22801 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22803 if (I->getOpcode() != ISD::VSELECT)
22804 // TODO: Add other opcodes eventually lowered into BLEND.
22807 // Update all the users of the condition, before committing the change,
22808 // so that the VSELECT optimizations that expect the correct vector
22809 // boolean value will not be triggered.
22810 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22812 DAG.ReplaceAllUsesOfValueWith(
22814 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22815 Cond, I->getOperand(1), I->getOperand(2)));
22816 DCI.CommitTargetLoweringOpt(TLO);
22819 // At this point, only Cond is changed. Change the condition
22820 // just for N to keep the opportunity to optimize all other
22821 // users their own way.
22822 DAG.ReplaceAllUsesOfValueWith(
22824 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22825 TLO.New, N->getOperand(1), N->getOperand(2)));
22833 // Check whether a boolean test is testing a boolean value generated by
22834 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22837 // Simplify the following patterns:
22838 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22839 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22840 // to (Op EFLAGS Cond)
22842 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22843 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22844 // to (Op EFLAGS !Cond)
22846 // where Op could be BRCOND or CMOV.
22848 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22849 // Quit if not CMP and SUB with its value result used.
22850 if (Cmp.getOpcode() != X86ISD::CMP &&
22851 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22854 // Quit if not used as a boolean value.
22855 if (CC != X86::COND_E && CC != X86::COND_NE)
22858 // Check CMP operands. One of them should be 0 or 1 and the other should be
22859 // an SetCC or extended from it.
22860 SDValue Op1 = Cmp.getOperand(0);
22861 SDValue Op2 = Cmp.getOperand(1);
22864 const ConstantSDNode* C = nullptr;
22865 bool needOppositeCond = (CC == X86::COND_E);
22866 bool checkAgainstTrue = false; // Is it a comparison against 1?
22868 if ((C = dyn_cast<ConstantSDNode>(Op1)))
22870 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22872 else // Quit if all operands are not constants.
22875 if (C->getZExtValue() == 1) {
22876 needOppositeCond = !needOppositeCond;
22877 checkAgainstTrue = true;
22878 } else if (C->getZExtValue() != 0)
22879 // Quit if the constant is neither 0 or 1.
22882 bool truncatedToBoolWithAnd = false;
22883 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22884 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22885 SetCC.getOpcode() == ISD::TRUNCATE ||
22886 SetCC.getOpcode() == ISD::AND) {
22887 if (SetCC.getOpcode() == ISD::AND) {
22889 ConstantSDNode *CS;
22890 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22891 CS->getZExtValue() == 1)
22893 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22894 CS->getZExtValue() == 1)
22898 SetCC = SetCC.getOperand(OpIdx);
22899 truncatedToBoolWithAnd = true;
22901 SetCC = SetCC.getOperand(0);
22904 switch (SetCC.getOpcode()) {
22905 case X86ISD::SETCC_CARRY:
22906 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22907 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22908 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22909 // truncated to i1 using 'and'.
22910 if (checkAgainstTrue && !truncatedToBoolWithAnd)
22912 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22913 "Invalid use of SETCC_CARRY!");
22915 case X86ISD::SETCC:
22916 // Set the condition code or opposite one if necessary.
22917 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22918 if (needOppositeCond)
22919 CC = X86::GetOppositeBranchCondition(CC);
22920 return SetCC.getOperand(1);
22921 case X86ISD::CMOV: {
22922 // Check whether false/true value has canonical one, i.e. 0 or 1.
22923 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22924 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22925 // Quit if true value is not a constant.
22928 // Quit if false value is not a constant.
22930 SDValue Op = SetCC.getOperand(0);
22931 // Skip 'zext' or 'trunc' node.
22932 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22933 Op.getOpcode() == ISD::TRUNCATE)
22934 Op = Op.getOperand(0);
22935 // A special case for rdrand/rdseed, where 0 is set if false cond is
22937 if ((Op.getOpcode() != X86ISD::RDRAND &&
22938 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22941 // Quit if false value is not the constant 0 or 1.
22942 bool FValIsFalse = true;
22943 if (FVal && FVal->getZExtValue() != 0) {
22944 if (FVal->getZExtValue() != 1)
22946 // If FVal is 1, opposite cond is needed.
22947 needOppositeCond = !needOppositeCond;
22948 FValIsFalse = false;
22950 // Quit if TVal is not the constant opposite of FVal.
22951 if (FValIsFalse && TVal->getZExtValue() != 1)
22953 if (!FValIsFalse && TVal->getZExtValue() != 0)
22955 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22956 if (needOppositeCond)
22957 CC = X86::GetOppositeBranchCondition(CC);
22958 return SetCC.getOperand(3);
22965 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22967 /// (X86or (X86setcc) (X86setcc))
22968 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
22969 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22970 X86::CondCode &CC1, SDValue &Flags,
22972 if (Cond->getOpcode() == X86ISD::CMP) {
22973 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22974 if (!CondOp1C || !CondOp1C->isNullValue())
22977 Cond = Cond->getOperand(0);
22982 SDValue SetCC0, SetCC1;
22983 switch (Cond->getOpcode()) {
22984 default: return false;
22991 SetCC0 = Cond->getOperand(0);
22992 SetCC1 = Cond->getOperand(1);
22996 // Make sure we have SETCC nodes, using the same flags value.
22997 if (SetCC0.getOpcode() != X86ISD::SETCC ||
22998 SetCC1.getOpcode() != X86ISD::SETCC ||
22999 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23002 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23003 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23004 Flags = SetCC0->getOperand(1);
23008 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23009 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23010 TargetLowering::DAGCombinerInfo &DCI,
23011 const X86Subtarget *Subtarget) {
23014 // If the flag operand isn't dead, don't touch this CMOV.
23015 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23018 SDValue FalseOp = N->getOperand(0);
23019 SDValue TrueOp = N->getOperand(1);
23020 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23021 SDValue Cond = N->getOperand(3);
23023 if (CC == X86::COND_E || CC == X86::COND_NE) {
23024 switch (Cond.getOpcode()) {
23028 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23029 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23030 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23036 Flags = checkBoolTestSetCCCombine(Cond, CC);
23037 if (Flags.getNode() &&
23038 // Extra check as FCMOV only supports a subset of X86 cond.
23039 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23040 SDValue Ops[] = { FalseOp, TrueOp,
23041 DAG.getConstant(CC, DL, MVT::i8), Flags };
23042 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23045 // If this is a select between two integer constants, try to do some
23046 // optimizations. Note that the operands are ordered the opposite of SELECT
23048 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23049 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23050 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23051 // larger than FalseC (the false value).
23052 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23053 CC = X86::GetOppositeBranchCondition(CC);
23054 std::swap(TrueC, FalseC);
23055 std::swap(TrueOp, FalseOp);
23058 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23059 // This is efficient for any integer data type (including i8/i16) and
23061 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23062 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23063 DAG.getConstant(CC, DL, MVT::i8), Cond);
23065 // Zero extend the condition if needed.
23066 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23068 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23069 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23070 DAG.getConstant(ShAmt, DL, MVT::i8));
23071 if (N->getNumValues() == 2) // Dead flag value?
23072 return DCI.CombineTo(N, Cond, SDValue());
23076 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23077 // for any integer data type, including i8/i16.
23078 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23079 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23080 DAG.getConstant(CC, DL, MVT::i8), Cond);
23082 // Zero extend the condition if needed.
23083 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23084 FalseC->getValueType(0), Cond);
23085 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23086 SDValue(FalseC, 0));
23088 if (N->getNumValues() == 2) // Dead flag value?
23089 return DCI.CombineTo(N, Cond, SDValue());
23093 // Optimize cases that will turn into an LEA instruction. This requires
23094 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23095 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23096 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23097 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23099 bool isFastMultiplier = false;
23101 switch ((unsigned char)Diff) {
23103 case 1: // result = add base, cond
23104 case 2: // result = lea base( , cond*2)
23105 case 3: // result = lea base(cond, cond*2)
23106 case 4: // result = lea base( , cond*4)
23107 case 5: // result = lea base(cond, cond*4)
23108 case 8: // result = lea base( , cond*8)
23109 case 9: // result = lea base(cond, cond*8)
23110 isFastMultiplier = true;
23115 if (isFastMultiplier) {
23116 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23117 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23118 DAG.getConstant(CC, DL, MVT::i8), Cond);
23119 // Zero extend the condition if needed.
23120 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23122 // Scale the condition by the difference.
23124 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23125 DAG.getConstant(Diff, DL, Cond.getValueType()));
23127 // Add the base if non-zero.
23128 if (FalseC->getAPIntValue() != 0)
23129 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23130 SDValue(FalseC, 0));
23131 if (N->getNumValues() == 2) // Dead flag value?
23132 return DCI.CombineTo(N, Cond, SDValue());
23139 // Handle these cases:
23140 // (select (x != c), e, c) -> select (x != c), e, x),
23141 // (select (x == c), c, e) -> select (x == c), x, e)
23142 // where the c is an integer constant, and the "select" is the combination
23143 // of CMOV and CMP.
23145 // The rationale for this change is that the conditional-move from a constant
23146 // needs two instructions, however, conditional-move from a register needs
23147 // only one instruction.
23149 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23150 // some instruction-combining opportunities. This opt needs to be
23151 // postponed as late as possible.
23153 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23154 // the DCI.xxxx conditions are provided to postpone the optimization as
23155 // late as possible.
23157 ConstantSDNode *CmpAgainst = nullptr;
23158 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23159 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23160 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23162 if (CC == X86::COND_NE &&
23163 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23164 CC = X86::GetOppositeBranchCondition(CC);
23165 std::swap(TrueOp, FalseOp);
23168 if (CC == X86::COND_E &&
23169 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23170 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23171 DAG.getConstant(CC, DL, MVT::i8), Cond };
23172 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23177 // Fold and/or of setcc's to double CMOV:
23178 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23179 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23181 // This combine lets us generate:
23182 // cmovcc1 (jcc1 if we don't have CMOV)
23188 // cmovne (jne if we don't have CMOV)
23189 // When we can't use the CMOV instruction, it might increase branch
23191 // When we can use CMOV, or when there is no mispredict, this improves
23192 // throughput and reduces register pressure.
23194 if (CC == X86::COND_NE) {
23196 X86::CondCode CC0, CC1;
23198 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23200 std::swap(FalseOp, TrueOp);
23201 CC0 = X86::GetOppositeBranchCondition(CC0);
23202 CC1 = X86::GetOppositeBranchCondition(CC1);
23205 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23207 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23208 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23209 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23210 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23218 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23219 const X86Subtarget *Subtarget) {
23220 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23222 default: return SDValue();
23223 // SSE/AVX/AVX2 blend intrinsics.
23224 case Intrinsic::x86_avx2_pblendvb:
23225 // Don't try to simplify this intrinsic if we don't have AVX2.
23226 if (!Subtarget->hasAVX2())
23229 case Intrinsic::x86_avx_blendv_pd_256:
23230 case Intrinsic::x86_avx_blendv_ps_256:
23231 // Don't try to simplify this intrinsic if we don't have AVX.
23232 if (!Subtarget->hasAVX())
23235 case Intrinsic::x86_sse41_blendvps:
23236 case Intrinsic::x86_sse41_blendvpd:
23237 case Intrinsic::x86_sse41_pblendvb: {
23238 SDValue Op0 = N->getOperand(1);
23239 SDValue Op1 = N->getOperand(2);
23240 SDValue Mask = N->getOperand(3);
23242 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23243 if (!Subtarget->hasSSE41())
23246 // fold (blend A, A, Mask) -> A
23249 // fold (blend A, B, allZeros) -> A
23250 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23252 // fold (blend A, B, allOnes) -> B
23253 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23256 // Simplify the case where the mask is a constant i32 value.
23257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23258 if (C->isNullValue())
23260 if (C->isAllOnesValue())
23267 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23268 case Intrinsic::x86_sse2_psrai_w:
23269 case Intrinsic::x86_sse2_psrai_d:
23270 case Intrinsic::x86_avx2_psrai_w:
23271 case Intrinsic::x86_avx2_psrai_d:
23272 case Intrinsic::x86_sse2_psra_w:
23273 case Intrinsic::x86_sse2_psra_d:
23274 case Intrinsic::x86_avx2_psra_w:
23275 case Intrinsic::x86_avx2_psra_d: {
23276 SDValue Op0 = N->getOperand(1);
23277 SDValue Op1 = N->getOperand(2);
23278 EVT VT = Op0.getValueType();
23279 assert(VT.isVector() && "Expected a vector type!");
23281 if (isa<BuildVectorSDNode>(Op1))
23282 Op1 = Op1.getOperand(0);
23284 if (!isa<ConstantSDNode>(Op1))
23287 EVT SVT = VT.getVectorElementType();
23288 unsigned SVTBits = SVT.getSizeInBits();
23290 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23291 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23292 uint64_t ShAmt = C.getZExtValue();
23294 // Don't try to convert this shift into a ISD::SRA if the shift
23295 // count is bigger than or equal to the element size.
23296 if (ShAmt >= SVTBits)
23299 // Trivial case: if the shift count is zero, then fold this
23300 // into the first operand.
23304 // Replace this packed shift intrinsic with a target independent
23307 SDValue Splat = DAG.getConstant(C, DL, VT);
23308 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23313 /// PerformMulCombine - Optimize a single multiply with constant into two
23314 /// in order to implement it with two cheaper instructions, e.g.
23315 /// LEA + SHL, LEA + LEA.
23316 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23317 TargetLowering::DAGCombinerInfo &DCI) {
23318 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23321 EVT VT = N->getValueType(0);
23322 if (VT != MVT::i64 && VT != MVT::i32)
23325 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23328 uint64_t MulAmt = C->getZExtValue();
23329 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23332 uint64_t MulAmt1 = 0;
23333 uint64_t MulAmt2 = 0;
23334 if ((MulAmt % 9) == 0) {
23336 MulAmt2 = MulAmt / 9;
23337 } else if ((MulAmt % 5) == 0) {
23339 MulAmt2 = MulAmt / 5;
23340 } else if ((MulAmt % 3) == 0) {
23342 MulAmt2 = MulAmt / 3;
23345 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23348 if (isPowerOf2_64(MulAmt2) &&
23349 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23350 // If second multiplifer is pow2, issue it first. We want the multiply by
23351 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23353 std::swap(MulAmt1, MulAmt2);
23356 if (isPowerOf2_64(MulAmt1))
23357 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23358 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23360 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23361 DAG.getConstant(MulAmt1, DL, VT));
23363 if (isPowerOf2_64(MulAmt2))
23364 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23365 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23367 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23368 DAG.getConstant(MulAmt2, DL, VT));
23370 // Do not add new nodes to DAG combiner worklist.
23371 DCI.CombineTo(N, NewMul, false);
23376 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23377 SDValue N0 = N->getOperand(0);
23378 SDValue N1 = N->getOperand(1);
23379 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23380 EVT VT = N0.getValueType();
23382 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23383 // since the result of setcc_c is all zero's or all ones.
23384 if (VT.isInteger() && !VT.isVector() &&
23385 N1C && N0.getOpcode() == ISD::AND &&
23386 N0.getOperand(1).getOpcode() == ISD::Constant) {
23387 SDValue N00 = N0.getOperand(0);
23388 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23389 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23390 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23391 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23392 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23393 APInt ShAmt = N1C->getAPIntValue();
23394 Mask = Mask.shl(ShAmt);
23397 return DAG.getNode(ISD::AND, DL, VT,
23398 N00, DAG.getConstant(Mask, DL, VT));
23403 // Hardware support for vector shifts is sparse which makes us scalarize the
23404 // vector operations in many cases. Also, on sandybridge ADD is faster than
23406 // (shl V, 1) -> add V,V
23407 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23408 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23409 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23410 // We shift all of the values by one. In many cases we do not have
23411 // hardware support for this operation. This is better expressed as an ADD
23413 if (N1SplatC->getAPIntValue() == 1)
23414 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23420 /// \brief Returns a vector of 0s if the node in input is a vector logical
23421 /// shift by a constant amount which is known to be bigger than or equal
23422 /// to the vector element size in bits.
23423 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23424 const X86Subtarget *Subtarget) {
23425 EVT VT = N->getValueType(0);
23427 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23428 (!Subtarget->hasInt256() ||
23429 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23432 SDValue Amt = N->getOperand(1);
23434 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23435 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23436 APInt ShiftAmt = AmtSplat->getAPIntValue();
23437 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23439 // SSE2/AVX2 logical shifts always return a vector of 0s
23440 // if the shift amount is bigger than or equal to
23441 // the element size. The constant shift amount will be
23442 // encoded as a 8-bit immediate.
23443 if (ShiftAmt.trunc(8).uge(MaxAmount))
23444 return getZeroVector(VT, Subtarget, DAG, DL);
23450 /// PerformShiftCombine - Combine shifts.
23451 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23452 TargetLowering::DAGCombinerInfo &DCI,
23453 const X86Subtarget *Subtarget) {
23454 if (N->getOpcode() == ISD::SHL)
23455 if (SDValue V = PerformSHLCombine(N, DAG))
23458 // Try to fold this logical shift into a zero vector.
23459 if (N->getOpcode() != ISD::SRA)
23460 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23466 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23467 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23468 // and friends. Likewise for OR -> CMPNEQSS.
23469 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23470 TargetLowering::DAGCombinerInfo &DCI,
23471 const X86Subtarget *Subtarget) {
23474 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23475 // we're requiring SSE2 for both.
23476 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23477 SDValue N0 = N->getOperand(0);
23478 SDValue N1 = N->getOperand(1);
23479 SDValue CMP0 = N0->getOperand(1);
23480 SDValue CMP1 = N1->getOperand(1);
23483 // The SETCCs should both refer to the same CMP.
23484 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23487 SDValue CMP00 = CMP0->getOperand(0);
23488 SDValue CMP01 = CMP0->getOperand(1);
23489 EVT VT = CMP00.getValueType();
23491 if (VT == MVT::f32 || VT == MVT::f64) {
23492 bool ExpectingFlags = false;
23493 // Check for any users that want flags:
23494 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23495 !ExpectingFlags && UI != UE; ++UI)
23496 switch (UI->getOpcode()) {
23501 ExpectingFlags = true;
23503 case ISD::CopyToReg:
23504 case ISD::SIGN_EXTEND:
23505 case ISD::ZERO_EXTEND:
23506 case ISD::ANY_EXTEND:
23510 if (!ExpectingFlags) {
23511 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23512 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23514 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23515 X86::CondCode tmp = cc0;
23520 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23521 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23522 // FIXME: need symbolic constants for these magic numbers.
23523 // See X86ATTInstPrinter.cpp:printSSECC().
23524 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23525 if (Subtarget->hasAVX512()) {
23526 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23528 DAG.getConstant(x86cc, DL, MVT::i8));
23529 if (N->getValueType(0) != MVT::i1)
23530 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23534 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23535 CMP00.getValueType(), CMP00, CMP01,
23536 DAG.getConstant(x86cc, DL,
23539 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23540 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23542 if (is64BitFP && !Subtarget->is64Bit()) {
23543 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23544 // 64-bit integer, since that's not a legal type. Since
23545 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23546 // bits, but can do this little dance to extract the lowest 32 bits
23547 // and work with those going forward.
23548 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23550 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23551 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23552 Vector32, DAG.getIntPtrConstant(0, DL));
23556 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23557 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23558 DAG.getConstant(1, DL, IntVT));
23559 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23561 return OneBitOfTruth;
23569 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23570 /// so it can be folded inside ANDNP.
23571 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23572 EVT VT = N->getValueType(0);
23574 // Match direct AllOnes for 128 and 256-bit vectors
23575 if (ISD::isBuildVectorAllOnes(N))
23578 // Look through a bit convert.
23579 if (N->getOpcode() == ISD::BITCAST)
23580 N = N->getOperand(0).getNode();
23582 // Sometimes the operand may come from a insert_subvector building a 256-bit
23584 if (VT.is256BitVector() &&
23585 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23586 SDValue V1 = N->getOperand(0);
23587 SDValue V2 = N->getOperand(1);
23589 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23590 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23591 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23592 ISD::isBuildVectorAllOnes(V2.getNode()))
23599 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23600 // register. In most cases we actually compare or select YMM-sized registers
23601 // and mixing the two types creates horrible code. This method optimizes
23602 // some of the transition sequences.
23603 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23604 TargetLowering::DAGCombinerInfo &DCI,
23605 const X86Subtarget *Subtarget) {
23606 EVT VT = N->getValueType(0);
23607 if (!VT.is256BitVector())
23610 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23611 N->getOpcode() == ISD::ZERO_EXTEND ||
23612 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23614 SDValue Narrow = N->getOperand(0);
23615 EVT NarrowVT = Narrow->getValueType(0);
23616 if (!NarrowVT.is128BitVector())
23619 if (Narrow->getOpcode() != ISD::XOR &&
23620 Narrow->getOpcode() != ISD::AND &&
23621 Narrow->getOpcode() != ISD::OR)
23624 SDValue N0 = Narrow->getOperand(0);
23625 SDValue N1 = Narrow->getOperand(1);
23628 // The Left side has to be a trunc.
23629 if (N0.getOpcode() != ISD::TRUNCATE)
23632 // The type of the truncated inputs.
23633 EVT WideVT = N0->getOperand(0)->getValueType(0);
23637 // The right side has to be a 'trunc' or a constant vector.
23638 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23639 ConstantSDNode *RHSConstSplat = nullptr;
23640 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23641 RHSConstSplat = RHSBV->getConstantSplatNode();
23642 if (!RHSTrunc && !RHSConstSplat)
23645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23647 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23650 // Set N0 and N1 to hold the inputs to the new wide operation.
23651 N0 = N0->getOperand(0);
23652 if (RHSConstSplat) {
23653 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23654 SDValue(RHSConstSplat, 0));
23655 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23656 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23657 } else if (RHSTrunc) {
23658 N1 = N1->getOperand(0);
23661 // Generate the wide operation.
23662 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23663 unsigned Opcode = N->getOpcode();
23665 case ISD::ANY_EXTEND:
23667 case ISD::ZERO_EXTEND: {
23668 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23669 APInt Mask = APInt::getAllOnesValue(InBits);
23670 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23671 return DAG.getNode(ISD::AND, DL, VT,
23672 Op, DAG.getConstant(Mask, DL, VT));
23674 case ISD::SIGN_EXTEND:
23675 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23676 Op, DAG.getValueType(NarrowVT));
23678 llvm_unreachable("Unexpected opcode");
23682 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23683 TargetLowering::DAGCombinerInfo &DCI,
23684 const X86Subtarget *Subtarget) {
23685 SDValue N0 = N->getOperand(0);
23686 SDValue N1 = N->getOperand(1);
23689 // A vector zext_in_reg may be represented as a shuffle,
23690 // feeding into a bitcast (this represents anyext) feeding into
23691 // an and with a mask.
23692 // We'd like to try to combine that into a shuffle with zero
23693 // plus a bitcast, removing the and.
23694 if (N0.getOpcode() != ISD::BITCAST ||
23695 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23698 // The other side of the AND should be a splat of 2^C, where C
23699 // is the number of bits in the source type.
23700 if (N1.getOpcode() == ISD::BITCAST)
23701 N1 = N1.getOperand(0);
23702 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23704 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23706 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23707 EVT SrcType = Shuffle->getValueType(0);
23709 // We expect a single-source shuffle
23710 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23713 unsigned SrcSize = SrcType.getScalarSizeInBits();
23715 APInt SplatValue, SplatUndef;
23716 unsigned SplatBitSize;
23718 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23719 SplatBitSize, HasAnyUndefs))
23722 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23723 // Make sure the splat matches the mask we expect
23724 if (SplatBitSize > ResSize ||
23725 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23728 // Make sure the input and output size make sense
23729 if (SrcSize >= ResSize || ResSize % SrcSize)
23732 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23733 // The number of u's between each two values depends on the ratio between
23734 // the source and dest type.
23735 unsigned ZextRatio = ResSize / SrcSize;
23736 bool IsZext = true;
23737 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23738 if (i % ZextRatio) {
23739 if (Shuffle->getMaskElt(i) > 0) {
23745 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23746 // Expected element number
23756 // Ok, perform the transformation - replace the shuffle with
23757 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23758 // (instead of undef) where the k elements come from the zero vector.
23759 SmallVector<int, 8> Mask;
23760 unsigned NumElems = SrcType.getVectorNumElements();
23761 for (unsigned i = 0; i < NumElems; ++i)
23763 Mask.push_back(NumElems);
23765 Mask.push_back(i / ZextRatio);
23767 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23768 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23769 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23772 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23773 TargetLowering::DAGCombinerInfo &DCI,
23774 const X86Subtarget *Subtarget) {
23775 if (DCI.isBeforeLegalizeOps())
23778 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23781 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23784 EVT VT = N->getValueType(0);
23785 SDValue N0 = N->getOperand(0);
23786 SDValue N1 = N->getOperand(1);
23789 // Create BEXTR instructions
23790 // BEXTR is ((X >> imm) & (2**size-1))
23791 if (VT == MVT::i32 || VT == MVT::i64) {
23792 // Check for BEXTR.
23793 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23794 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23795 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23796 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23797 if (MaskNode && ShiftNode) {
23798 uint64_t Mask = MaskNode->getZExtValue();
23799 uint64_t Shift = ShiftNode->getZExtValue();
23800 if (isMask_64(Mask)) {
23801 uint64_t MaskSize = countPopulation(Mask);
23802 if (Shift + MaskSize <= VT.getSizeInBits())
23803 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23804 DAG.getConstant(Shift | (MaskSize << 8), DL,
23813 // Want to form ANDNP nodes:
23814 // 1) In the hopes of then easily combining them with OR and AND nodes
23815 // to form PBLEND/PSIGN.
23816 // 2) To match ANDN packed intrinsics
23817 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23820 // Check LHS for vnot
23821 if (N0.getOpcode() == ISD::XOR &&
23822 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23823 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23824 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23826 // Check RHS for vnot
23827 if (N1.getOpcode() == ISD::XOR &&
23828 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23829 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23830 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23835 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23836 TargetLowering::DAGCombinerInfo &DCI,
23837 const X86Subtarget *Subtarget) {
23838 if (DCI.isBeforeLegalizeOps())
23841 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23844 SDValue N0 = N->getOperand(0);
23845 SDValue N1 = N->getOperand(1);
23846 EVT VT = N->getValueType(0);
23848 // look for psign/blend
23849 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23850 if (!Subtarget->hasSSSE3() ||
23851 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23854 // Canonicalize pandn to RHS
23855 if (N0.getOpcode() == X86ISD::ANDNP)
23857 // or (and (m, y), (pandn m, x))
23858 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23859 SDValue Mask = N1.getOperand(0);
23860 SDValue X = N1.getOperand(1);
23862 if (N0.getOperand(0) == Mask)
23863 Y = N0.getOperand(1);
23864 if (N0.getOperand(1) == Mask)
23865 Y = N0.getOperand(0);
23867 // Check to see if the mask appeared in both the AND and ANDNP and
23871 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23872 // Look through mask bitcast.
23873 if (Mask.getOpcode() == ISD::BITCAST)
23874 Mask = Mask.getOperand(0);
23875 if (X.getOpcode() == ISD::BITCAST)
23876 X = X.getOperand(0);
23877 if (Y.getOpcode() == ISD::BITCAST)
23878 Y = Y.getOperand(0);
23880 EVT MaskVT = Mask.getValueType();
23882 // Validate that the Mask operand is a vector sra node.
23883 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23884 // there is no psrai.b
23885 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23886 unsigned SraAmt = ~0;
23887 if (Mask.getOpcode() == ISD::SRA) {
23888 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23889 if (auto *AmtConst = AmtBV->getConstantSplatNode())
23890 SraAmt = AmtConst->getZExtValue();
23891 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23892 SDValue SraC = Mask.getOperand(1);
23893 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
23895 if ((SraAmt + 1) != EltBits)
23900 // Now we know we at least have a plendvb with the mask val. See if
23901 // we can form a psignb/w/d.
23902 // psign = x.type == y.type == mask.type && y = sub(0, x);
23903 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23904 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23905 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23906 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23907 "Unsupported VT for PSIGN");
23908 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23909 return DAG.getBitcast(VT, Mask);
23911 // PBLENDVB only available on SSE 4.1
23912 if (!Subtarget->hasSSE41())
23915 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23917 X = DAG.getBitcast(BlendVT, X);
23918 Y = DAG.getBitcast(BlendVT, Y);
23919 Mask = DAG.getBitcast(BlendVT, Mask);
23920 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23921 return DAG.getBitcast(VT, Mask);
23925 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23928 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23929 MachineFunction &MF = DAG.getMachineFunction();
23931 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23933 // SHLD/SHRD instructions have lower register pressure, but on some
23934 // platforms they have higher latency than the equivalent
23935 // series of shifts/or that would otherwise be generated.
23936 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23937 // have higher latencies and we are not optimizing for size.
23938 if (!OptForSize && Subtarget->isSHLDSlow())
23941 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23943 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23945 if (!N0.hasOneUse() || !N1.hasOneUse())
23948 SDValue ShAmt0 = N0.getOperand(1);
23949 if (ShAmt0.getValueType() != MVT::i8)
23951 SDValue ShAmt1 = N1.getOperand(1);
23952 if (ShAmt1.getValueType() != MVT::i8)
23954 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23955 ShAmt0 = ShAmt0.getOperand(0);
23956 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23957 ShAmt1 = ShAmt1.getOperand(0);
23960 unsigned Opc = X86ISD::SHLD;
23961 SDValue Op0 = N0.getOperand(0);
23962 SDValue Op1 = N1.getOperand(0);
23963 if (ShAmt0.getOpcode() == ISD::SUB) {
23964 Opc = X86ISD::SHRD;
23965 std::swap(Op0, Op1);
23966 std::swap(ShAmt0, ShAmt1);
23969 unsigned Bits = VT.getSizeInBits();
23970 if (ShAmt1.getOpcode() == ISD::SUB) {
23971 SDValue Sum = ShAmt1.getOperand(0);
23972 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23973 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23974 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23975 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23976 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23977 return DAG.getNode(Opc, DL, VT,
23979 DAG.getNode(ISD::TRUNCATE, DL,
23982 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23983 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23985 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23986 return DAG.getNode(Opc, DL, VT,
23987 N0.getOperand(0), N1.getOperand(0),
23988 DAG.getNode(ISD::TRUNCATE, DL,
23995 // Generate NEG and CMOV for integer abs.
23996 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23997 EVT VT = N->getValueType(0);
23999 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24000 // 8-bit integer abs to NEG and CMOV.
24001 if (VT.isInteger() && VT.getSizeInBits() == 8)
24004 SDValue N0 = N->getOperand(0);
24005 SDValue N1 = N->getOperand(1);
24008 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24009 // and change it to SUB and CMOV.
24010 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24011 N0.getOpcode() == ISD::ADD &&
24012 N0.getOperand(1) == N1 &&
24013 N1.getOpcode() == ISD::SRA &&
24014 N1.getOperand(0) == N0.getOperand(0))
24015 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24016 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24017 // Generate SUB & CMOV.
24018 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24019 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24021 SDValue Ops[] = { N0.getOperand(0), Neg,
24022 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24023 SDValue(Neg.getNode(), 1) };
24024 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24029 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24030 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24031 TargetLowering::DAGCombinerInfo &DCI,
24032 const X86Subtarget *Subtarget) {
24033 if (DCI.isBeforeLegalizeOps())
24036 if (Subtarget->hasCMov())
24037 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24043 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24044 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24045 TargetLowering::DAGCombinerInfo &DCI,
24046 const X86Subtarget *Subtarget) {
24047 LoadSDNode *Ld = cast<LoadSDNode>(N);
24048 EVT RegVT = Ld->getValueType(0);
24049 EVT MemVT = Ld->getMemoryVT();
24051 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24053 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24054 // into two 16-byte operations.
24055 ISD::LoadExtType Ext = Ld->getExtensionType();
24056 unsigned Alignment = Ld->getAlignment();
24057 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24058 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24059 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24060 unsigned NumElems = RegVT.getVectorNumElements();
24064 SDValue Ptr = Ld->getBasePtr();
24065 SDValue Increment =
24066 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24068 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24070 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24071 Ld->getPointerInfo(), Ld->isVolatile(),
24072 Ld->isNonTemporal(), Ld->isInvariant(),
24074 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24075 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24076 Ld->getPointerInfo(), Ld->isVolatile(),
24077 Ld->isNonTemporal(), Ld->isInvariant(),
24078 std::min(16U, Alignment));
24079 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24081 Load2.getValue(1));
24083 SDValue NewVec = DAG.getUNDEF(RegVT);
24084 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24085 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24086 return DCI.CombineTo(N, NewVec, TF, true);
24092 /// PerformMLOADCombine - Resolve extending loads
24093 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24094 TargetLowering::DAGCombinerInfo &DCI,
24095 const X86Subtarget *Subtarget) {
24096 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24097 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24100 EVT VT = Mld->getValueType(0);
24101 unsigned NumElems = VT.getVectorNumElements();
24102 EVT LdVT = Mld->getMemoryVT();
24105 assert(LdVT != VT && "Cannot extend to the same type");
24106 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24107 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24108 // From, To sizes and ElemCount must be pow of two
24109 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24110 "Unexpected size for extending masked load");
24112 unsigned SizeRatio = ToSz / FromSz;
24113 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24115 // Create a type on which we perform the shuffle
24116 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24117 LdVT.getScalarType(), NumElems*SizeRatio);
24118 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24120 // Convert Src0 value
24121 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24122 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24123 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24124 for (unsigned i = 0; i != NumElems; ++i)
24125 ShuffleVec[i] = i * SizeRatio;
24127 // Can't shuffle using an illegal type.
24128 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24129 && "WideVecVT should be legal");
24130 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24131 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24133 // Prepare the new mask
24135 SDValue Mask = Mld->getMask();
24136 if (Mask.getValueType() == VT) {
24137 // Mask and original value have the same type
24138 NewMask = DAG.getBitcast(WideVecVT, Mask);
24139 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24140 for (unsigned i = 0; i != NumElems; ++i)
24141 ShuffleVec[i] = i * SizeRatio;
24142 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24143 ShuffleVec[i] = NumElems*SizeRatio;
24144 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24145 DAG.getConstant(0, dl, WideVecVT),
24149 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24150 unsigned WidenNumElts = NumElems*SizeRatio;
24151 unsigned MaskNumElts = VT.getVectorNumElements();
24152 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24155 unsigned NumConcat = WidenNumElts / MaskNumElts;
24156 SmallVector<SDValue, 16> Ops(NumConcat);
24157 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24159 for (unsigned i = 1; i != NumConcat; ++i)
24162 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24165 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24166 Mld->getBasePtr(), NewMask, WideSrc0,
24167 Mld->getMemoryVT(), Mld->getMemOperand(),
24169 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24170 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24173 /// PerformMSTORECombine - Resolve truncating stores
24174 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24175 const X86Subtarget *Subtarget) {
24176 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24177 if (!Mst->isTruncatingStore())
24180 EVT VT = Mst->getValue().getValueType();
24181 unsigned NumElems = VT.getVectorNumElements();
24182 EVT StVT = Mst->getMemoryVT();
24185 assert(StVT != VT && "Cannot truncate to the same type");
24186 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24187 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24191 // The truncating store is legal in some cases. For example
24192 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24193 // are designated for truncate store.
24194 // In this case we don't need any further transformations.
24195 if (TLI.isTruncStoreLegal(VT, StVT))
24198 // From, To sizes and ElemCount must be pow of two
24199 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24200 "Unexpected size for truncating masked store");
24201 // We are going to use the original vector elt for storing.
24202 // Accumulated smaller vector elements must be a multiple of the store size.
24203 assert (((NumElems * FromSz) % ToSz) == 0 &&
24204 "Unexpected ratio for truncating masked store");
24206 unsigned SizeRatio = FromSz / ToSz;
24207 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24209 // Create a type on which we perform the shuffle
24210 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24211 StVT.getScalarType(), NumElems*SizeRatio);
24213 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24215 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24216 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24217 for (unsigned i = 0; i != NumElems; ++i)
24218 ShuffleVec[i] = i * SizeRatio;
24220 // Can't shuffle using an illegal type.
24221 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24222 && "WideVecVT should be legal");
24224 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24225 DAG.getUNDEF(WideVecVT),
24229 SDValue Mask = Mst->getMask();
24230 if (Mask.getValueType() == VT) {
24231 // Mask and original value have the same type
24232 NewMask = DAG.getBitcast(WideVecVT, Mask);
24233 for (unsigned i = 0; i != NumElems; ++i)
24234 ShuffleVec[i] = i * SizeRatio;
24235 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24236 ShuffleVec[i] = NumElems*SizeRatio;
24237 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24238 DAG.getConstant(0, dl, WideVecVT),
24242 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24243 unsigned WidenNumElts = NumElems*SizeRatio;
24244 unsigned MaskNumElts = VT.getVectorNumElements();
24245 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24248 unsigned NumConcat = WidenNumElts / MaskNumElts;
24249 SmallVector<SDValue, 16> Ops(NumConcat);
24250 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24252 for (unsigned i = 1; i != NumConcat; ++i)
24255 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24258 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24259 NewMask, StVT, Mst->getMemOperand(), false);
24261 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24262 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24263 const X86Subtarget *Subtarget) {
24264 StoreSDNode *St = cast<StoreSDNode>(N);
24265 EVT VT = St->getValue().getValueType();
24266 EVT StVT = St->getMemoryVT();
24268 SDValue StoredVal = St->getOperand(1);
24269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24271 // If we are saving a concatenation of two XMM registers and 32-byte stores
24272 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24273 unsigned Alignment = St->getAlignment();
24274 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24275 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24276 StVT == VT && !IsAligned) {
24277 unsigned NumElems = VT.getVectorNumElements();
24281 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24282 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24285 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24286 SDValue Ptr0 = St->getBasePtr();
24287 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24289 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24290 St->getPointerInfo(), St->isVolatile(),
24291 St->isNonTemporal(), Alignment);
24292 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24293 St->getPointerInfo(), St->isVolatile(),
24294 St->isNonTemporal(),
24295 std::min(16U, Alignment));
24296 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24299 // Optimize trunc store (of multiple scalars) to shuffle and store.
24300 // First, pack all of the elements in one place. Next, store to memory
24301 // in fewer chunks.
24302 if (St->isTruncatingStore() && VT.isVector()) {
24303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24304 unsigned NumElems = VT.getVectorNumElements();
24305 assert(StVT != VT && "Cannot truncate to the same type");
24306 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24307 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24309 // The truncating store is legal in some cases. For example
24310 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24311 // are designated for truncate store.
24312 // In this case we don't need any further transformations.
24313 if (TLI.isTruncStoreLegal(VT, StVT))
24316 // From, To sizes and ElemCount must be pow of two
24317 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24318 // We are going to use the original vector elt for storing.
24319 // Accumulated smaller vector elements must be a multiple of the store size.
24320 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24322 unsigned SizeRatio = FromSz / ToSz;
24324 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24326 // Create a type on which we perform the shuffle
24327 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24328 StVT.getScalarType(), NumElems*SizeRatio);
24330 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24332 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24333 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24334 for (unsigned i = 0; i != NumElems; ++i)
24335 ShuffleVec[i] = i * SizeRatio;
24337 // Can't shuffle using an illegal type.
24338 if (!TLI.isTypeLegal(WideVecVT))
24341 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24342 DAG.getUNDEF(WideVecVT),
24344 // At this point all of the data is stored at the bottom of the
24345 // register. We now need to save it to mem.
24347 // Find the largest store unit
24348 MVT StoreType = MVT::i8;
24349 for (MVT Tp : MVT::integer_valuetypes()) {
24350 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24354 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24355 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24356 (64 <= NumElems * ToSz))
24357 StoreType = MVT::f64;
24359 // Bitcast the original vector into a vector of store-size units
24360 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24361 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24362 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24363 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24364 SmallVector<SDValue, 8> Chains;
24365 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24366 TLI.getPointerTy(DAG.getDataLayout()));
24367 SDValue Ptr = St->getBasePtr();
24369 // Perform one or more big stores into memory.
24370 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24371 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24372 StoreType, ShuffWide,
24373 DAG.getIntPtrConstant(i, dl));
24374 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24375 St->getPointerInfo(), St->isVolatile(),
24376 St->isNonTemporal(), St->getAlignment());
24377 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24378 Chains.push_back(Ch);
24381 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24384 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24385 // the FP state in cases where an emms may be missing.
24386 // A preferable solution to the general problem is to figure out the right
24387 // places to insert EMMS. This qualifies as a quick hack.
24389 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24390 if (VT.getSizeInBits() != 64)
24393 const Function *F = DAG.getMachineFunction().getFunction();
24394 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24396 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24397 if ((VT.isVector() ||
24398 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24399 isa<LoadSDNode>(St->getValue()) &&
24400 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24401 St->getChain().hasOneUse() && !St->isVolatile()) {
24402 SDNode* LdVal = St->getValue().getNode();
24403 LoadSDNode *Ld = nullptr;
24404 int TokenFactorIndex = -1;
24405 SmallVector<SDValue, 8> Ops;
24406 SDNode* ChainVal = St->getChain().getNode();
24407 // Must be a store of a load. We currently handle two cases: the load
24408 // is a direct child, and it's under an intervening TokenFactor. It is
24409 // possible to dig deeper under nested TokenFactors.
24410 if (ChainVal == LdVal)
24411 Ld = cast<LoadSDNode>(St->getChain());
24412 else if (St->getValue().hasOneUse() &&
24413 ChainVal->getOpcode() == ISD::TokenFactor) {
24414 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24415 if (ChainVal->getOperand(i).getNode() == LdVal) {
24416 TokenFactorIndex = i;
24417 Ld = cast<LoadSDNode>(St->getValue());
24419 Ops.push_back(ChainVal->getOperand(i));
24423 if (!Ld || !ISD::isNormalLoad(Ld))
24426 // If this is not the MMX case, i.e. we are just turning i64 load/store
24427 // into f64 load/store, avoid the transformation if there are multiple
24428 // uses of the loaded value.
24429 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24434 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24435 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24437 if (Subtarget->is64Bit() || F64IsLegal) {
24438 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24439 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24440 Ld->getPointerInfo(), Ld->isVolatile(),
24441 Ld->isNonTemporal(), Ld->isInvariant(),
24442 Ld->getAlignment());
24443 SDValue NewChain = NewLd.getValue(1);
24444 if (TokenFactorIndex != -1) {
24445 Ops.push_back(NewChain);
24446 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24448 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24449 St->getPointerInfo(),
24450 St->isVolatile(), St->isNonTemporal(),
24451 St->getAlignment());
24454 // Otherwise, lower to two pairs of 32-bit loads / stores.
24455 SDValue LoAddr = Ld->getBasePtr();
24456 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24457 DAG.getConstant(4, LdDL, MVT::i32));
24459 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24460 Ld->getPointerInfo(),
24461 Ld->isVolatile(), Ld->isNonTemporal(),
24462 Ld->isInvariant(), Ld->getAlignment());
24463 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24464 Ld->getPointerInfo().getWithOffset(4),
24465 Ld->isVolatile(), Ld->isNonTemporal(),
24467 MinAlign(Ld->getAlignment(), 4));
24469 SDValue NewChain = LoLd.getValue(1);
24470 if (TokenFactorIndex != -1) {
24471 Ops.push_back(LoLd);
24472 Ops.push_back(HiLd);
24473 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24476 LoAddr = St->getBasePtr();
24477 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24478 DAG.getConstant(4, StDL, MVT::i32));
24480 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24481 St->getPointerInfo(),
24482 St->isVolatile(), St->isNonTemporal(),
24483 St->getAlignment());
24484 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24485 St->getPointerInfo().getWithOffset(4),
24487 St->isNonTemporal(),
24488 MinAlign(St->getAlignment(), 4));
24489 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24492 // This is similar to the above case, but here we handle a scalar 64-bit
24493 // integer store that is extracted from a vector on a 32-bit target.
24494 // If we have SSE2, then we can treat it like a floating-point double
24495 // to get past legalization. The execution dependencies fixup pass will
24496 // choose the optimal machine instruction for the store if this really is
24497 // an integer or v2f32 rather than an f64.
24498 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24499 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24500 SDValue OldExtract = St->getOperand(1);
24501 SDValue ExtOp0 = OldExtract.getOperand(0);
24502 unsigned VecSize = ExtOp0.getValueSizeInBits();
24503 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24504 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24505 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24506 BitCast, OldExtract.getOperand(1));
24507 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24508 St->getPointerInfo(), St->isVolatile(),
24509 St->isNonTemporal(), St->getAlignment());
24515 /// Return 'true' if this vector operation is "horizontal"
24516 /// and return the operands for the horizontal operation in LHS and RHS. A
24517 /// horizontal operation performs the binary operation on successive elements
24518 /// of its first operand, then on successive elements of its second operand,
24519 /// returning the resulting values in a vector. For example, if
24520 /// A = < float a0, float a1, float a2, float a3 >
24522 /// B = < float b0, float b1, float b2, float b3 >
24523 /// then the result of doing a horizontal operation on A and B is
24524 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24525 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24526 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24527 /// set to A, RHS to B, and the routine returns 'true'.
24528 /// Note that the binary operation should have the property that if one of the
24529 /// operands is UNDEF then the result is UNDEF.
24530 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24531 // Look for the following pattern: if
24532 // A = < float a0, float a1, float a2, float a3 >
24533 // B = < float b0, float b1, float b2, float b3 >
24535 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24536 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24537 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24538 // which is A horizontal-op B.
24540 // At least one of the operands should be a vector shuffle.
24541 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24542 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24545 MVT VT = LHS.getSimpleValueType();
24547 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24548 "Unsupported vector type for horizontal add/sub");
24550 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24551 // operate independently on 128-bit lanes.
24552 unsigned NumElts = VT.getVectorNumElements();
24553 unsigned NumLanes = VT.getSizeInBits()/128;
24554 unsigned NumLaneElts = NumElts / NumLanes;
24555 assert((NumLaneElts % 2 == 0) &&
24556 "Vector type should have an even number of elements in each lane");
24557 unsigned HalfLaneElts = NumLaneElts/2;
24559 // View LHS in the form
24560 // LHS = VECTOR_SHUFFLE A, B, LMask
24561 // If LHS is not a shuffle then pretend it is the shuffle
24562 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24563 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24566 SmallVector<int, 16> LMask(NumElts);
24567 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24568 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24569 A = LHS.getOperand(0);
24570 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24571 B = LHS.getOperand(1);
24572 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24573 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24575 if (LHS.getOpcode() != ISD::UNDEF)
24577 for (unsigned i = 0; i != NumElts; ++i)
24581 // Likewise, view RHS in the form
24582 // RHS = VECTOR_SHUFFLE C, D, RMask
24584 SmallVector<int, 16> RMask(NumElts);
24585 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24586 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24587 C = RHS.getOperand(0);
24588 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24589 D = RHS.getOperand(1);
24590 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24591 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24593 if (RHS.getOpcode() != ISD::UNDEF)
24595 for (unsigned i = 0; i != NumElts; ++i)
24599 // Check that the shuffles are both shuffling the same vectors.
24600 if (!(A == C && B == D) && !(A == D && B == C))
24603 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24604 if (!A.getNode() && !B.getNode())
24607 // If A and B occur in reverse order in RHS, then "swap" them (which means
24608 // rewriting the mask).
24610 ShuffleVectorSDNode::commuteMask(RMask);
24612 // At this point LHS and RHS are equivalent to
24613 // LHS = VECTOR_SHUFFLE A, B, LMask
24614 // RHS = VECTOR_SHUFFLE A, B, RMask
24615 // Check that the masks correspond to performing a horizontal operation.
24616 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24617 for (unsigned i = 0; i != NumLaneElts; ++i) {
24618 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24620 // Ignore any UNDEF components.
24621 if (LIdx < 0 || RIdx < 0 ||
24622 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24623 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24626 // Check that successive elements are being operated on. If not, this is
24627 // not a horizontal operation.
24628 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24629 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24630 if (!(LIdx == Index && RIdx == Index + 1) &&
24631 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24636 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24637 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24641 /// Do target-specific dag combines on floating point adds.
24642 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24643 const X86Subtarget *Subtarget) {
24644 EVT VT = N->getValueType(0);
24645 SDValue LHS = N->getOperand(0);
24646 SDValue RHS = N->getOperand(1);
24648 // Try to synthesize horizontal adds from adds of shuffles.
24649 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24650 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24651 isHorizontalBinOp(LHS, RHS, true))
24652 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24656 /// Do target-specific dag combines on floating point subs.
24657 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24658 const X86Subtarget *Subtarget) {
24659 EVT VT = N->getValueType(0);
24660 SDValue LHS = N->getOperand(0);
24661 SDValue RHS = N->getOperand(1);
24663 // Try to synthesize horizontal subs from subs of shuffles.
24664 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24665 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24666 isHorizontalBinOp(LHS, RHS, false))
24667 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24671 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24672 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24673 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24675 // F[X]OR(0.0, x) -> x
24676 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24677 if (C->getValueAPF().isPosZero())
24678 return N->getOperand(1);
24680 // F[X]OR(x, 0.0) -> x
24681 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24682 if (C->getValueAPF().isPosZero())
24683 return N->getOperand(0);
24687 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24688 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24689 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24691 // Only perform optimizations if UnsafeMath is used.
24692 if (!DAG.getTarget().Options.UnsafeFPMath)
24695 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24696 // into FMINC and FMAXC, which are Commutative operations.
24697 unsigned NewOp = 0;
24698 switch (N->getOpcode()) {
24699 default: llvm_unreachable("unknown opcode");
24700 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24701 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24704 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24705 N->getOperand(0), N->getOperand(1));
24708 /// Do target-specific dag combines on X86ISD::FAND nodes.
24709 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24710 // FAND(0.0, x) -> 0.0
24711 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24712 if (C->getValueAPF().isPosZero())
24713 return N->getOperand(0);
24715 // FAND(x, 0.0) -> 0.0
24716 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24717 if (C->getValueAPF().isPosZero())
24718 return N->getOperand(1);
24723 /// Do target-specific dag combines on X86ISD::FANDN nodes
24724 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24725 // FANDN(0.0, x) -> x
24726 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24727 if (C->getValueAPF().isPosZero())
24728 return N->getOperand(1);
24730 // FANDN(x, 0.0) -> 0.0
24731 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24732 if (C->getValueAPF().isPosZero())
24733 return N->getOperand(1);
24738 static SDValue PerformBTCombine(SDNode *N,
24740 TargetLowering::DAGCombinerInfo &DCI) {
24741 // BT ignores high bits in the bit index operand.
24742 SDValue Op1 = N->getOperand(1);
24743 if (Op1.hasOneUse()) {
24744 unsigned BitWidth = Op1.getValueSizeInBits();
24745 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24746 APInt KnownZero, KnownOne;
24747 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24748 !DCI.isBeforeLegalizeOps());
24749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24750 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24751 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24752 DCI.CommitTargetLoweringOpt(TLO);
24757 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24758 SDValue Op = N->getOperand(0);
24759 if (Op.getOpcode() == ISD::BITCAST)
24760 Op = Op.getOperand(0);
24761 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24762 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24763 VT.getVectorElementType().getSizeInBits() ==
24764 OpVT.getVectorElementType().getSizeInBits()) {
24765 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24770 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24771 const X86Subtarget *Subtarget) {
24772 EVT VT = N->getValueType(0);
24773 if (!VT.isVector())
24776 SDValue N0 = N->getOperand(0);
24777 SDValue N1 = N->getOperand(1);
24778 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24781 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24782 // both SSE and AVX2 since there is no sign-extended shift right
24783 // operation on a vector with 64-bit elements.
24784 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24785 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24786 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24787 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24788 SDValue N00 = N0.getOperand(0);
24790 // EXTLOAD has a better solution on AVX2,
24791 // it may be replaced with X86ISD::VSEXT node.
24792 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24793 if (!ISD::isNormalLoad(N00.getNode()))
24796 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24797 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24799 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24805 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24806 TargetLowering::DAGCombinerInfo &DCI,
24807 const X86Subtarget *Subtarget) {
24808 SDValue N0 = N->getOperand(0);
24809 EVT VT = N->getValueType(0);
24810 EVT SVT = VT.getScalarType();
24811 EVT InVT = N0.getValueType();
24812 EVT InSVT = InVT.getScalarType();
24815 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24816 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24817 // This exposes the sext to the sdivrem lowering, so that it directly extends
24818 // from AH (which we otherwise need to do contortions to access).
24819 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24820 InVT == MVT::i8 && VT == MVT::i32) {
24821 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24822 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24823 N0.getOperand(0), N0.getOperand(1));
24824 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24825 return R.getValue(1);
24828 if (!DCI.isBeforeLegalizeOps()) {
24829 if (InVT == MVT::i1) {
24830 SDValue Zero = DAG.getConstant(0, DL, VT);
24832 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24833 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24838 if (VT.isVector() && Subtarget->hasSSE2()) {
24839 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24840 EVT InVT = N.getValueType();
24841 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24842 Size / InVT.getScalarSizeInBits());
24843 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24844 DAG.getUNDEF(InVT));
24846 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24849 // If target-size is less than 128-bits, extend to a type that would extend
24850 // to 128 bits, extend that and extract the original target vector.
24851 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24852 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24853 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24854 unsigned Scale = 128 / VT.getSizeInBits();
24856 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24857 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24858 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24859 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24860 DAG.getIntPtrConstant(0, DL));
24863 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24864 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24865 if (VT.getSizeInBits() == 128 &&
24866 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24867 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24868 SDValue ExOp = ExtendVecSize(DL, N0, 128);
24869 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24872 // On pre-AVX2 targets, split into 128-bit nodes of
24873 // ISD::SIGN_EXTEND_VECTOR_INREG.
24874 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24875 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24876 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24877 unsigned NumVecs = VT.getSizeInBits() / 128;
24878 unsigned NumSubElts = 128 / SVT.getSizeInBits();
24879 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24880 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24882 SmallVector<SDValue, 8> Opnds;
24883 for (unsigned i = 0, Offset = 0; i != NumVecs;
24884 ++i, Offset += NumSubElts) {
24885 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24886 DAG.getIntPtrConstant(Offset, DL));
24887 SrcVec = ExtendVecSize(DL, SrcVec, 128);
24888 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24889 Opnds.push_back(SrcVec);
24891 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24895 if (!Subtarget->hasFp256())
24898 if (VT.isVector() && VT.getSizeInBits() == 256)
24899 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24905 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24906 const X86Subtarget* Subtarget) {
24908 EVT VT = N->getValueType(0);
24910 // Let legalize expand this if it isn't a legal type yet.
24911 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24914 EVT ScalarVT = VT.getScalarType();
24915 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24916 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24917 !Subtarget->hasAVX512()))
24920 SDValue A = N->getOperand(0);
24921 SDValue B = N->getOperand(1);
24922 SDValue C = N->getOperand(2);
24924 bool NegA = (A.getOpcode() == ISD::FNEG);
24925 bool NegB = (B.getOpcode() == ISD::FNEG);
24926 bool NegC = (C.getOpcode() == ISD::FNEG);
24928 // Negative multiplication when NegA xor NegB
24929 bool NegMul = (NegA != NegB);
24931 A = A.getOperand(0);
24933 B = B.getOperand(0);
24935 C = C.getOperand(0);
24939 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24941 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24943 return DAG.getNode(Opcode, dl, VT, A, B, C);
24946 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24947 TargetLowering::DAGCombinerInfo &DCI,
24948 const X86Subtarget *Subtarget) {
24949 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
24950 // (and (i32 x86isd::setcc_carry), 1)
24951 // This eliminates the zext. This transformation is necessary because
24952 // ISD::SETCC is always legalized to i8.
24954 SDValue N0 = N->getOperand(0);
24955 EVT VT = N->getValueType(0);
24957 if (N0.getOpcode() == ISD::AND &&
24959 N0.getOperand(0).hasOneUse()) {
24960 SDValue N00 = N0.getOperand(0);
24961 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24962 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24963 if (!C || C->getZExtValue() != 1)
24965 return DAG.getNode(ISD::AND, dl, VT,
24966 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24967 N00.getOperand(0), N00.getOperand(1)),
24968 DAG.getConstant(1, dl, VT));
24972 if (N0.getOpcode() == ISD::TRUNCATE &&
24974 N0.getOperand(0).hasOneUse()) {
24975 SDValue N00 = N0.getOperand(0);
24976 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24977 return DAG.getNode(ISD::AND, dl, VT,
24978 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24979 N00.getOperand(0), N00.getOperand(1)),
24980 DAG.getConstant(1, dl, VT));
24984 if (VT.is256BitVector())
24985 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24988 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24989 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24990 // This exposes the zext to the udivrem lowering, so that it directly extends
24991 // from AH (which we otherwise need to do contortions to access).
24992 if (N0.getOpcode() == ISD::UDIVREM &&
24993 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24994 (VT == MVT::i32 || VT == MVT::i64)) {
24995 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24996 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24997 N0.getOperand(0), N0.getOperand(1));
24998 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24999 return R.getValue(1);
25005 // Optimize x == -y --> x+y == 0
25006 // x != -y --> x+y != 0
25007 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25008 const X86Subtarget* Subtarget) {
25009 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25010 SDValue LHS = N->getOperand(0);
25011 SDValue RHS = N->getOperand(1);
25012 EVT VT = N->getValueType(0);
25015 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25017 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25018 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25019 LHS.getOperand(1));
25020 return DAG.getSetCC(DL, N->getValueType(0), addV,
25021 DAG.getConstant(0, DL, addV.getValueType()), CC);
25023 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25025 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25026 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25027 RHS.getOperand(1));
25028 return DAG.getSetCC(DL, N->getValueType(0), addV,
25029 DAG.getConstant(0, DL, addV.getValueType()), CC);
25032 if (VT.getScalarType() == MVT::i1 &&
25033 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25035 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25036 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25037 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25039 if (!IsSEXT0 || !IsVZero1) {
25040 // Swap the operands and update the condition code.
25041 std::swap(LHS, RHS);
25042 CC = ISD::getSetCCSwappedOperands(CC);
25044 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25045 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25046 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25049 if (IsSEXT0 && IsVZero1) {
25050 assert(VT == LHS.getOperand(0).getValueType() &&
25051 "Uexpected operand type");
25052 if (CC == ISD::SETGT)
25053 return DAG.getConstant(0, DL, VT);
25054 if (CC == ISD::SETLE)
25055 return DAG.getConstant(1, DL, VT);
25056 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25057 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25059 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25060 "Unexpected condition code!");
25061 return LHS.getOperand(0);
25068 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25069 SelectionDAG &DAG) {
25071 MVT VT = Load->getSimpleValueType(0);
25072 MVT EVT = VT.getVectorElementType();
25073 SDValue Addr = Load->getOperand(1);
25074 SDValue NewAddr = DAG.getNode(
25075 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25076 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25077 Addr.getSimpleValueType()));
25080 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25081 DAG.getMachineFunction().getMachineMemOperand(
25082 Load->getMemOperand(), 0, EVT.getStoreSize()));
25086 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25087 const X86Subtarget *Subtarget) {
25089 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25090 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25091 "X86insertps is only defined for v4x32");
25093 SDValue Ld = N->getOperand(1);
25094 if (MayFoldLoad(Ld)) {
25095 // Extract the countS bits from the immediate so we can get the proper
25096 // address when narrowing the vector load to a specific element.
25097 // When the second source op is a memory address, insertps doesn't use
25098 // countS and just gets an f32 from that address.
25099 unsigned DestIndex =
25100 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25102 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25104 // Create this as a scalar to vector to match the instruction pattern.
25105 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25106 // countS bits are ignored when loading from memory on insertps, which
25107 // means we don't need to explicitly set them to 0.
25108 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25109 LoadScalarToVector, N->getOperand(2));
25114 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25115 SDValue V0 = N->getOperand(0);
25116 SDValue V1 = N->getOperand(1);
25118 EVT VT = N->getValueType(0);
25120 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25121 // operands and changing the mask to 1. This saves us a bunch of
25122 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25123 // x86InstrInfo knows how to commute this back after instruction selection
25124 // if it would help register allocation.
25126 // TODO: If optimizing for size or a processor that doesn't suffer from
25127 // partial register update stalls, this should be transformed into a MOVSD
25128 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25130 if (VT == MVT::v2f64)
25131 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25132 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25133 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25134 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25140 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25141 // as "sbb reg,reg", since it can be extended without zext and produces
25142 // an all-ones bit which is more useful than 0/1 in some cases.
25143 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25146 return DAG.getNode(ISD::AND, DL, VT,
25147 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25148 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25150 DAG.getConstant(1, DL, VT));
25151 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25152 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25153 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25154 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25158 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25159 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25160 TargetLowering::DAGCombinerInfo &DCI,
25161 const X86Subtarget *Subtarget) {
25163 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25164 SDValue EFLAGS = N->getOperand(1);
25166 if (CC == X86::COND_A) {
25167 // Try to convert COND_A into COND_B in an attempt to facilitate
25168 // materializing "setb reg".
25170 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25171 // cannot take an immediate as its first operand.
25173 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25174 EFLAGS.getValueType().isInteger() &&
25175 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25176 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25177 EFLAGS.getNode()->getVTList(),
25178 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25179 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25180 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25184 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25185 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25187 if (CC == X86::COND_B)
25188 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25190 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25191 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25192 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25198 // Optimize branch condition evaluation.
25200 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25201 TargetLowering::DAGCombinerInfo &DCI,
25202 const X86Subtarget *Subtarget) {
25204 SDValue Chain = N->getOperand(0);
25205 SDValue Dest = N->getOperand(1);
25206 SDValue EFLAGS = N->getOperand(3);
25207 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25209 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25210 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25211 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25218 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25219 SelectionDAG &DAG) {
25220 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25221 // optimize away operation when it's from a constant.
25223 // The general transformation is:
25224 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25225 // AND(VECTOR_CMP(x,y), constant2)
25226 // constant2 = UNARYOP(constant)
25228 // Early exit if this isn't a vector operation, the operand of the
25229 // unary operation isn't a bitwise AND, or if the sizes of the operations
25230 // aren't the same.
25231 EVT VT = N->getValueType(0);
25232 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25233 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25234 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25237 // Now check that the other operand of the AND is a constant. We could
25238 // make the transformation for non-constant splats as well, but it's unclear
25239 // that would be a benefit as it would not eliminate any operations, just
25240 // perform one more step in scalar code before moving to the vector unit.
25241 if (BuildVectorSDNode *BV =
25242 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25243 // Bail out if the vector isn't a constant.
25244 if (!BV->isConstant())
25247 // Everything checks out. Build up the new and improved node.
25249 EVT IntVT = BV->getValueType(0);
25250 // Create a new constant of the appropriate type for the transformed
25252 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25253 // The AND node needs bitcasts to/from an integer vector type around it.
25254 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25255 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25256 N->getOperand(0)->getOperand(0), MaskConst);
25257 SDValue Res = DAG.getBitcast(VT, NewAnd);
25264 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25265 const X86Subtarget *Subtarget) {
25266 SDValue Op0 = N->getOperand(0);
25267 EVT VT = N->getValueType(0);
25268 EVT InVT = Op0.getValueType();
25269 EVT InSVT = InVT.getScalarType();
25270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25272 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25273 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25274 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25276 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25277 InVT.getVectorNumElements());
25278 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25280 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25281 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25283 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25289 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25290 const X86Subtarget *Subtarget) {
25291 // First try to optimize away the conversion entirely when it's
25292 // conditionally from a constant. Vectors only.
25293 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25296 // Now move on to more general possibilities.
25297 SDValue Op0 = N->getOperand(0);
25298 EVT VT = N->getValueType(0);
25299 EVT InVT = Op0.getValueType();
25300 EVT InSVT = InVT.getScalarType();
25302 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25303 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25304 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25306 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25307 InVT.getVectorNumElements());
25308 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25309 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25312 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25313 // a 32-bit target where SSE doesn't support i64->FP operations.
25314 if (Op0.getOpcode() == ISD::LOAD) {
25315 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25316 EVT LdVT = Ld->getValueType(0);
25318 // This transformation is not supported if the result type is f16
25319 if (VT == MVT::f16)
25322 if (!Ld->isVolatile() && !VT.isVector() &&
25323 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25324 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25325 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25326 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25327 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25334 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25335 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25336 X86TargetLowering::DAGCombinerInfo &DCI) {
25337 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25338 // the result is either zero or one (depending on the input carry bit).
25339 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25340 if (X86::isZeroNode(N->getOperand(0)) &&
25341 X86::isZeroNode(N->getOperand(1)) &&
25342 // We don't have a good way to replace an EFLAGS use, so only do this when
25344 SDValue(N, 1).use_empty()) {
25346 EVT VT = N->getValueType(0);
25347 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25348 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25349 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25350 DAG.getConstant(X86::COND_B, DL,
25353 DAG.getConstant(1, DL, VT));
25354 return DCI.CombineTo(N, Res1, CarryOut);
25360 // fold (add Y, (sete X, 0)) -> adc 0, Y
25361 // (add Y, (setne X, 0)) -> sbb -1, Y
25362 // (sub (sete X, 0), Y) -> sbb 0, Y
25363 // (sub (setne X, 0), Y) -> adc -1, Y
25364 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25367 // Look through ZExts.
25368 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25369 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25372 SDValue SetCC = Ext.getOperand(0);
25373 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25376 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25377 if (CC != X86::COND_E && CC != X86::COND_NE)
25380 SDValue Cmp = SetCC.getOperand(1);
25381 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25382 !X86::isZeroNode(Cmp.getOperand(1)) ||
25383 !Cmp.getOperand(0).getValueType().isInteger())
25386 SDValue CmpOp0 = Cmp.getOperand(0);
25387 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25388 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25390 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25391 if (CC == X86::COND_NE)
25392 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25393 DL, OtherVal.getValueType(), OtherVal,
25394 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25396 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25397 DL, OtherVal.getValueType(), OtherVal,
25398 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25401 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25402 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25403 const X86Subtarget *Subtarget) {
25404 EVT VT = N->getValueType(0);
25405 SDValue Op0 = N->getOperand(0);
25406 SDValue Op1 = N->getOperand(1);
25408 // Try to synthesize horizontal adds from adds of shuffles.
25409 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25410 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25411 isHorizontalBinOp(Op0, Op1, true))
25412 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25414 return OptimizeConditionalInDecrement(N, DAG);
25417 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25418 const X86Subtarget *Subtarget) {
25419 SDValue Op0 = N->getOperand(0);
25420 SDValue Op1 = N->getOperand(1);
25422 // X86 can't encode an immediate LHS of a sub. See if we can push the
25423 // negation into a preceding instruction.
25424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25425 // If the RHS of the sub is a XOR with one use and a constant, invert the
25426 // immediate. Then add one to the LHS of the sub so we can turn
25427 // X-Y -> X+~Y+1, saving one register.
25428 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25429 isa<ConstantSDNode>(Op1.getOperand(1))) {
25430 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25431 EVT VT = Op0.getValueType();
25432 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25434 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25435 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25436 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25440 // Try to synthesize horizontal adds from adds of shuffles.
25441 EVT VT = N->getValueType(0);
25442 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25443 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25444 isHorizontalBinOp(Op0, Op1, true))
25445 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25447 return OptimizeConditionalInDecrement(N, DAG);
25450 /// performVZEXTCombine - Performs build vector combines
25451 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25452 TargetLowering::DAGCombinerInfo &DCI,
25453 const X86Subtarget *Subtarget) {
25455 MVT VT = N->getSimpleValueType(0);
25456 SDValue Op = N->getOperand(0);
25457 MVT OpVT = Op.getSimpleValueType();
25458 MVT OpEltVT = OpVT.getVectorElementType();
25459 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25461 // (vzext (bitcast (vzext (x)) -> (vzext x)
25463 while (V.getOpcode() == ISD::BITCAST)
25464 V = V.getOperand(0);
25466 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25467 MVT InnerVT = V.getSimpleValueType();
25468 MVT InnerEltVT = InnerVT.getVectorElementType();
25470 // If the element sizes match exactly, we can just do one larger vzext. This
25471 // is always an exact type match as vzext operates on integer types.
25472 if (OpEltVT == InnerEltVT) {
25473 assert(OpVT == InnerVT && "Types must match for vzext!");
25474 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25477 // The only other way we can combine them is if only a single element of the
25478 // inner vzext is used in the input to the outer vzext.
25479 if (InnerEltVT.getSizeInBits() < InputBits)
25482 // In this case, the inner vzext is completely dead because we're going to
25483 // only look at bits inside of the low element. Just do the outer vzext on
25484 // a bitcast of the input to the inner.
25485 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25488 // Check if we can bypass extracting and re-inserting an element of an input
25489 // vector. Essentialy:
25490 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25491 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25492 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25493 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25494 SDValue ExtractedV = V.getOperand(0);
25495 SDValue OrigV = ExtractedV.getOperand(0);
25496 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25497 if (ExtractIdx->getZExtValue() == 0) {
25498 MVT OrigVT = OrigV.getSimpleValueType();
25499 // Extract a subvector if necessary...
25500 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25501 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25502 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25503 OrigVT.getVectorNumElements() / Ratio);
25504 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25505 DAG.getIntPtrConstant(0, DL));
25507 Op = DAG.getBitcast(OpVT, OrigV);
25508 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25515 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25516 DAGCombinerInfo &DCI) const {
25517 SelectionDAG &DAG = DCI.DAG;
25518 switch (N->getOpcode()) {
25520 case ISD::EXTRACT_VECTOR_ELT:
25521 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25524 case X86ISD::SHRUNKBLEND:
25525 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25526 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25527 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25528 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25529 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25530 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25531 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25534 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25535 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25536 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25537 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25538 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25539 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25540 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25541 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25542 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25543 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25544 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25545 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25547 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25549 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25550 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25551 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25552 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25553 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25554 case ISD::ANY_EXTEND:
25555 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25556 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25557 case ISD::SIGN_EXTEND_INREG:
25558 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25559 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25560 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25561 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25562 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25563 case X86ISD::SHUFP: // Handle all target specific shuffles
25564 case X86ISD::PALIGNR:
25565 case X86ISD::UNPCKH:
25566 case X86ISD::UNPCKL:
25567 case X86ISD::MOVHLPS:
25568 case X86ISD::MOVLHPS:
25569 case X86ISD::PSHUFB:
25570 case X86ISD::PSHUFD:
25571 case X86ISD::PSHUFHW:
25572 case X86ISD::PSHUFLW:
25573 case X86ISD::MOVSS:
25574 case X86ISD::MOVSD:
25575 case X86ISD::VPERMILPI:
25576 case X86ISD::VPERM2X128:
25577 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25578 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25579 case ISD::INTRINSIC_WO_CHAIN:
25580 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25581 case X86ISD::INSERTPS: {
25582 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25583 return PerformINSERTPSCombine(N, DAG, Subtarget);
25586 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25592 /// isTypeDesirableForOp - Return true if the target has native support for
25593 /// the specified value type and it is 'desirable' to use the type for the
25594 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25595 /// instruction encodings are longer and some i16 instructions are slow.
25596 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25597 if (!isTypeLegal(VT))
25599 if (VT != MVT::i16)
25606 case ISD::SIGN_EXTEND:
25607 case ISD::ZERO_EXTEND:
25608 case ISD::ANY_EXTEND:
25621 /// IsDesirableToPromoteOp - This method query the target whether it is
25622 /// beneficial for dag combiner to promote the specified node. If true, it
25623 /// should return the desired promotion type by reference.
25624 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25625 EVT VT = Op.getValueType();
25626 if (VT != MVT::i16)
25629 bool Promote = false;
25630 bool Commute = false;
25631 switch (Op.getOpcode()) {
25634 LoadSDNode *LD = cast<LoadSDNode>(Op);
25635 // If the non-extending load has a single use and it's not live out, then it
25636 // might be folded.
25637 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25638 Op.hasOneUse()*/) {
25639 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25640 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25641 // The only case where we'd want to promote LOAD (rather then it being
25642 // promoted as an operand is when it's only use is liveout.
25643 if (UI->getOpcode() != ISD::CopyToReg)
25650 case ISD::SIGN_EXTEND:
25651 case ISD::ZERO_EXTEND:
25652 case ISD::ANY_EXTEND:
25657 SDValue N0 = Op.getOperand(0);
25658 // Look out for (store (shl (load), x)).
25659 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25672 SDValue N0 = Op.getOperand(0);
25673 SDValue N1 = Op.getOperand(1);
25674 if (!Commute && MayFoldLoad(N1))
25676 // Avoid disabling potential load folding opportunities.
25677 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25679 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25689 //===----------------------------------------------------------------------===//
25690 // X86 Inline Assembly Support
25691 //===----------------------------------------------------------------------===//
25693 // Helper to match a string separated by whitespace.
25694 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25695 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25697 for (StringRef Piece : Pieces) {
25698 if (!S.startswith(Piece)) // Check if the piece matches.
25701 S = S.substr(Piece.size());
25702 StringRef::size_type Pos = S.find_first_not_of(" \t");
25703 if (Pos == 0) // We matched a prefix.
25712 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25714 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25715 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25716 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25717 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25719 if (AsmPieces.size() == 3)
25721 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25728 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25729 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25731 std::string AsmStr = IA->getAsmString();
25733 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25734 if (!Ty || Ty->getBitWidth() % 16 != 0)
25737 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25738 SmallVector<StringRef, 4> AsmPieces;
25739 SplitString(AsmStr, AsmPieces, ";\n");
25741 switch (AsmPieces.size()) {
25742 default: return false;
25744 // FIXME: this should verify that we are targeting a 486 or better. If not,
25745 // we will turn this bswap into something that will be lowered to logical
25746 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25747 // lower so don't worry about this.
25749 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25750 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25751 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25752 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25753 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25754 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25755 // No need to check constraints, nothing other than the equivalent of
25756 // "=r,0" would be valid here.
25757 return IntrinsicLowering::LowerToByteSwap(CI);
25760 // rorw $$8, ${0:w} --> llvm.bswap.i16
25761 if (CI->getType()->isIntegerTy(16) &&
25762 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25763 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25764 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25766 StringRef ConstraintsStr = IA->getConstraintString();
25767 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25768 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25769 if (clobbersFlagRegisters(AsmPieces))
25770 return IntrinsicLowering::LowerToByteSwap(CI);
25774 if (CI->getType()->isIntegerTy(32) &&
25775 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25776 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25777 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25778 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25780 StringRef ConstraintsStr = IA->getConstraintString();
25781 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25782 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25783 if (clobbersFlagRegisters(AsmPieces))
25784 return IntrinsicLowering::LowerToByteSwap(CI);
25787 if (CI->getType()->isIntegerTy(64)) {
25788 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25789 if (Constraints.size() >= 2 &&
25790 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25791 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25792 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25793 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25794 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25795 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25796 return IntrinsicLowering::LowerToByteSwap(CI);
25804 /// getConstraintType - Given a constraint letter, return the type of
25805 /// constraint it is for this target.
25806 X86TargetLowering::ConstraintType
25807 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25808 if (Constraint.size() == 1) {
25809 switch (Constraint[0]) {
25820 return C_RegisterClass;
25844 return TargetLowering::getConstraintType(Constraint);
25847 /// Examine constraint type and operand type and determine a weight value.
25848 /// This object must already have been set up with the operand type
25849 /// and the current alternative constraint selected.
25850 TargetLowering::ConstraintWeight
25851 X86TargetLowering::getSingleConstraintMatchWeight(
25852 AsmOperandInfo &info, const char *constraint) const {
25853 ConstraintWeight weight = CW_Invalid;
25854 Value *CallOperandVal = info.CallOperandVal;
25855 // If we don't have a value, we can't do a match,
25856 // but allow it at the lowest weight.
25857 if (!CallOperandVal)
25859 Type *type = CallOperandVal->getType();
25860 // Look at the constraint type.
25861 switch (*constraint) {
25863 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25874 if (CallOperandVal->getType()->isIntegerTy())
25875 weight = CW_SpecificReg;
25880 if (type->isFloatingPointTy())
25881 weight = CW_SpecificReg;
25884 if (type->isX86_MMXTy() && Subtarget->hasMMX())
25885 weight = CW_SpecificReg;
25889 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25890 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25891 weight = CW_Register;
25894 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25895 if (C->getZExtValue() <= 31)
25896 weight = CW_Constant;
25900 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25901 if (C->getZExtValue() <= 63)
25902 weight = CW_Constant;
25906 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25907 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25908 weight = CW_Constant;
25912 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25913 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25914 weight = CW_Constant;
25918 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25919 if (C->getZExtValue() <= 3)
25920 weight = CW_Constant;
25924 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25925 if (C->getZExtValue() <= 0xff)
25926 weight = CW_Constant;
25931 if (isa<ConstantFP>(CallOperandVal)) {
25932 weight = CW_Constant;
25936 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25937 if ((C->getSExtValue() >= -0x80000000LL) &&
25938 (C->getSExtValue() <= 0x7fffffffLL))
25939 weight = CW_Constant;
25943 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25944 if (C->getZExtValue() <= 0xffffffff)
25945 weight = CW_Constant;
25952 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25953 /// with another that has more specific requirements based on the type of the
25954 /// corresponding operand.
25955 const char *X86TargetLowering::
25956 LowerXConstraint(EVT ConstraintVT) const {
25957 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25958 // 'f' like normal targets.
25959 if (ConstraintVT.isFloatingPoint()) {
25960 if (Subtarget->hasSSE2())
25962 if (Subtarget->hasSSE1())
25966 return TargetLowering::LowerXConstraint(ConstraintVT);
25969 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25970 /// vector. If it is invalid, don't add anything to Ops.
25971 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25972 std::string &Constraint,
25973 std::vector<SDValue>&Ops,
25974 SelectionDAG &DAG) const {
25977 // Only support length 1 constraints for now.
25978 if (Constraint.length() > 1) return;
25980 char ConstraintLetter = Constraint[0];
25981 switch (ConstraintLetter) {
25984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25985 if (C->getZExtValue() <= 31) {
25986 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25987 Op.getValueType());
25993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25994 if (C->getZExtValue() <= 63) {
25995 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25996 Op.getValueType());
26002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26003 if (isInt<8>(C->getSExtValue())) {
26004 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26005 Op.getValueType());
26011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26012 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26013 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26014 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26015 Op.getValueType());
26021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26022 if (C->getZExtValue() <= 3) {
26023 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26024 Op.getValueType());
26030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26031 if (C->getZExtValue() <= 255) {
26032 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26033 Op.getValueType());
26039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26040 if (C->getZExtValue() <= 127) {
26041 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26042 Op.getValueType());
26048 // 32-bit signed value
26049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26050 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26051 C->getSExtValue())) {
26052 // Widen to 64 bits here to get it sign extended.
26053 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26056 // FIXME gcc accepts some relocatable values here too, but only in certain
26057 // memory models; it's complicated.
26062 // 32-bit unsigned value
26063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26064 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26065 C->getZExtValue())) {
26066 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26067 Op.getValueType());
26071 // FIXME gcc accepts some relocatable values here too, but only in certain
26072 // memory models; it's complicated.
26076 // Literal immediates are always ok.
26077 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26078 // Widen to 64 bits here to get it sign extended.
26079 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26083 // In any sort of PIC mode addresses need to be computed at runtime by
26084 // adding in a register or some sort of table lookup. These can't
26085 // be used as immediates.
26086 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26089 // If we are in non-pic codegen mode, we allow the address of a global (with
26090 // an optional displacement) to be used with 'i'.
26091 GlobalAddressSDNode *GA = nullptr;
26092 int64_t Offset = 0;
26094 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26096 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26097 Offset += GA->getOffset();
26099 } else if (Op.getOpcode() == ISD::ADD) {
26100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26101 Offset += C->getZExtValue();
26102 Op = Op.getOperand(0);
26105 } else if (Op.getOpcode() == ISD::SUB) {
26106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26107 Offset += -C->getZExtValue();
26108 Op = Op.getOperand(0);
26113 // Otherwise, this isn't something we can handle, reject it.
26117 const GlobalValue *GV = GA->getGlobal();
26118 // If we require an extra load to get this address, as in PIC mode, we
26119 // can't accept it.
26120 if (isGlobalStubReference(
26121 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26124 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26125 GA->getValueType(0), Offset);
26130 if (Result.getNode()) {
26131 Ops.push_back(Result);
26134 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26137 std::pair<unsigned, const TargetRegisterClass *>
26138 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26139 StringRef Constraint,
26141 // First, see if this is a constraint that directly corresponds to an LLVM
26143 if (Constraint.size() == 1) {
26144 // GCC Constraint Letters
26145 switch (Constraint[0]) {
26147 // TODO: Slight differences here in allocation order and leaving
26148 // RIP in the class. Do they matter any more here than they do
26149 // in the normal allocation?
26150 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26151 if (Subtarget->is64Bit()) {
26152 if (VT == MVT::i32 || VT == MVT::f32)
26153 return std::make_pair(0U, &X86::GR32RegClass);
26154 if (VT == MVT::i16)
26155 return std::make_pair(0U, &X86::GR16RegClass);
26156 if (VT == MVT::i8 || VT == MVT::i1)
26157 return std::make_pair(0U, &X86::GR8RegClass);
26158 if (VT == MVT::i64 || VT == MVT::f64)
26159 return std::make_pair(0U, &X86::GR64RegClass);
26162 // 32-bit fallthrough
26163 case 'Q': // Q_REGS
26164 if (VT == MVT::i32 || VT == MVT::f32)
26165 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26166 if (VT == MVT::i16)
26167 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26168 if (VT == MVT::i8 || VT == MVT::i1)
26169 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26170 if (VT == MVT::i64)
26171 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26173 case 'r': // GENERAL_REGS
26174 case 'l': // INDEX_REGS
26175 if (VT == MVT::i8 || VT == MVT::i1)
26176 return std::make_pair(0U, &X86::GR8RegClass);
26177 if (VT == MVT::i16)
26178 return std::make_pair(0U, &X86::GR16RegClass);
26179 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26180 return std::make_pair(0U, &X86::GR32RegClass);
26181 return std::make_pair(0U, &X86::GR64RegClass);
26182 case 'R': // LEGACY_REGS
26183 if (VT == MVT::i8 || VT == MVT::i1)
26184 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26185 if (VT == MVT::i16)
26186 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26187 if (VT == MVT::i32 || !Subtarget->is64Bit())
26188 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26189 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26190 case 'f': // FP Stack registers.
26191 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26192 // value to the correct fpstack register class.
26193 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26194 return std::make_pair(0U, &X86::RFP32RegClass);
26195 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26196 return std::make_pair(0U, &X86::RFP64RegClass);
26197 return std::make_pair(0U, &X86::RFP80RegClass);
26198 case 'y': // MMX_REGS if MMX allowed.
26199 if (!Subtarget->hasMMX()) break;
26200 return std::make_pair(0U, &X86::VR64RegClass);
26201 case 'Y': // SSE_REGS if SSE2 allowed
26202 if (!Subtarget->hasSSE2()) break;
26204 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26205 if (!Subtarget->hasSSE1()) break;
26207 switch (VT.SimpleTy) {
26209 // Scalar SSE types.
26212 return std::make_pair(0U, &X86::FR32RegClass);
26215 return std::make_pair(0U, &X86::FR64RegClass);
26223 return std::make_pair(0U, &X86::VR128RegClass);
26231 return std::make_pair(0U, &X86::VR256RegClass);
26236 return std::make_pair(0U, &X86::VR512RegClass);
26242 // Use the default implementation in TargetLowering to convert the register
26243 // constraint into a member of a register class.
26244 std::pair<unsigned, const TargetRegisterClass*> Res;
26245 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26247 // Not found as a standard register?
26249 // Map st(0) -> st(7) -> ST0
26250 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26251 tolower(Constraint[1]) == 's' &&
26252 tolower(Constraint[2]) == 't' &&
26253 Constraint[3] == '(' &&
26254 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26255 Constraint[5] == ')' &&
26256 Constraint[6] == '}') {
26258 Res.first = X86::FP0+Constraint[4]-'0';
26259 Res.second = &X86::RFP80RegClass;
26263 // GCC allows "st(0)" to be called just plain "st".
26264 if (StringRef("{st}").equals_lower(Constraint)) {
26265 Res.first = X86::FP0;
26266 Res.second = &X86::RFP80RegClass;
26271 if (StringRef("{flags}").equals_lower(Constraint)) {
26272 Res.first = X86::EFLAGS;
26273 Res.second = &X86::CCRRegClass;
26277 // 'A' means EAX + EDX.
26278 if (Constraint == "A") {
26279 Res.first = X86::EAX;
26280 Res.second = &X86::GR32_ADRegClass;
26286 // Otherwise, check to see if this is a register class of the wrong value
26287 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26288 // turn into {ax},{dx}.
26289 // MVT::Other is used to specify clobber names.
26290 if (Res.second->hasType(VT) || VT == MVT::Other)
26291 return Res; // Correct type already, nothing to do.
26293 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26294 // return "eax". This should even work for things like getting 64bit integer
26295 // registers when given an f64 type.
26296 const TargetRegisterClass *Class = Res.second;
26297 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26298 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26299 unsigned Size = VT.getSizeInBits();
26300 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26301 : Size == 16 ? MVT::i16
26302 : Size == 32 ? MVT::i32
26303 : Size == 64 ? MVT::i64
26305 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26307 Res.first = DestReg;
26308 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26309 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26310 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26311 : &X86::GR64RegClass;
26312 assert(Res.second->contains(Res.first) && "Register in register class");
26314 // No register found/type mismatch.
26316 Res.second = nullptr;
26318 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26319 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26320 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26321 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26322 Class == &X86::VR512RegClass) {
26323 // Handle references to XMM physical registers that got mapped into the
26324 // wrong class. This can happen with constraints like {xmm0} where the
26325 // target independent register mapper will just pick the first match it can
26326 // find, ignoring the required type.
26328 if (VT == MVT::f32 || VT == MVT::i32)
26329 Res.second = &X86::FR32RegClass;
26330 else if (VT == MVT::f64 || VT == MVT::i64)
26331 Res.second = &X86::FR64RegClass;
26332 else if (X86::VR128RegClass.hasType(VT))
26333 Res.second = &X86::VR128RegClass;
26334 else if (X86::VR256RegClass.hasType(VT))
26335 Res.second = &X86::VR256RegClass;
26336 else if (X86::VR512RegClass.hasType(VT))
26337 Res.second = &X86::VR512RegClass;
26339 // Type mismatch and not a clobber: Return an error;
26341 Res.second = nullptr;
26348 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26349 const AddrMode &AM, Type *Ty,
26350 unsigned AS) const {
26351 // Scaling factors are not free at all.
26352 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26353 // will take 2 allocations in the out of order engine instead of 1
26354 // for plain addressing mode, i.e. inst (reg1).
26356 // vaddps (%rsi,%drx), %ymm0, %ymm1
26357 // Requires two allocations (one for the load, one for the computation)
26359 // vaddps (%rsi), %ymm0, %ymm1
26360 // Requires just 1 allocation, i.e., freeing allocations for other operations
26361 // and having less micro operations to execute.
26363 // For some X86 architectures, this is even worse because for instance for
26364 // stores, the complex addressing mode forces the instruction to use the
26365 // "load" ports instead of the dedicated "store" port.
26366 // E.g., on Haswell:
26367 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26368 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26369 if (isLegalAddressingMode(DL, AM, Ty, AS))
26370 // Scale represents reg2 * scale, thus account for 1
26371 // as soon as we use a second register.
26372 return AM.Scale != 0;
26376 bool X86TargetLowering::isTargetFTOL() const {
26377 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();