1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168 // f32/f64 are legal, f80 is custom.
169 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 } else if (!Subtarget->useSoftFloat()) {
174 // We have an algorithm for SSE2->double, and we turn this into a
175 // 64-bit FILD followed by conditional FADD for other targets.
176 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
177 // We have an algorithm for SSE2, and we turn this into a 64-bit
178 // FILD or VCVTUSI2SS/SD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
182 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
187 if (!Subtarget->useSoftFloat()) {
188 // SSE has no i16 to fp conversion, only i32
189 if (X86ScalarSSEf32) {
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
191 // f32 and f64 cases are Legal, f80 case is not
192 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
202 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
203 // are Legal, f80 is custom lowered.
204 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
207 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
209 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
212 if (X86ScalarSSEf32) {
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
214 // f32 and f64 cases are Legal, f80 case is not
215 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
221 // Handle FP_TO_UINT by promoting the destination to a larger signed
223 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
224 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
225 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
227 if (Subtarget->is64Bit()) {
228 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
233 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
234 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 } else if (!Subtarget->useSoftFloat()) {
237 // Since AVX is a superset of SSE3, only check for SSE here.
238 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239 // Expand FP_TO_UINT into a select.
240 // FIXME: We would like to use a Custom expander here eventually to do
241 // the optimal thing for SSE vs. the default expansion in the legalizer.
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
244 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
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);
249 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
252 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253 if (!X86ScalarSSEf64) {
254 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
255 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
258 // Without SSE, i64->f64 goes through memory.
259 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
263 // Scalar integer divide and remainder are lowered to use operations that
264 // produce two results, to match the available instructions. This exposes
265 // the two-result form to trivial CSE, which is able to combine x/y and x%y
266 // into a single instruction.
268 // Scalar integer multiply-high is also lowered to use two-result
269 // operations, to match the available instructions. However, plain multiply
270 // (low) operations are left as Legal, as there are single-result
271 // instructions for this in x86. Using the two-result multiply instructions
272 // when both high and low results are needed must be arranged by dagcombine.
273 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
275 setOperationAction(ISD::MULHS, VT, Expand);
276 setOperationAction(ISD::MULHU, VT, Expand);
277 setOperationAction(ISD::SDIV, VT, Expand);
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SREM, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
282 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283 setOperationAction(ISD::ADDC, VT, Custom);
284 setOperationAction(ISD::ADDE, VT, Custom);
285 setOperationAction(ISD::SUBC, VT, Custom);
286 setOperationAction(ISD::SUBE, VT, Custom);
289 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
291 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
292 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
293 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
294 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
295 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
296 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
301 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
309 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
310 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
312 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314 // is. We should promote the value to 64-bits to solve this.
315 // This is what the CRT headers do - `fmodf` is an inline header
316 // function casting to f64 and calling `fmod`.
317 setOperationAction(ISD::FREM , MVT::f32 , Promote);
319 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->isTarget64BitLP64()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit()) {
502 setOperationAction(ISD::VAARG , MVT::Other, Custom);
503 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
505 // TargetInfo::CharPtrBuiltinVaList
506 setOperationAction(ISD::VAARG , MVT::Other, Expand);
507 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
510 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
511 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
513 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
515 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520 // f32 and f64 use SSE.
521 // Set up the FP register classes.
522 addRegisterClass(MVT::f32, &X86::FR32RegClass);
523 addRegisterClass(MVT::f64, &X86::FR64RegClass);
525 // Use ANDPD to simulate FABS.
526 setOperationAction(ISD::FABS , MVT::f64, Custom);
527 setOperationAction(ISD::FABS , MVT::f32, Custom);
529 // Use XORP to simulate FNEG.
530 setOperationAction(ISD::FNEG , MVT::f64, Custom);
531 setOperationAction(ISD::FNEG , MVT::f32, Custom);
533 // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537 // Lower this to FGETSIGNx86 plus an AND.
538 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541 // We don't support sin/cos/fmod
542 setOperationAction(ISD::FSIN , MVT::f64, Expand);
543 setOperationAction(ISD::FCOS , MVT::f64, Expand);
544 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545 setOperationAction(ISD::FSIN , MVT::f32, Expand);
546 setOperationAction(ISD::FCOS , MVT::f32, Expand);
547 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549 // Expand FP immediates into loads from the stack, except for the special
551 addLegalFPImmediate(APFloat(+0.0)); // xorpd
552 addLegalFPImmediate(APFloat(+0.0f)); // xorps
553 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554 // Use SSE for f32, x87 for f64.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, &X86::FR32RegClass);
557 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559 // Use ANDPS to simulate FABS.
560 setOperationAction(ISD::FABS , MVT::f32, Custom);
562 // Use XORP to simulate FNEG.
563 setOperationAction(ISD::FNEG , MVT::f32, Custom);
565 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
567 // Use ANDPS and ORPS to simulate FCOPYSIGN.
568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571 // We don't support sin/cos/fmod
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
574 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576 // Special cases we handle for FP constants.
577 addLegalFPImmediate(APFloat(+0.0f)); // xorps
578 addLegalFPImmediate(APFloat(+0.0)); // FLD0
579 addLegalFPImmediate(APFloat(+1.0)); // FLD1
580 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583 if (!TM.Options.UnsafeFPMath) {
584 setOperationAction(ISD::FSIN , MVT::f64, Expand);
585 setOperationAction(ISD::FCOS , MVT::f64, Expand);
586 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588 } else if (!Subtarget->useSoftFloat()) {
589 // f32 and f64 in x87.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
595 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599 if (!TM.Options.UnsafeFPMath) {
600 setOperationAction(ISD::FSIN , MVT::f64, Expand);
601 setOperationAction(ISD::FSIN , MVT::f32, Expand);
602 setOperationAction(ISD::FCOS , MVT::f64, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
604 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607 addLegalFPImmediate(APFloat(+0.0)); // FLD0
608 addLegalFPImmediate(APFloat(+1.0)); // FLD1
609 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
617 // We don't support FMA.
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FMA, MVT::f32, Expand);
621 // Long double always uses X87.
622 if (!Subtarget->useSoftFloat()) {
623 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628 addLegalFPImmediate(TmpFlt); // FLD0
630 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
633 APFloat TmpFlt2(+1.0);
634 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636 addLegalFPImmediate(TmpFlt2); // FLD1
637 TmpFlt2.changeSign();
638 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
641 if (!TM.Options.UnsafeFPMath) {
642 setOperationAction(ISD::FSIN , MVT::f80, Expand);
643 setOperationAction(ISD::FCOS , MVT::f80, Expand);
644 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
647 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
649 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650 setOperationAction(ISD::FRINT, MVT::f80, Expand);
651 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652 setOperationAction(ISD::FMA, MVT::f80, Expand);
655 // Always use a library call for pow.
656 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
657 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
660 setOperationAction(ISD::FLOG, MVT::f80, Expand);
661 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663 setOperationAction(ISD::FEXP, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668 // First set operation action for all vector types to either promote
669 // (for widening) or expand (for scalarization). Then we will selectively
670 // turn on ones that can be effectively codegen'd.
671 for (MVT VT : MVT::vector_valuetypes()) {
672 setOperationAction(ISD::ADD , VT, Expand);
673 setOperationAction(ISD::SUB , VT, Expand);
674 setOperationAction(ISD::FADD, VT, Expand);
675 setOperationAction(ISD::FNEG, VT, Expand);
676 setOperationAction(ISD::FSUB, VT, Expand);
677 setOperationAction(ISD::MUL , VT, Expand);
678 setOperationAction(ISD::FMUL, VT, Expand);
679 setOperationAction(ISD::SDIV, VT, Expand);
680 setOperationAction(ISD::UDIV, VT, Expand);
681 setOperationAction(ISD::FDIV, VT, Expand);
682 setOperationAction(ISD::SREM, VT, Expand);
683 setOperationAction(ISD::UREM, VT, Expand);
684 setOperationAction(ISD::LOAD, VT, Expand);
685 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::FABS, VT, Expand);
691 setOperationAction(ISD::FSIN, VT, Expand);
692 setOperationAction(ISD::FSINCOS, VT, Expand);
693 setOperationAction(ISD::FCOS, VT, Expand);
694 setOperationAction(ISD::FSINCOS, VT, Expand);
695 setOperationAction(ISD::FREM, VT, Expand);
696 setOperationAction(ISD::FMA, VT, Expand);
697 setOperationAction(ISD::FPOWI, VT, Expand);
698 setOperationAction(ISD::FSQRT, VT, Expand);
699 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700 setOperationAction(ISD::FFLOOR, VT, Expand);
701 setOperationAction(ISD::FCEIL, VT, Expand);
702 setOperationAction(ISD::FTRUNC, VT, Expand);
703 setOperationAction(ISD::FRINT, VT, Expand);
704 setOperationAction(ISD::FNEARBYINT, VT, Expand);
705 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706 setOperationAction(ISD::MULHS, VT, Expand);
707 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708 setOperationAction(ISD::MULHU, VT, Expand);
709 setOperationAction(ISD::SDIVREM, VT, Expand);
710 setOperationAction(ISD::UDIVREM, VT, Expand);
711 setOperationAction(ISD::FPOW, VT, Expand);
712 setOperationAction(ISD::CTPOP, VT, Expand);
713 setOperationAction(ISD::CTTZ, VT, Expand);
714 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715 setOperationAction(ISD::CTLZ, VT, Expand);
716 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717 setOperationAction(ISD::SHL, VT, Expand);
718 setOperationAction(ISD::SRA, VT, Expand);
719 setOperationAction(ISD::SRL, VT, Expand);
720 setOperationAction(ISD::ROTL, VT, Expand);
721 setOperationAction(ISD::ROTR, VT, Expand);
722 setOperationAction(ISD::BSWAP, VT, Expand);
723 setOperationAction(ISD::SETCC, VT, Expand);
724 setOperationAction(ISD::FLOG, VT, Expand);
725 setOperationAction(ISD::FLOG2, VT, Expand);
726 setOperationAction(ISD::FLOG10, VT, Expand);
727 setOperationAction(ISD::FEXP, VT, Expand);
728 setOperationAction(ISD::FEXP2, VT, Expand);
729 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734 setOperationAction(ISD::TRUNCATE, VT, Expand);
735 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738 setOperationAction(ISD::VSELECT, VT, Expand);
739 setOperationAction(ISD::SELECT_CC, VT, Expand);
740 for (MVT InnerVT : MVT::vector_valuetypes()) {
741 setTruncStoreAction(InnerVT, VT, Expand);
743 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747 // types, we have to deal with them whether we ask for Expansion or not.
748 // Setting Expand causes its own optimisation problems though, so leave
750 if (VT.getVectorElementType() == MVT::i1)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754 // split/scalarized right now.
755 if (VT.getVectorElementType() == MVT::f16)
756 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
760 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761 // with -msoft-float, disable use of MMX as well.
762 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764 // No operations on x86mmx supported, everything uses intrinsics.
767 // MMX-sized vectors (other than x86mmx) are expected to be expanded
768 // into smaller operations.
769 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770 setOperationAction(ISD::MULHS, MMXTy, Expand);
771 setOperationAction(ISD::AND, MMXTy, Expand);
772 setOperationAction(ISD::OR, MMXTy, Expand);
773 setOperationAction(ISD::XOR, MMXTy, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
775 setOperationAction(ISD::SELECT, MMXTy, Expand);
776 setOperationAction(ISD::BITCAST, MMXTy, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
784 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
785 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
786 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
787 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
788 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
789 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
790 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
791 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
792 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
793 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
794 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
796 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
799 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803 // registers cannot be used even for integer operations.
804 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
810 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
811 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
812 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
813 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
814 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
815 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
816 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
817 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
818 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
819 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
831 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
833 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
834 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
835 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
836 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
838 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
839 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
840 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
841 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
844 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
851 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
852 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
854 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
855 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
857 // ISD::CTTZ v2i64 - scalarization is faster.
858 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
859 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
861 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
863 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865 MVT VT = (MVT::SimpleValueType)i;
866 // Do not attempt to custom lower non-power-of-2 vectors
867 if (!isPowerOf2_32(VT.getVectorNumElements()))
869 // Do not attempt to custom lower non-128-bit vectors
870 if (!VT.is128BitVector())
872 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
874 setOperationAction(ISD::VSELECT, VT, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
878 // We support custom legalizing of sext and anyext loads for specific
879 // memory vector types which we can load as a scalar (or sequence of
880 // scalars) and extend in-register to a legal 128-bit vector type. For sext
881 // loads these must work with a single scalar load.
882 for (MVT VT : MVT::integer_vector_valuetypes()) {
883 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
897 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
898 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
899 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910 MVT VT = (MVT::SimpleValueType)i;
912 // Do not attempt to promote non-128-bit vectors
913 if (!VT.is128BitVector())
916 setOperationAction(ISD::AND, VT, Promote);
917 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
918 setOperationAction(ISD::OR, VT, Promote);
919 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
920 setOperationAction(ISD::XOR, VT, Promote);
921 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
922 setOperationAction(ISD::LOAD, VT, Promote);
923 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
924 setOperationAction(ISD::SELECT, VT, Promote);
925 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928 // Custom lower v2i64 and v2f64 selects.
929 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
930 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
931 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
932 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941 // As there is no 64-bit GPR available, we need build a special custom
942 // sequence to convert from v2i32 to v2f32.
943 if (!Subtarget->is64Bit())
944 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
946 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
949 for (MVT VT : MVT::fp_vector_valuetypes())
950 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
953 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
957 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
960 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
961 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
962 setOperationAction(ISD::FRINT, RoundedTy, Legal);
963 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
966 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
967 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
968 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
969 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
971 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
972 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
973 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 // We directly match byte blends in the backend as they match the VSELECT
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
982 // SSE41 brings specific instructions for doing vector sign extend even in
983 // cases where we don't have SRA.
984 for (MVT VT : MVT::integer_vector_valuetypes()) {
985 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005 // i8 and i16 vectors are custom because the source register and source
1006 // source memory operand types are not the same width. f32 vectors are
1007 // custom since the immediate controlling the insert encodes additional
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019 // FIXME: these should be Legal, but that's only for the case where
1020 // the index is constant. For now custom expand to deal with that.
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1027 if (Subtarget->hasSSE2()) {
1028 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1041 // In the customized shift lowering, the legal cases in AVX2 will be
1043 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1044 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1049 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1053 if (Subtarget->hasXOP()) {
1054 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1055 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1056 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1064 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1065 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1066 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1067 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1072 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1073 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1074 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1076 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1077 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1078 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1087 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1090 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1091 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1100 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1102 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1103 // even though v8i16 is a legal type.
1104 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1105 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1106 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1108 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1109 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1110 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1112 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1113 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1115 for (MVT VT : MVT::fp_vector_valuetypes())
1116 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1119 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1121 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1122 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1124 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1125 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1127 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1128 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1132 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1133 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1136 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1137 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1139 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1140 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1142 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1143 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1145 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1146 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1149 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1150 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1154 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1155 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1158 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1163 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1164 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::f64, Legal);
1172 if (Subtarget->hasInt256()) {
1173 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1175 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1176 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1178 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1179 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1180 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1181 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1183 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1184 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1185 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1186 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1188 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1189 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1190 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1191 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1193 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1194 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1196 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1197 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1199 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1200 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1202 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1203 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1206 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1207 // when we have a 256bit-wide blend with immediate.
1208 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1211 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1212 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1218 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1219 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1225 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1226 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1227 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1228 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1232 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1233 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1235 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1236 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1237 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1238 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1240 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1241 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1243 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1244 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1247 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1249 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1250 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1254 // In the customized shift lowering, the legal cases in AVX2 will be
1256 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (MVT VT : MVT::vector_valuetypes()) {
1267 if (VT.getScalarSizeInBits() >= 32) {
1268 setOperationAction(ISD::MLOAD, VT, Legal);
1269 setOperationAction(ISD::MSTORE, VT, Legal);
1271 // Extract subvector is special because the value type
1272 // (result) is 128-bit but the source is 256-bit wide.
1273 if (VT.is128BitVector()) {
1274 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276 // Do not attempt to custom lower other non-256-bit vectors
1277 if (!VT.is256BitVector())
1280 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1281 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1282 setOperationAction(ISD::VSELECT, VT, Custom);
1283 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1284 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1286 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1287 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1290 if (Subtarget->hasInt256())
1291 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295 MVT VT = (MVT::SimpleValueType)i;
1297 // Do not attempt to promote non-256-bit vectors
1298 if (!VT.is256BitVector())
1301 setOperationAction(ISD::AND, VT, Promote);
1302 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1303 setOperationAction(ISD::OR, VT, Promote);
1304 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1305 setOperationAction(ISD::XOR, VT, Promote);
1306 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1307 setOperationAction(ISD::LOAD, VT, Promote);
1308 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1309 setOperationAction(ISD::SELECT, VT, Promote);
1310 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1314 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1315 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1318 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1320 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1321 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1322 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1324 for (MVT VT : MVT::fp_vector_valuetypes())
1325 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1329 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1330 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1331 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1332 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1333 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1334 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1335 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1336 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1337 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1338 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1340 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1341 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1342 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1343 setOperationAction(ISD::XOR, MVT::i1, Legal);
1344 setOperationAction(ISD::OR, MVT::i1, Legal);
1345 setOperationAction(ISD::AND, MVT::i1, Legal);
1346 setOperationAction(ISD::SUB, MVT::i1, Custom);
1347 setOperationAction(ISD::ADD, MVT::i1, Custom);
1348 setOperationAction(ISD::MUL, MVT::i1, Custom);
1349 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1350 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1351 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1352 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1353 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1355 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1357 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1358 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1359 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1360 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1362 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1364 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1366 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1367 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1368 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1369 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1371 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1374 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1379 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1385 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1386 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1388 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1389 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1390 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1391 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1392 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1393 if (Subtarget->hasVLX()){
1394 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1395 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1396 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1397 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1398 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1400 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1401 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1402 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1403 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1404 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1406 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1407 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1408 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1409 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1410 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1411 if (Subtarget->hasDQI()) {
1412 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1413 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1415 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1416 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1417 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1418 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1419 if (Subtarget->hasVLX()) {
1420 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1421 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1422 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1423 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1424 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1425 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1426 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1427 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1430 if (Subtarget->hasVLX()) {
1431 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1432 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1433 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1434 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1435 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1436 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1437 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1438 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1440 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1441 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1442 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1443 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1444 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1445 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1446 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1447 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1448 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1449 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1450 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1452 if (Subtarget->hasDQI()) {
1453 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1456 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1457 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1458 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1459 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1460 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1461 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1462 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1463 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1464 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1465 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1467 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1468 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1469 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1470 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1473 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1474 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1476 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1478 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1480 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1481 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1482 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1483 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1484 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1485 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1486 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1487 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1488 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1490 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1491 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1492 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1493 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1494 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1495 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1496 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1497 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1499 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1500 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1502 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1503 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1505 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1507 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1508 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1510 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1511 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1513 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1514 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1516 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1517 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1518 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1519 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1520 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1521 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1523 if (Subtarget->hasCDI()) {
1524 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1525 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1526 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1527 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1529 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1530 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1531 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1532 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1533 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Custom);
1534 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Custom);
1535 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Custom);
1536 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Custom);
1538 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1539 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1541 if (Subtarget->hasVLX()) {
1542 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1543 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1544 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1545 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1546 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1547 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1548 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1549 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1551 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1552 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1553 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1554 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1556 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1557 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1558 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1559 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1560 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Custom);
1561 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Custom);
1562 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Custom);
1563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Custom);
1565 } // Subtarget->hasCDI()
1567 if (Subtarget->hasDQI()) {
1568 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1569 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1570 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1572 // Custom lower several nodes.
1573 for (MVT VT : MVT::vector_valuetypes()) {
1574 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1576 setOperationAction(ISD::AND, VT, Legal);
1577 setOperationAction(ISD::OR, VT, Legal);
1578 setOperationAction(ISD::XOR, VT, Legal);
1580 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1581 setOperationAction(ISD::MGATHER, VT, Custom);
1582 setOperationAction(ISD::MSCATTER, VT, Custom);
1584 // Extract subvector is special because the value type
1585 // (result) is 256/128-bit but the source is 512-bit wide.
1586 if (VT.is128BitVector() || VT.is256BitVector()) {
1587 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1589 if (VT.getVectorElementType() == MVT::i1)
1590 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1592 // Do not attempt to custom lower other non-512-bit vectors
1593 if (!VT.is512BitVector())
1596 if (EltSize >= 32) {
1597 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1598 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1599 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1600 setOperationAction(ISD::VSELECT, VT, Legal);
1601 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1602 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1603 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1604 setOperationAction(ISD::MLOAD, VT, Legal);
1605 setOperationAction(ISD::MSTORE, VT, Legal);
1608 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1609 MVT VT = (MVT::SimpleValueType)i;
1611 // Do not attempt to promote non-512-bit vectors.
1612 if (!VT.is512BitVector())
1615 setOperationAction(ISD::SELECT, VT, Promote);
1616 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1620 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1621 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1622 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1624 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1625 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1627 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1628 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1629 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1630 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1631 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1632 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1633 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1634 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1635 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1636 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1637 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1638 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Legal);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Legal);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1641 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1642 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1645 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1646 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1648 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1649 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1650 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1651 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1652 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1653 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1656 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1657 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1662 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1663 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1664 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1665 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1666 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1670 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1671 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1672 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1673 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1674 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1675 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1676 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1677 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1679 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1680 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1681 if (Subtarget->hasVLX())
1682 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1684 if (Subtarget->hasCDI()) {
1685 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1686 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1687 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Custom);
1691 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1692 const MVT VT = (MVT::SimpleValueType)i;
1694 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1696 // Do not attempt to promote non-512-bit vectors.
1697 if (!VT.is512BitVector())
1701 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1702 setOperationAction(ISD::VSELECT, VT, Legal);
1707 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1708 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1709 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1711 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1712 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1713 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1715 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1716 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1717 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1718 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1719 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1720 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1721 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1722 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1724 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1725 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1726 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1727 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1728 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1729 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1730 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1731 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1733 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1734 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1735 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1736 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1737 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1738 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1739 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1740 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1743 // We want to custom lower some of our intrinsics.
1744 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1745 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1746 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1747 if (!Subtarget->is64Bit())
1748 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1750 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1751 // handle type legalization for these operations here.
1753 // FIXME: We really should do custom legalization for addition and
1754 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1755 // than generic legalization for 64-bit multiplication-with-overflow, though.
1756 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1757 // Add/Sub/Mul with overflow operations are custom lowered.
1759 setOperationAction(ISD::SADDO, VT, Custom);
1760 setOperationAction(ISD::UADDO, VT, Custom);
1761 setOperationAction(ISD::SSUBO, VT, Custom);
1762 setOperationAction(ISD::USUBO, VT, Custom);
1763 setOperationAction(ISD::SMULO, VT, Custom);
1764 setOperationAction(ISD::UMULO, VT, Custom);
1767 if (!Subtarget->is64Bit()) {
1768 // These libcalls are not available in 32-bit.
1769 setLibcallName(RTLIB::SHL_I128, nullptr);
1770 setLibcallName(RTLIB::SRL_I128, nullptr);
1771 setLibcallName(RTLIB::SRA_I128, nullptr);
1774 // Combine sin / cos into one node or libcall if possible.
1775 if (Subtarget->hasSinCos()) {
1776 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1777 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1778 if (Subtarget->isTargetDarwin()) {
1779 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1780 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1781 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1782 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1786 if (Subtarget->isTargetWin64()) {
1787 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1788 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1789 setOperationAction(ISD::SREM, MVT::i128, Custom);
1790 setOperationAction(ISD::UREM, MVT::i128, Custom);
1791 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1792 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1795 // We have target-specific dag combine patterns for the following nodes:
1796 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1797 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1798 setTargetDAGCombine(ISD::BITCAST);
1799 setTargetDAGCombine(ISD::VSELECT);
1800 setTargetDAGCombine(ISD::SELECT);
1801 setTargetDAGCombine(ISD::SHL);
1802 setTargetDAGCombine(ISD::SRA);
1803 setTargetDAGCombine(ISD::SRL);
1804 setTargetDAGCombine(ISD::OR);
1805 setTargetDAGCombine(ISD::AND);
1806 setTargetDAGCombine(ISD::ADD);
1807 setTargetDAGCombine(ISD::FADD);
1808 setTargetDAGCombine(ISD::FSUB);
1809 setTargetDAGCombine(ISD::FMA);
1810 setTargetDAGCombine(ISD::SUB);
1811 setTargetDAGCombine(ISD::LOAD);
1812 setTargetDAGCombine(ISD::MLOAD);
1813 setTargetDAGCombine(ISD::STORE);
1814 setTargetDAGCombine(ISD::MSTORE);
1815 setTargetDAGCombine(ISD::ZERO_EXTEND);
1816 setTargetDAGCombine(ISD::ANY_EXTEND);
1817 setTargetDAGCombine(ISD::SIGN_EXTEND);
1818 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1819 setTargetDAGCombine(ISD::SINT_TO_FP);
1820 setTargetDAGCombine(ISD::UINT_TO_FP);
1821 setTargetDAGCombine(ISD::SETCC);
1822 setTargetDAGCombine(ISD::BUILD_VECTOR);
1823 setTargetDAGCombine(ISD::MUL);
1824 setTargetDAGCombine(ISD::XOR);
1826 computeRegisterProperties(Subtarget->getRegisterInfo());
1828 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1829 MaxStoresPerMemsetOptSize = 8;
1830 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1831 MaxStoresPerMemcpyOptSize = 4;
1832 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1833 MaxStoresPerMemmoveOptSize = 4;
1834 setPrefLoopAlignment(4); // 2^4 bytes.
1836 // A predictable cmov does not hurt on an in-order CPU.
1837 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1838 PredictableSelectIsExpensive = !Subtarget->isAtom();
1839 EnableExtLdPromotion = true;
1840 setPrefFunctionAlignment(4); // 2^4 bytes.
1842 verifyIntrinsicTables();
1845 // This has so far only been implemented for 64-bit MachO.
1846 bool X86TargetLowering::useLoadStackGuardNode() const {
1847 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1850 TargetLoweringBase::LegalizeTypeAction
1851 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1852 if (ExperimentalVectorWideningLegalization &&
1853 VT.getVectorNumElements() != 1 &&
1854 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1855 return TypeWidenVector;
1857 return TargetLoweringBase::getPreferredVectorAction(VT);
1860 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1863 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1865 const unsigned NumElts = VT.getVectorNumElements();
1866 const EVT EltVT = VT.getVectorElementType();
1867 if (VT.is512BitVector()) {
1868 if (Subtarget->hasAVX512())
1869 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1870 EltVT == MVT::f32 || EltVT == MVT::f64)
1872 case 8: return MVT::v8i1;
1873 case 16: return MVT::v16i1;
1875 if (Subtarget->hasBWI())
1876 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1878 case 32: return MVT::v32i1;
1879 case 64: return MVT::v64i1;
1883 if (VT.is256BitVector() || VT.is128BitVector()) {
1884 if (Subtarget->hasVLX())
1885 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1886 EltVT == MVT::f32 || EltVT == MVT::f64)
1888 case 2: return MVT::v2i1;
1889 case 4: return MVT::v4i1;
1890 case 8: return MVT::v8i1;
1892 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1893 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1895 case 8: return MVT::v8i1;
1896 case 16: return MVT::v16i1;
1897 case 32: return MVT::v32i1;
1901 return VT.changeVectorElementTypeToInteger();
1904 /// Helper for getByValTypeAlignment to determine
1905 /// the desired ByVal argument alignment.
1906 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1909 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1910 if (VTy->getBitWidth() == 128)
1912 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1913 unsigned EltAlign = 0;
1914 getMaxByValAlign(ATy->getElementType(), EltAlign);
1915 if (EltAlign > MaxAlign)
1916 MaxAlign = EltAlign;
1917 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1918 for (auto *EltTy : STy->elements()) {
1919 unsigned EltAlign = 0;
1920 getMaxByValAlign(EltTy, EltAlign);
1921 if (EltAlign > MaxAlign)
1922 MaxAlign = EltAlign;
1929 /// Return the desired alignment for ByVal aggregate
1930 /// function arguments in the caller parameter area. For X86, aggregates
1931 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1932 /// are at 4-byte boundaries.
1933 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1934 const DataLayout &DL) const {
1935 if (Subtarget->is64Bit()) {
1936 // Max of 8 and alignment of type.
1937 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1944 if (Subtarget->hasSSE1())
1945 getMaxByValAlign(Ty, Align);
1949 /// Returns the target specific optimal type for load
1950 /// and store operations as a result of memset, memcpy, and memmove
1951 /// lowering. If DstAlign is zero that means it's safe to destination
1952 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1953 /// means there isn't a need to check it against alignment requirement,
1954 /// probably because the source does not need to be loaded. If 'IsMemset' is
1955 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1956 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1957 /// source is constant so it does not need to be loaded.
1958 /// It returns EVT::Other if the type should be determined using generic
1959 /// target-independent logic.
1961 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1962 unsigned DstAlign, unsigned SrcAlign,
1963 bool IsMemset, bool ZeroMemset,
1965 MachineFunction &MF) const {
1966 const Function *F = MF.getFunction();
1967 if ((!IsMemset || ZeroMemset) &&
1968 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1970 (!Subtarget->isUnalignedMem16Slow() ||
1971 ((DstAlign == 0 || DstAlign >= 16) &&
1972 (SrcAlign == 0 || SrcAlign >= 16)))) {
1974 // FIXME: Check if unaligned 32-byte accesses are slow.
1975 if (Subtarget->hasInt256())
1977 if (Subtarget->hasFp256())
1980 if (Subtarget->hasSSE2())
1982 if (Subtarget->hasSSE1())
1984 } else if (!MemcpyStrSrc && Size >= 8 &&
1985 !Subtarget->is64Bit() &&
1986 Subtarget->hasSSE2()) {
1987 // Do not use f64 to lower memcpy if source is string constant. It's
1988 // better to use i32 to avoid the loads.
1992 // This is a compromise. If we reach here, unaligned accesses may be slow on
1993 // this target. However, creating smaller, aligned accesses could be even
1994 // slower and would certainly be a lot more code.
1995 if (Subtarget->is64Bit() && Size >= 8)
2000 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2002 return X86ScalarSSEf32;
2003 else if (VT == MVT::f64)
2004 return X86ScalarSSEf64;
2009 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2014 switch (VT.getSizeInBits()) {
2016 // 8-byte and under are always assumed to be fast.
2020 *Fast = !Subtarget->isUnalignedMem16Slow();
2023 *Fast = !Subtarget->isUnalignedMem32Slow();
2025 // TODO: What about AVX-512 (512-bit) accesses?
2028 // Misaligned accesses of any size are always allowed.
2032 /// Return the entry encoding for a jump table in the
2033 /// current function. The returned value is a member of the
2034 /// MachineJumpTableInfo::JTEntryKind enum.
2035 unsigned X86TargetLowering::getJumpTableEncoding() const {
2036 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2038 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2039 Subtarget->isPICStyleGOT())
2040 return MachineJumpTableInfo::EK_Custom32;
2042 // Otherwise, use the normal jump table encoding heuristics.
2043 return TargetLowering::getJumpTableEncoding();
2046 bool X86TargetLowering::useSoftFloat() const {
2047 return Subtarget->useSoftFloat();
2051 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2052 const MachineBasicBlock *MBB,
2053 unsigned uid,MCContext &Ctx) const{
2054 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2055 Subtarget->isPICStyleGOT());
2056 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2058 return MCSymbolRefExpr::create(MBB->getSymbol(),
2059 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2062 /// Returns relocation base for the given PIC jumptable.
2063 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2064 SelectionDAG &DAG) const {
2065 if (!Subtarget->is64Bit())
2066 // This doesn't have SDLoc associated with it, but is not really the
2067 // same as a Register.
2068 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2069 getPointerTy(DAG.getDataLayout()));
2073 /// This returns the relocation base for the given PIC jumptable,
2074 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2075 const MCExpr *X86TargetLowering::
2076 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2077 MCContext &Ctx) const {
2078 // X86-64 uses RIP relative addressing based on the jump table label.
2079 if (Subtarget->isPICStyleRIPRel())
2080 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2082 // Otherwise, the reference is relative to the PIC base.
2083 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2086 std::pair<const TargetRegisterClass *, uint8_t>
2087 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2089 const TargetRegisterClass *RRC = nullptr;
2091 switch (VT.SimpleTy) {
2093 return TargetLowering::findRepresentativeClass(TRI, VT);
2094 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2095 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2098 RRC = &X86::VR64RegClass;
2100 case MVT::f32: case MVT::f64:
2101 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2102 case MVT::v4f32: case MVT::v2f64:
2103 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2105 RRC = &X86::VR128RegClass;
2108 return std::make_pair(RRC, Cost);
2111 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2112 unsigned &Offset) const {
2113 if (!Subtarget->isTargetLinux())
2116 if (Subtarget->is64Bit()) {
2117 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2119 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2131 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2132 if (!Subtarget->isTargetAndroid())
2133 return TargetLowering::getSafeStackPointerLocation(IRB);
2135 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2136 // definition of TLS_SLOT_SAFESTACK in
2137 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2138 unsigned AddressSpace, Offset;
2139 if (Subtarget->is64Bit()) {
2140 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2142 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2152 return ConstantExpr::getIntToPtr(
2153 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2154 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2157 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2158 unsigned DestAS) const {
2159 assert(SrcAS != DestAS && "Expected different address spaces!");
2161 return SrcAS < 256 && DestAS < 256;
2164 //===----------------------------------------------------------------------===//
2165 // Return Value Calling Convention Implementation
2166 //===----------------------------------------------------------------------===//
2168 #include "X86GenCallingConv.inc"
2170 bool X86TargetLowering::CanLowerReturn(
2171 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2172 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2173 SmallVector<CCValAssign, 16> RVLocs;
2174 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2175 return CCInfo.CheckReturn(Outs, RetCC_X86);
2178 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2179 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2184 X86TargetLowering::LowerReturn(SDValue Chain,
2185 CallingConv::ID CallConv, bool isVarArg,
2186 const SmallVectorImpl<ISD::OutputArg> &Outs,
2187 const SmallVectorImpl<SDValue> &OutVals,
2188 SDLoc dl, SelectionDAG &DAG) const {
2189 MachineFunction &MF = DAG.getMachineFunction();
2190 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2192 SmallVector<CCValAssign, 16> RVLocs;
2193 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2194 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2197 SmallVector<SDValue, 6> RetOps;
2198 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2199 // Operand #1 = Bytes To Pop
2200 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2203 // Copy the result values into the output registers.
2204 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2205 CCValAssign &VA = RVLocs[i];
2206 assert(VA.isRegLoc() && "Can only return in registers!");
2207 SDValue ValToCopy = OutVals[i];
2208 EVT ValVT = ValToCopy.getValueType();
2210 // Promote values to the appropriate types.
2211 if (VA.getLocInfo() == CCValAssign::SExt)
2212 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2213 else if (VA.getLocInfo() == CCValAssign::ZExt)
2214 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2215 else if (VA.getLocInfo() == CCValAssign::AExt) {
2216 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2217 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2219 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2221 else if (VA.getLocInfo() == CCValAssign::BCvt)
2222 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2224 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2225 "Unexpected FP-extend for return value.");
2227 // If this is x86-64, and we disabled SSE, we can't return FP values,
2228 // or SSE or MMX vectors.
2229 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2230 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2231 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2232 report_fatal_error("SSE register return with SSE disabled");
2234 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2235 // llvm-gcc has never done it right and no one has noticed, so this
2236 // should be OK for now.
2237 if (ValVT == MVT::f64 &&
2238 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2239 report_fatal_error("SSE2 register return with SSE2 disabled");
2241 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2242 // the RET instruction and handled by the FP Stackifier.
2243 if (VA.getLocReg() == X86::FP0 ||
2244 VA.getLocReg() == X86::FP1) {
2245 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2246 // change the value to the FP stack register class.
2247 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2248 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2249 RetOps.push_back(ValToCopy);
2250 // Don't emit a copytoreg.
2254 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2255 // which is returned in RAX / RDX.
2256 if (Subtarget->is64Bit()) {
2257 if (ValVT == MVT::x86mmx) {
2258 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2259 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2260 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2262 // If we don't have SSE2 available, convert to v4f32 so the generated
2263 // register is legal.
2264 if (!Subtarget->hasSSE2())
2265 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2270 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2271 Flag = Chain.getValue(1);
2272 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2275 // All x86 ABIs require that for returning structs by value we copy
2276 // the sret argument into %rax/%eax (depending on ABI) for the return.
2277 // We saved the argument into a virtual register in the entry block,
2278 // so now we copy the value out and into %rax/%eax.
2280 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2281 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2282 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2283 // either case FuncInfo->setSRetReturnReg() will have been called.
2284 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2285 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2286 getPointerTy(MF.getDataLayout()));
2289 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2290 X86::RAX : X86::EAX;
2291 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2292 Flag = Chain.getValue(1);
2294 // RAX/EAX now acts like a return value.
2296 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2299 RetOps[0] = Chain; // Update chain.
2301 // Add the flag if we have it.
2303 RetOps.push_back(Flag);
2305 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2308 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2309 if (N->getNumValues() != 1)
2311 if (!N->hasNUsesOfValue(1, 0))
2314 SDValue TCChain = Chain;
2315 SDNode *Copy = *N->use_begin();
2316 if (Copy->getOpcode() == ISD::CopyToReg) {
2317 // If the copy has a glue operand, we conservatively assume it isn't safe to
2318 // perform a tail call.
2319 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2321 TCChain = Copy->getOperand(0);
2322 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2325 bool HasRet = false;
2326 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2328 if (UI->getOpcode() != X86ISD::RET_FLAG)
2330 // If we are returning more than one value, we can definitely
2331 // not make a tail call see PR19530
2332 if (UI->getNumOperands() > 4)
2334 if (UI->getNumOperands() == 4 &&
2335 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2348 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2349 ISD::NodeType ExtendKind) const {
2351 // TODO: Is this also valid on 32-bit?
2352 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2353 ReturnMVT = MVT::i8;
2355 ReturnMVT = MVT::i32;
2357 EVT MinVT = getRegisterType(Context, ReturnMVT);
2358 return VT.bitsLT(MinVT) ? MinVT : VT;
2361 /// Lower the result values of a call into the
2362 /// appropriate copies out of appropriate physical registers.
2365 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2366 CallingConv::ID CallConv, bool isVarArg,
2367 const SmallVectorImpl<ISD::InputArg> &Ins,
2368 SDLoc dl, SelectionDAG &DAG,
2369 SmallVectorImpl<SDValue> &InVals) const {
2371 // Assign locations to each value returned by this call.
2372 SmallVector<CCValAssign, 16> RVLocs;
2373 bool Is64Bit = Subtarget->is64Bit();
2374 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2376 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2378 // Copy all of the result registers out of their specified physreg.
2379 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2380 CCValAssign &VA = RVLocs[i];
2381 EVT CopyVT = VA.getLocVT();
2383 // If this is x86-64, and we disabled SSE, we can't return FP values
2384 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2385 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2386 report_fatal_error("SSE register return with SSE disabled");
2389 // If we prefer to use the value in xmm registers, copy it out as f80 and
2390 // use a truncate to move it from fp stack reg to xmm reg.
2391 bool RoundAfterCopy = false;
2392 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2393 isScalarFPTypeInSSEReg(VA.getValVT())) {
2395 RoundAfterCopy = (CopyVT != VA.getLocVT());
2398 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2399 CopyVT, InFlag).getValue(1);
2400 SDValue Val = Chain.getValue(0);
2403 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2404 // This truncation won't change the value.
2405 DAG.getIntPtrConstant(1, dl));
2407 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2408 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2410 InFlag = Chain.getValue(2);
2411 InVals.push_back(Val);
2417 //===----------------------------------------------------------------------===//
2418 // C & StdCall & Fast Calling Convention implementation
2419 //===----------------------------------------------------------------------===//
2420 // StdCall calling convention seems to be standard for many Windows' API
2421 // routines and around. It differs from C calling convention just a little:
2422 // callee should clean up the stack, not caller. Symbols should be also
2423 // decorated in some fancy way :) It doesn't support any vector arguments.
2424 // For info on fast calling convention see Fast Calling Convention (tail call)
2425 // implementation LowerX86_32FastCCCallTo.
2427 /// CallIsStructReturn - Determines whether a call uses struct return
2429 enum StructReturnType {
2434 static StructReturnType
2435 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2437 return NotStructReturn;
2439 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2440 if (!Flags.isSRet())
2441 return NotStructReturn;
2442 if (Flags.isInReg())
2443 return RegStructReturn;
2444 return StackStructReturn;
2447 /// Determines whether a function uses struct return semantics.
2448 static StructReturnType
2449 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2451 return NotStructReturn;
2453 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2454 if (!Flags.isSRet())
2455 return NotStructReturn;
2456 if (Flags.isInReg())
2457 return RegStructReturn;
2458 return StackStructReturn;
2461 /// Make a copy of an aggregate at address specified by "Src" to address
2462 /// "Dst" with size and alignment information specified by the specific
2463 /// parameter attribute. The copy will be passed as a byval function parameter.
2465 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2466 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2468 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2470 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2471 /*isVolatile*/false, /*AlwaysInline=*/true,
2472 /*isTailCall*/false,
2473 MachinePointerInfo(), MachinePointerInfo());
2476 /// Return true if the calling convention is one that we can guarantee TCO for.
2477 static bool canGuaranteeTCO(CallingConv::ID CC) {
2478 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2479 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2482 /// Return true if we might ever do TCO for calls with this calling convention.
2483 static bool mayTailCallThisCC(CallingConv::ID CC) {
2485 // C calling conventions:
2486 case CallingConv::C:
2487 case CallingConv::X86_64_Win64:
2488 case CallingConv::X86_64_SysV:
2489 // Callee pop conventions:
2490 case CallingConv::X86_ThisCall:
2491 case CallingConv::X86_StdCall:
2492 case CallingConv::X86_VectorCall:
2493 case CallingConv::X86_FastCall:
2496 return canGuaranteeTCO(CC);
2500 /// Return true if the function is being made into a tailcall target by
2501 /// changing its ABI.
2502 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2503 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2506 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2508 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2509 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2513 CallingConv::ID CalleeCC = CS.getCallingConv();
2514 if (!mayTailCallThisCC(CalleeCC))
2521 X86TargetLowering::LowerMemArgument(SDValue Chain,
2522 CallingConv::ID CallConv,
2523 const SmallVectorImpl<ISD::InputArg> &Ins,
2524 SDLoc dl, SelectionDAG &DAG,
2525 const CCValAssign &VA,
2526 MachineFrameInfo *MFI,
2528 // Create the nodes corresponding to a load from this parameter slot.
2529 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2530 bool AlwaysUseMutable = shouldGuaranteeTCO(
2531 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2532 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2535 // If value is passed by pointer we have address passed instead of the value
2537 bool ExtendedInMem = VA.isExtInLoc() &&
2538 VA.getValVT().getScalarType() == MVT::i1;
2540 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2541 ValVT = VA.getLocVT();
2543 ValVT = VA.getValVT();
2545 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2546 // changed with more analysis.
2547 // In case of tail call optimization mark all arguments mutable. Since they
2548 // could be overwritten by lowering of arguments in case of a tail call.
2549 if (Flags.isByVal()) {
2550 unsigned Bytes = Flags.getByValSize();
2551 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2552 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2553 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2555 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2556 VA.getLocMemOffset(), isImmutable);
2557 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2558 SDValue Val = DAG.getLoad(
2559 ValVT, dl, Chain, FIN,
2560 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2562 return ExtendedInMem ?
2563 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2567 // FIXME: Get this from tablegen.
2568 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2569 const X86Subtarget *Subtarget) {
2570 assert(Subtarget->is64Bit());
2572 if (Subtarget->isCallingConvWin64(CallConv)) {
2573 static const MCPhysReg GPR64ArgRegsWin64[] = {
2574 X86::RCX, X86::RDX, X86::R8, X86::R9
2576 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2579 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2580 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2582 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2585 // FIXME: Get this from tablegen.
2586 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2587 CallingConv::ID CallConv,
2588 const X86Subtarget *Subtarget) {
2589 assert(Subtarget->is64Bit());
2590 if (Subtarget->isCallingConvWin64(CallConv)) {
2591 // The XMM registers which might contain var arg parameters are shadowed
2592 // in their paired GPR. So we only need to save the GPR to their home
2594 // TODO: __vectorcall will change this.
2598 const Function *Fn = MF.getFunction();
2599 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2600 bool isSoftFloat = Subtarget->useSoftFloat();
2601 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2602 "SSE register cannot be used when SSE is disabled!");
2603 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2604 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2608 static const MCPhysReg XMMArgRegs64Bit[] = {
2609 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2610 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2612 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2615 SDValue X86TargetLowering::LowerFormalArguments(
2616 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2617 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2618 SmallVectorImpl<SDValue> &InVals) const {
2619 MachineFunction &MF = DAG.getMachineFunction();
2620 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2621 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2623 const Function* Fn = MF.getFunction();
2624 if (Fn->hasExternalLinkage() &&
2625 Subtarget->isTargetCygMing() &&
2626 Fn->getName() == "main")
2627 FuncInfo->setForceFramePointer(true);
2629 MachineFrameInfo *MFI = MF.getFrameInfo();
2630 bool Is64Bit = Subtarget->is64Bit();
2631 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2633 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2634 "Var args not supported with calling convention fastcc, ghc or hipe");
2636 // Assign locations to all of the incoming arguments.
2637 SmallVector<CCValAssign, 16> ArgLocs;
2638 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2640 // Allocate shadow area for Win64
2642 CCInfo.AllocateStack(32, 8);
2644 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2646 unsigned LastVal = ~0U;
2648 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2649 CCValAssign &VA = ArgLocs[i];
2650 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2652 assert(VA.getValNo() != LastVal &&
2653 "Don't support value assigned to multiple locs yet");
2655 LastVal = VA.getValNo();
2657 if (VA.isRegLoc()) {
2658 EVT RegVT = VA.getLocVT();
2659 const TargetRegisterClass *RC;
2660 if (RegVT == MVT::i32)
2661 RC = &X86::GR32RegClass;
2662 else if (Is64Bit && RegVT == MVT::i64)
2663 RC = &X86::GR64RegClass;
2664 else if (RegVT == MVT::f32)
2665 RC = &X86::FR32RegClass;
2666 else if (RegVT == MVT::f64)
2667 RC = &X86::FR64RegClass;
2668 else if (RegVT.is512BitVector())
2669 RC = &X86::VR512RegClass;
2670 else if (RegVT.is256BitVector())
2671 RC = &X86::VR256RegClass;
2672 else if (RegVT.is128BitVector())
2673 RC = &X86::VR128RegClass;
2674 else if (RegVT == MVT::x86mmx)
2675 RC = &X86::VR64RegClass;
2676 else if (RegVT == MVT::i1)
2677 RC = &X86::VK1RegClass;
2678 else if (RegVT == MVT::v8i1)
2679 RC = &X86::VK8RegClass;
2680 else if (RegVT == MVT::v16i1)
2681 RC = &X86::VK16RegClass;
2682 else if (RegVT == MVT::v32i1)
2683 RC = &X86::VK32RegClass;
2684 else if (RegVT == MVT::v64i1)
2685 RC = &X86::VK64RegClass;
2687 llvm_unreachable("Unknown argument type!");
2689 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2690 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2692 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2693 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2695 if (VA.getLocInfo() == CCValAssign::SExt)
2696 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2697 DAG.getValueType(VA.getValVT()));
2698 else if (VA.getLocInfo() == CCValAssign::ZExt)
2699 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2700 DAG.getValueType(VA.getValVT()));
2701 else if (VA.getLocInfo() == CCValAssign::BCvt)
2702 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2704 if (VA.isExtInLoc()) {
2705 // Handle MMX values passed in XMM regs.
2706 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2707 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2709 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2712 assert(VA.isMemLoc());
2713 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2716 // If value is passed via pointer - do a load.
2717 if (VA.getLocInfo() == CCValAssign::Indirect)
2718 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2719 MachinePointerInfo(), false, false, false, 0);
2721 InVals.push_back(ArgValue);
2724 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725 // All x86 ABIs require that for returning structs by value we copy the
2726 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2727 // the argument into a virtual register so that we can access it from the
2729 if (Ins[i].Flags.isSRet()) {
2730 unsigned Reg = FuncInfo->getSRetReturnReg();
2732 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2733 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2734 FuncInfo->setSRetReturnReg(Reg);
2736 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2737 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2742 unsigned StackSize = CCInfo.getNextStackOffset();
2743 // Align stack specially for tail calls.
2744 if (shouldGuaranteeTCO(CallConv,
2745 MF.getTarget().Options.GuaranteedTailCallOpt))
2746 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2748 // If the function takes variable number of arguments, make a frame index for
2749 // the start of the first vararg value... for expansion of llvm.va_start. We
2750 // can skip this if there are no va_start calls.
2751 if (MFI->hasVAStart() &&
2752 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2753 CallConv != CallingConv::X86_ThisCall))) {
2754 FuncInfo->setVarArgsFrameIndex(
2755 MFI->CreateFixedObject(1, StackSize, true));
2758 MachineModuleInfo &MMI = MF.getMMI();
2760 // Figure out if XMM registers are in use.
2761 assert(!(Subtarget->useSoftFloat() &&
2762 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2763 "SSE register cannot be used when SSE is disabled!");
2765 // 64-bit calling conventions support varargs and register parameters, so we
2766 // have to do extra work to spill them in the prologue.
2767 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2768 // Find the first unallocated argument registers.
2769 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2770 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2771 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2772 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2773 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2774 "SSE register cannot be used when SSE is disabled!");
2776 // Gather all the live in physical registers.
2777 SmallVector<SDValue, 6> LiveGPRs;
2778 SmallVector<SDValue, 8> LiveXMMRegs;
2780 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2781 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2783 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2785 if (!ArgXMMs.empty()) {
2786 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2787 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2788 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2789 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2790 LiveXMMRegs.push_back(
2791 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2796 // Get to the caller-allocated home save location. Add 8 to account
2797 // for the return address.
2798 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2799 FuncInfo->setRegSaveFrameIndex(
2800 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2801 // Fixup to set vararg frame on shadow area (4 x i64).
2803 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2805 // For X86-64, if there are vararg parameters that are passed via
2806 // registers, then we must store them to their spots on the stack so
2807 // they may be loaded by deferencing the result of va_next.
2808 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2809 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2810 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2811 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2814 // Store the integer parameter registers.
2815 SmallVector<SDValue, 8> MemOps;
2816 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2817 getPointerTy(DAG.getDataLayout()));
2818 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2819 for (SDValue Val : LiveGPRs) {
2820 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2821 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2823 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2824 MachinePointerInfo::getFixedStack(
2825 DAG.getMachineFunction(),
2826 FuncInfo->getRegSaveFrameIndex(), Offset),
2828 MemOps.push_back(Store);
2832 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2833 // Now store the XMM (fp + vector) parameter registers.
2834 SmallVector<SDValue, 12> SaveXMMOps;
2835 SaveXMMOps.push_back(Chain);
2836 SaveXMMOps.push_back(ALVal);
2837 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2838 FuncInfo->getRegSaveFrameIndex(), dl));
2839 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2840 FuncInfo->getVarArgsFPOffset(), dl));
2841 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2843 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2844 MVT::Other, SaveXMMOps));
2847 if (!MemOps.empty())
2848 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2851 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2852 // Find the largest legal vector type.
2853 MVT VecVT = MVT::Other;
2854 // FIXME: Only some x86_32 calling conventions support AVX512.
2855 if (Subtarget->hasAVX512() &&
2856 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2857 CallConv == CallingConv::Intel_OCL_BI)))
2858 VecVT = MVT::v16f32;
2859 else if (Subtarget->hasAVX())
2861 else if (Subtarget->hasSSE2())
2864 // We forward some GPRs and some vector types.
2865 SmallVector<MVT, 2> RegParmTypes;
2866 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2867 RegParmTypes.push_back(IntVT);
2868 if (VecVT != MVT::Other)
2869 RegParmTypes.push_back(VecVT);
2871 // Compute the set of forwarded registers. The rest are scratch.
2872 SmallVectorImpl<ForwardedRegister> &Forwards =
2873 FuncInfo->getForwardedMustTailRegParms();
2874 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2876 // Conservatively forward AL on x86_64, since it might be used for varargs.
2877 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2878 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2879 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2882 // Copy all forwards from physical to virtual registers.
2883 for (ForwardedRegister &F : Forwards) {
2884 // FIXME: Can we use a less constrained schedule?
2885 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2886 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2887 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2891 // Some CCs need callee pop.
2892 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2893 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2894 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2896 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2897 // If this is an sret function, the return should pop the hidden pointer.
2898 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2899 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2900 argsAreStructReturn(Ins) == StackStructReturn)
2901 FuncInfo->setBytesToPopOnReturn(4);
2905 // RegSaveFrameIndex is X86-64 only.
2906 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2907 if (CallConv == CallingConv::X86_FastCall ||
2908 CallConv == CallingConv::X86_ThisCall)
2909 // fastcc functions can't have varargs.
2910 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2913 FuncInfo->setArgumentStackSize(StackSize);
2915 if (MMI.hasWinEHFuncInfo(Fn)) {
2917 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2918 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2919 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2920 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2921 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2922 MachinePointerInfo::getFixedStack(
2923 DAG.getMachineFunction(), UnwindHelpFI),
2924 /*isVolatile=*/true,
2925 /*isNonTemporal=*/false, /*Alignment=*/0);
2927 // Functions using Win32 EH are considered to have opaque SP adjustments
2928 // to force local variables to be addressed from the frame or base
2930 MFI->setHasOpaqueSPAdjustment(true);
2938 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2939 SDValue StackPtr, SDValue Arg,
2940 SDLoc dl, SelectionDAG &DAG,
2941 const CCValAssign &VA,
2942 ISD::ArgFlagsTy Flags) const {
2943 unsigned LocMemOffset = VA.getLocMemOffset();
2944 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2945 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2947 if (Flags.isByVal())
2948 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2950 return DAG.getStore(
2951 Chain, dl, Arg, PtrOff,
2952 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2956 /// Emit a load of return address if tail call
2957 /// optimization is performed and it is required.
2959 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2960 SDValue &OutRetAddr, SDValue Chain,
2961 bool IsTailCall, bool Is64Bit,
2962 int FPDiff, SDLoc dl) const {
2963 // Adjust the Return address stack slot.
2964 EVT VT = getPointerTy(DAG.getDataLayout());
2965 OutRetAddr = getReturnAddressFrameIndex(DAG);
2967 // Load the "old" Return address.
2968 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2969 false, false, false, 0);
2970 return SDValue(OutRetAddr.getNode(), 1);
2973 /// Emit a store of the return address if tail call
2974 /// optimization is performed and it is required (FPDiff!=0).
2975 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2976 SDValue Chain, SDValue RetAddrFrIdx,
2977 EVT PtrVT, unsigned SlotSize,
2978 int FPDiff, SDLoc dl) {
2979 // Store the return address to the appropriate stack slot.
2980 if (!FPDiff) return Chain;
2981 // Calculate the new stack slot for the return address.
2982 int NewReturnAddrFI =
2983 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2985 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2986 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2987 MachinePointerInfo::getFixedStack(
2988 DAG.getMachineFunction(), NewReturnAddrFI),
2993 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2994 /// operation of specified width.
2995 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2997 unsigned NumElems = VT.getVectorNumElements();
2998 SmallVector<int, 8> Mask;
2999 Mask.push_back(NumElems);
3000 for (unsigned i = 1; i != NumElems; ++i)
3002 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3006 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3007 SmallVectorImpl<SDValue> &InVals) const {
3008 SelectionDAG &DAG = CLI.DAG;
3010 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3011 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3012 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3013 SDValue Chain = CLI.Chain;
3014 SDValue Callee = CLI.Callee;
3015 CallingConv::ID CallConv = CLI.CallConv;
3016 bool &isTailCall = CLI.IsTailCall;
3017 bool isVarArg = CLI.IsVarArg;
3019 MachineFunction &MF = DAG.getMachineFunction();
3020 bool Is64Bit = Subtarget->is64Bit();
3021 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3022 StructReturnType SR = callIsStructReturn(Outs);
3023 bool IsSibcall = false;
3024 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3025 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3027 if (Attr.getValueAsString() == "true")
3030 if (Subtarget->isPICStyleGOT() &&
3031 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3032 // If we are using a GOT, disable tail calls to external symbols with
3033 // default visibility. Tail calling such a symbol requires using a GOT
3034 // relocation, which forces early binding of the symbol. This breaks code
3035 // that require lazy function symbol resolution. Using musttail or
3036 // GuaranteedTailCallOpt will override this.
3037 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3038 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3039 G->getGlobal()->hasDefaultVisibility()))
3043 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3045 // Force this to be a tail call. The verifier rules are enough to ensure
3046 // that we can lower this successfully without moving the return address
3049 } else if (isTailCall) {
3050 // Check if it's really possible to do a tail call.
3051 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3052 isVarArg, SR != NotStructReturn,
3053 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3054 Outs, OutVals, Ins, DAG);
3056 // Sibcalls are automatically detected tailcalls which do not require
3058 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3065 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3066 "Var args not supported with calling convention fastcc, ghc or hipe");
3068 // Analyze operands of the call, assigning locations to each operand.
3069 SmallVector<CCValAssign, 16> ArgLocs;
3070 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3072 // Allocate shadow area for Win64
3074 CCInfo.AllocateStack(32, 8);
3076 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3078 // Get a count of how many bytes are to be pushed on the stack.
3079 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3081 // This is a sibcall. The memory operands are available in caller's
3082 // own caller's stack.
3084 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3085 canGuaranteeTCO(CallConv))
3086 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3089 if (isTailCall && !IsSibcall && !IsMustTail) {
3090 // Lower arguments at fp - stackoffset + fpdiff.
3091 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3093 FPDiff = NumBytesCallerPushed - NumBytes;
3095 // Set the delta of movement of the returnaddr stackslot.
3096 // But only set if delta is greater than previous delta.
3097 if (FPDiff < X86Info->getTCReturnAddrDelta())
3098 X86Info->setTCReturnAddrDelta(FPDiff);
3101 unsigned NumBytesToPush = NumBytes;
3102 unsigned NumBytesToPop = NumBytes;
3104 // If we have an inalloca argument, all stack space has already been allocated
3105 // for us and be right at the top of the stack. We don't support multiple
3106 // arguments passed in memory when using inalloca.
3107 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3109 if (!ArgLocs.back().isMemLoc())
3110 report_fatal_error("cannot use inalloca attribute on a register "
3112 if (ArgLocs.back().getLocMemOffset() != 0)
3113 report_fatal_error("any parameter with the inalloca attribute must be "
3114 "the only memory argument");
3118 Chain = DAG.getCALLSEQ_START(
3119 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3121 SDValue RetAddrFrIdx;
3122 // Load return address for tail calls.
3123 if (isTailCall && FPDiff)
3124 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3125 Is64Bit, FPDiff, dl);
3127 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3128 SmallVector<SDValue, 8> MemOpChains;
3131 // Walk the register/memloc assignments, inserting copies/loads. In the case
3132 // of tail call optimization arguments are handle later.
3133 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3134 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3135 // Skip inalloca arguments, they have already been written.
3136 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3137 if (Flags.isInAlloca())
3140 CCValAssign &VA = ArgLocs[i];
3141 EVT RegVT = VA.getLocVT();
3142 SDValue Arg = OutVals[i];
3143 bool isByVal = Flags.isByVal();
3145 // Promote the value if needed.
3146 switch (VA.getLocInfo()) {
3147 default: llvm_unreachable("Unknown loc info!");
3148 case CCValAssign::Full: break;
3149 case CCValAssign::SExt:
3150 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3152 case CCValAssign::ZExt:
3153 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3155 case CCValAssign::AExt:
3156 if (Arg.getValueType().isVector() &&
3157 Arg.getValueType().getScalarType() == MVT::i1)
3158 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3159 else if (RegVT.is128BitVector()) {
3160 // Special case: passing MMX values in XMM registers.
3161 Arg = DAG.getBitcast(MVT::i64, Arg);
3162 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3163 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3165 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3167 case CCValAssign::BCvt:
3168 Arg = DAG.getBitcast(RegVT, Arg);
3170 case CCValAssign::Indirect: {
3171 // Store the argument.
3172 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3173 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3174 Chain = DAG.getStore(
3175 Chain, dl, Arg, SpillSlot,
3176 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3183 if (VA.isRegLoc()) {
3184 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3185 if (isVarArg && IsWin64) {
3186 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3187 // shadow reg if callee is a varargs function.
3188 unsigned ShadowReg = 0;
3189 switch (VA.getLocReg()) {
3190 case X86::XMM0: ShadowReg = X86::RCX; break;
3191 case X86::XMM1: ShadowReg = X86::RDX; break;
3192 case X86::XMM2: ShadowReg = X86::R8; break;
3193 case X86::XMM3: ShadowReg = X86::R9; break;
3196 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3198 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3199 assert(VA.isMemLoc());
3200 if (!StackPtr.getNode())
3201 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3202 getPointerTy(DAG.getDataLayout()));
3203 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3204 dl, DAG, VA, Flags));
3208 if (!MemOpChains.empty())
3209 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3211 if (Subtarget->isPICStyleGOT()) {
3212 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3215 RegsToPass.push_back(std::make_pair(
3216 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3217 getPointerTy(DAG.getDataLayout()))));
3219 // If we are tail calling and generating PIC/GOT style code load the
3220 // address of the callee into ECX. The value in ecx is used as target of
3221 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3222 // for tail calls on PIC/GOT architectures. Normally we would just put the
3223 // address of GOT into ebx and then call target@PLT. But for tail calls
3224 // ebx would be restored (since ebx is callee saved) before jumping to the
3227 // Note: The actual moving to ECX is done further down.
3228 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3229 if (G && !G->getGlobal()->hasLocalLinkage() &&
3230 G->getGlobal()->hasDefaultVisibility())
3231 Callee = LowerGlobalAddress(Callee, DAG);
3232 else if (isa<ExternalSymbolSDNode>(Callee))
3233 Callee = LowerExternalSymbol(Callee, DAG);
3237 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3238 // From AMD64 ABI document:
3239 // For calls that may call functions that use varargs or stdargs
3240 // (prototype-less calls or calls to functions containing ellipsis (...) in
3241 // the declaration) %al is used as hidden argument to specify the number
3242 // of SSE registers used. The contents of %al do not need to match exactly
3243 // the number of registers, but must be an ubound on the number of SSE
3244 // registers used and is in the range 0 - 8 inclusive.
3246 // Count the number of XMM registers allocated.
3247 static const MCPhysReg XMMArgRegs[] = {
3248 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3249 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3251 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3252 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3253 && "SSE registers cannot be used when SSE is disabled");
3255 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3256 DAG.getConstant(NumXMMRegs, dl,
3260 if (isVarArg && IsMustTail) {
3261 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3262 for (const auto &F : Forwards) {
3263 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3264 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3268 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3269 // don't need this because the eligibility check rejects calls that require
3270 // shuffling arguments passed in memory.
3271 if (!IsSibcall && isTailCall) {
3272 // Force all the incoming stack arguments to be loaded from the stack
3273 // before any new outgoing arguments are stored to the stack, because the
3274 // outgoing stack slots may alias the incoming argument stack slots, and
3275 // the alias isn't otherwise explicit. This is slightly more conservative
3276 // than necessary, because it means that each store effectively depends
3277 // on every argument instead of just those arguments it would clobber.
3278 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3280 SmallVector<SDValue, 8> MemOpChains2;
3283 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3284 CCValAssign &VA = ArgLocs[i];
3287 assert(VA.isMemLoc());
3288 SDValue Arg = OutVals[i];
3289 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3290 // Skip inalloca arguments. They don't require any work.
3291 if (Flags.isInAlloca())
3293 // Create frame index.
3294 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3295 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3296 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3297 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3299 if (Flags.isByVal()) {
3300 // Copy relative to framepointer.
3301 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3302 if (!StackPtr.getNode())
3303 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3304 getPointerTy(DAG.getDataLayout()));
3305 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3308 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3312 // Store relative to framepointer.
3313 MemOpChains2.push_back(DAG.getStore(
3314 ArgChain, dl, Arg, FIN,
3315 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3320 if (!MemOpChains2.empty())
3321 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3323 // Store the return address to the appropriate stack slot.
3324 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3325 getPointerTy(DAG.getDataLayout()),
3326 RegInfo->getSlotSize(), FPDiff, dl);
3329 // Build a sequence of copy-to-reg nodes chained together with token chain
3330 // and flag operands which copy the outgoing args into registers.
3332 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3333 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3334 RegsToPass[i].second, InFlag);
3335 InFlag = Chain.getValue(1);
3338 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3339 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3340 // In the 64-bit large code model, we have to make all calls
3341 // through a register, since the call instruction's 32-bit
3342 // pc-relative offset may not be large enough to hold the whole
3344 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3345 // If the callee is a GlobalAddress node (quite common, every direct call
3346 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3348 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3350 // We should use extra load for direct calls to dllimported functions in
3352 const GlobalValue *GV = G->getGlobal();
3353 if (!GV->hasDLLImportStorageClass()) {
3354 unsigned char OpFlags = 0;
3355 bool ExtraLoad = false;
3356 unsigned WrapperKind = ISD::DELETED_NODE;
3358 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3359 // external symbols most go through the PLT in PIC mode. If the symbol
3360 // has hidden or protected visibility, or if it is static or local, then
3361 // we don't need to use the PLT - we can directly call it.
3362 if (Subtarget->isTargetELF() &&
3363 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3364 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3365 OpFlags = X86II::MO_PLT;
3366 } else if (Subtarget->isPICStyleStubAny() &&
3367 !GV->isStrongDefinitionForLinker() &&
3368 (!Subtarget->getTargetTriple().isMacOSX() ||
3369 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3370 // PC-relative references to external symbols should go through $stub,
3371 // unless we're building with the leopard linker or later, which
3372 // automatically synthesizes these stubs.
3373 OpFlags = X86II::MO_DARWIN_STUB;
3374 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3375 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3376 // If the function is marked as non-lazy, generate an indirect call
3377 // which loads from the GOT directly. This avoids runtime overhead
3378 // at the cost of eager binding (and one extra byte of encoding).
3379 OpFlags = X86II::MO_GOTPCREL;
3380 WrapperKind = X86ISD::WrapperRIP;
3384 Callee = DAG.getTargetGlobalAddress(
3385 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3387 // Add a wrapper if needed.
3388 if (WrapperKind != ISD::DELETED_NODE)
3389 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3390 getPointerTy(DAG.getDataLayout()), Callee);
3391 // Add extra indirection if needed.
3393 Callee = DAG.getLoad(
3394 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3395 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3398 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3399 unsigned char OpFlags = 0;
3401 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3402 // external symbols should go through the PLT.
3403 if (Subtarget->isTargetELF() &&
3404 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3405 OpFlags = X86II::MO_PLT;
3406 } else if (Subtarget->isPICStyleStubAny() &&
3407 (!Subtarget->getTargetTriple().isMacOSX() ||
3408 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3409 // PC-relative references to external symbols should go through $stub,
3410 // unless we're building with the leopard linker or later, which
3411 // automatically synthesizes these stubs.
3412 OpFlags = X86II::MO_DARWIN_STUB;
3415 Callee = DAG.getTargetExternalSymbol(
3416 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3417 } else if (Subtarget->isTarget64BitILP32() &&
3418 Callee->getValueType(0) == MVT::i32) {
3419 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3420 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3423 // Returns a chain & a flag for retval copy to use.
3424 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3425 SmallVector<SDValue, 8> Ops;
3427 if (!IsSibcall && isTailCall) {
3428 Chain = DAG.getCALLSEQ_END(Chain,
3429 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3430 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3431 InFlag = Chain.getValue(1);
3434 Ops.push_back(Chain);
3435 Ops.push_back(Callee);
3438 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3440 // Add argument registers to the end of the list so that they are known live
3442 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3443 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3444 RegsToPass[i].second.getValueType()));
3446 // Add a register mask operand representing the call-preserved registers.
3447 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3448 assert(Mask && "Missing call preserved mask for calling convention");
3450 // If this is an invoke in a 32-bit function using a funclet-based
3451 // personality, assume the function clobbers all registers. If an exception
3452 // is thrown, the runtime will not restore CSRs.
3453 // FIXME: Model this more precisely so that we can register allocate across
3454 // the normal edge and spill and fill across the exceptional edge.
3455 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3456 const Function *CallerFn = MF.getFunction();
3457 EHPersonality Pers =
3458 CallerFn->hasPersonalityFn()
3459 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3460 : EHPersonality::Unknown;
3461 if (isFuncletEHPersonality(Pers))
3462 Mask = RegInfo->getNoPreservedMask();
3465 Ops.push_back(DAG.getRegisterMask(Mask));
3467 if (InFlag.getNode())
3468 Ops.push_back(InFlag);
3472 //// If this is the first return lowered for this function, add the regs
3473 //// to the liveout set for the function.
3474 // This isn't right, although it's probably harmless on x86; liveouts
3475 // should be computed from returns not tail calls. Consider a void
3476 // function making a tail call to a function returning int.
3477 MF.getFrameInfo()->setHasTailCall();
3478 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3481 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3482 InFlag = Chain.getValue(1);
3484 // Create the CALLSEQ_END node.
3485 unsigned NumBytesForCalleeToPop;
3486 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3487 DAG.getTarget().Options.GuaranteedTailCallOpt))
3488 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3489 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3490 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3491 SR == StackStructReturn)
3492 // If this is a call to a struct-return function, the callee
3493 // pops the hidden struct pointer, so we have to push it back.
3494 // This is common for Darwin/X86, Linux & Mingw32 targets.
3495 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3496 NumBytesForCalleeToPop = 4;
3498 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3500 // Returns a flag for retval copy to use.
3502 Chain = DAG.getCALLSEQ_END(Chain,
3503 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3504 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3507 InFlag = Chain.getValue(1);
3510 // Handle result values, copying them out of physregs into vregs that we
3512 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3513 Ins, dl, DAG, InVals);
3516 //===----------------------------------------------------------------------===//
3517 // Fast Calling Convention (tail call) implementation
3518 //===----------------------------------------------------------------------===//
3520 // Like std call, callee cleans arguments, convention except that ECX is
3521 // reserved for storing the tail called function address. Only 2 registers are
3522 // free for argument passing (inreg). Tail call optimization is performed
3524 // * tailcallopt is enabled
3525 // * caller/callee are fastcc
3526 // On X86_64 architecture with GOT-style position independent code only local
3527 // (within module) calls are supported at the moment.
3528 // To keep the stack aligned according to platform abi the function
3529 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3530 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3531 // If a tail called function callee has more arguments than the caller the
3532 // caller needs to make sure that there is room to move the RETADDR to. This is
3533 // achieved by reserving an area the size of the argument delta right after the
3534 // original RETADDR, but before the saved framepointer or the spilled registers
3535 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3547 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3550 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3551 SelectionDAG& DAG) const {
3552 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3553 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3554 unsigned StackAlignment = TFI.getStackAlignment();
3555 uint64_t AlignMask = StackAlignment - 1;
3556 int64_t Offset = StackSize;
3557 unsigned SlotSize = RegInfo->getSlotSize();
3558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3559 // Number smaller than 12 so just add the difference.
3560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3562 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3563 Offset = ((~AlignMask) & Offset) + StackAlignment +
3564 (StackAlignment-SlotSize);
3569 /// Return true if the given stack call argument is already available in the
3570 /// same position (relatively) of the caller's incoming argument stack.
3572 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3573 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3574 const X86InstrInfo *TII) {
3575 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3577 if (Arg.getOpcode() == ISD::CopyFromReg) {
3578 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3579 if (!TargetRegisterInfo::isVirtualRegister(VR))
3581 MachineInstr *Def = MRI->getVRegDef(VR);
3584 if (!Flags.isByVal()) {
3585 if (!TII->isLoadFromStackSlot(Def, FI))
3588 unsigned Opcode = Def->getOpcode();
3589 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3590 Opcode == X86::LEA64_32r) &&
3591 Def->getOperand(1).isFI()) {
3592 FI = Def->getOperand(1).getIndex();
3593 Bytes = Flags.getByValSize();
3597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3598 if (Flags.isByVal())
3599 // ByVal argument is passed in as a pointer but it's now being
3600 // dereferenced. e.g.
3601 // define @foo(%struct.X* %A) {
3602 // tail call @bar(%struct.X* byval %A)
3605 SDValue Ptr = Ld->getBasePtr();
3606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3609 FI = FINode->getIndex();
3610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3612 FI = FINode->getIndex();
3613 Bytes = Flags.getByValSize();
3617 assert(FI != INT_MAX);
3618 if (!MFI->isFixedObjectIndex(FI))
3620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3623 /// Check whether the call is eligible for tail call optimization. Targets
3624 /// that want to do tail call optimization should implement this function.
3625 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3626 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3627 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3628 const SmallVectorImpl<ISD::OutputArg> &Outs,
3629 const SmallVectorImpl<SDValue> &OutVals,
3630 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3631 if (!mayTailCallThisCC(CalleeCC))
3634 // If -tailcallopt is specified, make fastcc functions tail-callable.
3635 MachineFunction &MF = DAG.getMachineFunction();
3636 const Function *CallerF = MF.getFunction();
3638 // If the function return type is x86_fp80 and the callee return type is not,
3639 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3640 // perform a tailcall optimization here.
3641 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3644 CallingConv::ID CallerCC = CallerF->getCallingConv();
3645 bool CCMatch = CallerCC == CalleeCC;
3646 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3647 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3649 // Win64 functions have extra shadow space for argument homing. Don't do the
3650 // sibcall if the caller and callee have mismatched expectations for this
3652 if (IsCalleeWin64 != IsCallerWin64)
3655 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3656 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3661 // Look for obvious safe cases to perform tail call optimization that do not
3662 // require ABI changes. This is what gcc calls sibcall.
3664 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3665 // emit a special epilogue.
3666 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3667 if (RegInfo->needsStackRealignment(MF))
3670 // Also avoid sibcall optimization if either caller or callee uses struct
3671 // return semantics.
3672 if (isCalleeStructRet || isCallerStructRet)
3675 // Do not sibcall optimize vararg calls unless all arguments are passed via
3677 if (isVarArg && !Outs.empty()) {
3678 // Optimizing for varargs on Win64 is unlikely to be safe without
3679 // additional testing.
3680 if (IsCalleeWin64 || IsCallerWin64)
3683 SmallVector<CCValAssign, 16> ArgLocs;
3684 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3687 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3688 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3689 if (!ArgLocs[i].isRegLoc())
3693 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3694 // stack. Therefore, if it's not used by the call it is not safe to optimize
3695 // this into a sibcall.
3696 bool Unused = false;
3697 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3704 SmallVector<CCValAssign, 16> RVLocs;
3705 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3707 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3708 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3709 CCValAssign &VA = RVLocs[i];
3710 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3715 // If the calling conventions do not match, then we'd better make sure the
3716 // results are returned in the same way as what the caller expects.
3718 SmallVector<CCValAssign, 16> RVLocs1;
3719 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3721 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3723 SmallVector<CCValAssign, 16> RVLocs2;
3724 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3726 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3728 if (RVLocs1.size() != RVLocs2.size())
3730 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3731 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3733 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3735 if (RVLocs1[i].isRegLoc()) {
3736 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3739 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3745 unsigned StackArgsSize = 0;
3747 // If the callee takes no arguments then go on to check the results of the
3749 if (!Outs.empty()) {
3750 // Check if stack adjustment is needed. For now, do not do this if any
3751 // argument is passed on the stack.
3752 SmallVector<CCValAssign, 16> ArgLocs;
3753 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3756 // Allocate shadow area for Win64
3758 CCInfo.AllocateStack(32, 8);
3760 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3761 StackArgsSize = CCInfo.getNextStackOffset();
3763 if (CCInfo.getNextStackOffset()) {
3764 // Check if the arguments are already laid out in the right way as
3765 // the caller's fixed stack objects.
3766 MachineFrameInfo *MFI = MF.getFrameInfo();
3767 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3768 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3769 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3770 CCValAssign &VA = ArgLocs[i];
3771 SDValue Arg = OutVals[i];
3772 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3773 if (VA.getLocInfo() == CCValAssign::Indirect)
3775 if (!VA.isRegLoc()) {
3776 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3783 // If the tailcall address may be in a register, then make sure it's
3784 // possible to register allocate for it. In 32-bit, the call address can
3785 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3786 // callee-saved registers are restored. These happen to be the same
3787 // registers used to pass 'inreg' arguments so watch out for those.
3788 if (!Subtarget->is64Bit() &&
3789 ((!isa<GlobalAddressSDNode>(Callee) &&
3790 !isa<ExternalSymbolSDNode>(Callee)) ||
3791 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3792 unsigned NumInRegs = 0;
3793 // In PIC we need an extra register to formulate the address computation
3795 unsigned MaxInRegs =
3796 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3798 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3799 CCValAssign &VA = ArgLocs[i];
3802 unsigned Reg = VA.getLocReg();
3805 case X86::EAX: case X86::EDX: case X86::ECX:
3806 if (++NumInRegs == MaxInRegs)
3814 bool CalleeWillPop =
3815 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3816 MF.getTarget().Options.GuaranteedTailCallOpt);
3818 if (unsigned BytesToPop =
3819 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3820 // If we have bytes to pop, the callee must pop them.
3821 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3822 if (!CalleePopMatches)
3824 } else if (CalleeWillPop && StackArgsSize > 0) {
3825 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3833 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3834 const TargetLibraryInfo *libInfo) const {
3835 return X86::createFastISel(funcInfo, libInfo);
3838 //===----------------------------------------------------------------------===//
3839 // Other Lowering Hooks
3840 //===----------------------------------------------------------------------===//
3842 static bool MayFoldLoad(SDValue Op) {
3843 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3846 static bool MayFoldIntoStore(SDValue Op) {
3847 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3850 static bool isTargetShuffle(unsigned Opcode) {
3852 default: return false;
3853 case X86ISD::BLENDI:
3854 case X86ISD::PSHUFB:
3855 case X86ISD::PSHUFD:
3856 case X86ISD::PSHUFHW:
3857 case X86ISD::PSHUFLW:
3859 case X86ISD::PALIGNR:
3860 case X86ISD::MOVLHPS:
3861 case X86ISD::MOVLHPD:
3862 case X86ISD::MOVHLPS:
3863 case X86ISD::MOVLPS:
3864 case X86ISD::MOVLPD:
3865 case X86ISD::MOVSHDUP:
3866 case X86ISD::MOVSLDUP:
3867 case X86ISD::MOVDDUP:
3870 case X86ISD::UNPCKL:
3871 case X86ISD::UNPCKH:
3872 case X86ISD::VPERMILPI:
3873 case X86ISD::VPERM2X128:
3874 case X86ISD::VPERMI:
3875 case X86ISD::VPERMV:
3876 case X86ISD::VPERMV3:
3881 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3882 SDValue V1, unsigned TargetMask,
3883 SelectionDAG &DAG) {
3885 default: llvm_unreachable("Unknown x86 shuffle node");
3886 case X86ISD::PSHUFD:
3887 case X86ISD::PSHUFHW:
3888 case X86ISD::PSHUFLW:
3889 case X86ISD::VPERMILPI:
3890 case X86ISD::VPERMI:
3891 return DAG.getNode(Opc, dl, VT, V1,
3892 DAG.getConstant(TargetMask, dl, MVT::i8));
3896 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3897 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3899 default: llvm_unreachable("Unknown x86 shuffle node");
3900 case X86ISD::MOVLHPS:
3901 case X86ISD::MOVLHPD:
3902 case X86ISD::MOVHLPS:
3903 case X86ISD::MOVLPS:
3904 case X86ISD::MOVLPD:
3907 case X86ISD::UNPCKL:
3908 case X86ISD::UNPCKH:
3909 return DAG.getNode(Opc, dl, VT, V1, V2);
3913 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3914 MachineFunction &MF = DAG.getMachineFunction();
3915 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3916 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3917 int ReturnAddrIndex = FuncInfo->getRAIndex();
3919 if (ReturnAddrIndex == 0) {
3920 // Set up a frame object for the return address.
3921 unsigned SlotSize = RegInfo->getSlotSize();
3922 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3925 FuncInfo->setRAIndex(ReturnAddrIndex);
3928 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3931 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3932 bool hasSymbolicDisplacement) {
3933 // Offset should fit into 32 bit immediate field.
3934 if (!isInt<32>(Offset))
3937 // If we don't have a symbolic displacement - we don't have any extra
3939 if (!hasSymbolicDisplacement)
3942 // FIXME: Some tweaks might be needed for medium code model.
3943 if (M != CodeModel::Small && M != CodeModel::Kernel)
3946 // For small code model we assume that latest object is 16MB before end of 31
3947 // bits boundary. We may also accept pretty large negative constants knowing
3948 // that all objects are in the positive half of address space.
3949 if (M == CodeModel::Small && Offset < 16*1024*1024)
3952 // For kernel code model we know that all object resist in the negative half
3953 // of 32bits address space. We may not accept negative offsets, since they may
3954 // be just off and we may accept pretty large positive ones.
3955 if (M == CodeModel::Kernel && Offset >= 0)
3961 /// Determines whether the callee is required to pop its own arguments.
3962 /// Callee pop is necessary to support tail calls.
3963 bool X86::isCalleePop(CallingConv::ID CallingConv,
3964 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3965 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3966 // can guarantee TCO.
3967 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3970 switch (CallingConv) {
3973 case CallingConv::X86_StdCall:
3974 case CallingConv::X86_FastCall:
3975 case CallingConv::X86_ThisCall:
3976 case CallingConv::X86_VectorCall:
3981 /// \brief Return true if the condition is an unsigned comparison operation.
3982 static bool isX86CCUnsigned(unsigned X86CC) {
3984 default: llvm_unreachable("Invalid integer condition!");
3985 case X86::COND_E: return true;
3986 case X86::COND_G: return false;
3987 case X86::COND_GE: return false;
3988 case X86::COND_L: return false;
3989 case X86::COND_LE: return false;
3990 case X86::COND_NE: return true;
3991 case X86::COND_B: return true;
3992 case X86::COND_A: return true;
3993 case X86::COND_BE: return true;
3994 case X86::COND_AE: return true;
3996 llvm_unreachable("covered switch fell through?!");
3999 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4000 /// condition code, returning the condition code and the LHS/RHS of the
4001 /// comparison to make.
4002 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4003 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4005 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4006 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4007 // X > -1 -> X == 0, jump !sign.
4008 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4009 return X86::COND_NS;
4011 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4012 // X < 0 -> X == 0, jump on sign.
4015 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4017 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4018 return X86::COND_LE;
4022 switch (SetCCOpcode) {
4023 default: llvm_unreachable("Invalid integer condition!");
4024 case ISD::SETEQ: return X86::COND_E;
4025 case ISD::SETGT: return X86::COND_G;
4026 case ISD::SETGE: return X86::COND_GE;
4027 case ISD::SETLT: return X86::COND_L;
4028 case ISD::SETLE: return X86::COND_LE;
4029 case ISD::SETNE: return X86::COND_NE;
4030 case ISD::SETULT: return X86::COND_B;
4031 case ISD::SETUGT: return X86::COND_A;
4032 case ISD::SETULE: return X86::COND_BE;
4033 case ISD::SETUGE: return X86::COND_AE;
4037 // First determine if it is required or is profitable to flip the operands.
4039 // If LHS is a foldable load, but RHS is not, flip the condition.
4040 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4041 !ISD::isNON_EXTLoad(RHS.getNode())) {
4042 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4043 std::swap(LHS, RHS);
4046 switch (SetCCOpcode) {
4052 std::swap(LHS, RHS);
4056 // On a floating point condition, the flags are set as follows:
4058 // 0 | 0 | 0 | X > Y
4059 // 0 | 0 | 1 | X < Y
4060 // 1 | 0 | 0 | X == Y
4061 // 1 | 1 | 1 | unordered
4062 switch (SetCCOpcode) {
4063 default: llvm_unreachable("Condcode should be pre-legalized away");
4065 case ISD::SETEQ: return X86::COND_E;
4066 case ISD::SETOLT: // flipped
4068 case ISD::SETGT: return X86::COND_A;
4069 case ISD::SETOLE: // flipped
4071 case ISD::SETGE: return X86::COND_AE;
4072 case ISD::SETUGT: // flipped
4074 case ISD::SETLT: return X86::COND_B;
4075 case ISD::SETUGE: // flipped
4077 case ISD::SETLE: return X86::COND_BE;
4079 case ISD::SETNE: return X86::COND_NE;
4080 case ISD::SETUO: return X86::COND_P;
4081 case ISD::SETO: return X86::COND_NP;
4083 case ISD::SETUNE: return X86::COND_INVALID;
4087 /// Is there a floating point cmov for the specific X86 condition code?
4088 /// Current x86 isa includes the following FP cmov instructions:
4089 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4090 static bool hasFPCMov(unsigned X86CC) {
4106 /// Returns true if the target can instruction select the
4107 /// specified FP immediate natively. If false, the legalizer will
4108 /// materialize the FP immediate as a load from a constant pool.
4109 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4110 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4111 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4117 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4118 ISD::LoadExtType ExtTy,
4120 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4121 // relocation target a movq or addq instruction: don't let the load shrink.
4122 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4123 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4124 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4125 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4129 /// \brief Returns true if it is beneficial to convert a load of a constant
4130 /// to just the constant itself.
4131 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4133 assert(Ty->isIntegerTy());
4135 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4136 if (BitSize == 0 || BitSize > 64)
4141 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4142 unsigned Index) const {
4143 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4146 return (Index == 0 || Index == ResVT.getVectorNumElements());
4149 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4150 // Speculate cttz only if we can directly use TZCNT.
4151 return Subtarget->hasBMI();
4154 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4155 // Speculate ctlz only if we can directly use LZCNT.
4156 return Subtarget->hasLZCNT();
4159 /// Return true if every element in Mask, beginning
4160 /// from position Pos and ending in Pos+Size is undef.
4161 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4162 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4168 /// Return true if Val is undef or if its value falls within the
4169 /// specified range (L, H].
4170 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4171 return (Val < 0) || (Val >= Low && Val < Hi);
4174 /// Val is either less than zero (undef) or equal to the specified value.
4175 static bool isUndefOrEqual(int Val, int CmpVal) {
4176 return (Val < 0 || Val == CmpVal);
4179 /// Return true if every element in Mask, beginning
4180 /// from position Pos and ending in Pos+Size, falls within the specified
4181 /// sequential range (Low, Low+Size]. or is undef.
4182 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4183 unsigned Pos, unsigned Size, int Low) {
4184 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4185 if (!isUndefOrEqual(Mask[i], Low))
4190 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4191 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4192 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4193 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4194 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4197 // The index should be aligned on a vecWidth-bit boundary.
4199 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4201 MVT VT = N->getSimpleValueType(0);
4202 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4203 bool Result = (Index * ElSize) % vecWidth == 0;
4208 /// Return true if the specified INSERT_SUBVECTOR
4209 /// operand specifies a subvector insert that is suitable for input to
4210 /// insertion of 128 or 256-bit subvectors
4211 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4212 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4213 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4215 // The index should be aligned on a vecWidth-bit boundary.
4217 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4219 MVT VT = N->getSimpleValueType(0);
4220 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4221 bool Result = (Index * ElSize) % vecWidth == 0;
4226 bool X86::isVINSERT128Index(SDNode *N) {
4227 return isVINSERTIndex(N, 128);
4230 bool X86::isVINSERT256Index(SDNode *N) {
4231 return isVINSERTIndex(N, 256);
4234 bool X86::isVEXTRACT128Index(SDNode *N) {
4235 return isVEXTRACTIndex(N, 128);
4238 bool X86::isVEXTRACT256Index(SDNode *N) {
4239 return isVEXTRACTIndex(N, 256);
4242 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4243 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4244 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4245 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4248 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4250 MVT VecVT = N->getOperand(0).getSimpleValueType();
4251 MVT ElVT = VecVT.getVectorElementType();
4253 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4254 return Index / NumElemsPerChunk;
4257 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4258 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4259 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4260 llvm_unreachable("Illegal insert subvector for VINSERT");
4263 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4265 MVT VecVT = N->getSimpleValueType(0);
4266 MVT ElVT = VecVT.getVectorElementType();
4268 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4269 return Index / NumElemsPerChunk;
4272 /// Return the appropriate immediate to extract the specified
4273 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4274 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4275 return getExtractVEXTRACTImmediate(N, 128);
4278 /// Return the appropriate immediate to extract the specified
4279 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4280 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4281 return getExtractVEXTRACTImmediate(N, 256);
4284 /// Return the appropriate immediate to insert at the specified
4285 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4286 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4287 return getInsertVINSERTImmediate(N, 128);
4290 /// Return the appropriate immediate to insert at the specified
4291 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4292 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4293 return getInsertVINSERTImmediate(N, 256);
4296 /// Returns true if V is a constant integer zero.
4297 static bool isZero(SDValue V) {
4298 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4299 return C && C->isNullValue();
4302 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4303 bool X86::isZeroNode(SDValue Elt) {
4306 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4307 return CFP->getValueAPF().isPosZero();
4311 // Build a vector of constants
4312 // Use an UNDEF node if MaskElt == -1.
4313 // Spilt 64-bit constants in the 32-bit mode.
4314 static SDValue getConstVector(ArrayRef<int> Values, EVT VT,
4316 SDLoc dl, bool IsMask = false) {
4318 SmallVector<SDValue, 32> Ops;
4321 EVT ConstVecVT = VT;
4322 unsigned NumElts = VT.getVectorNumElements();
4323 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4324 if (!In64BitMode && VT.getScalarType() == MVT::i64) {
4325 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4329 EVT EltVT = ConstVecVT.getScalarType();
4330 for (unsigned i = 0; i < NumElts; ++i) {
4331 bool IsUndef = Values[i] < 0 && IsMask;
4332 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4333 DAG.getConstant(Values[i], dl, EltVT);
4334 Ops.push_back(OpNode);
4336 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4337 DAG.getConstant(0, dl, EltVT));
4339 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4341 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4345 /// Returns a vector of specified type with all zero elements.
4346 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4347 SelectionDAG &DAG, SDLoc dl) {
4348 assert(VT.isVector() && "Expected a vector type");
4350 // Always build SSE zero vectors as <4 x i32> bitcasted
4351 // to their dest type. This ensures they get CSE'd.
4353 if (VT.is128BitVector()) { // SSE
4354 if (Subtarget->hasSSE2()) { // SSE2
4355 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4358 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4359 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4361 } else if (VT.is256BitVector()) { // AVX
4362 if (Subtarget->hasInt256()) { // AVX2
4363 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4364 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4365 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4367 // 256-bit logic and arithmetic instructions in AVX are all
4368 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4369 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4370 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4371 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4373 } else if (VT.is512BitVector()) { // AVX-512
4374 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4375 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4376 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4377 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4378 } else if (VT.getScalarType() == MVT::i1) {
4380 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4381 && "Unexpected vector type");
4382 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4383 && "Unexpected vector type");
4384 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4385 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4386 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4388 llvm_unreachable("Unexpected vector type");
4390 return DAG.getBitcast(VT, Vec);
4393 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4394 SelectionDAG &DAG, SDLoc dl,
4395 unsigned vectorWidth) {
4396 assert((vectorWidth == 128 || vectorWidth == 256) &&
4397 "Unsupported vector width");
4398 EVT VT = Vec.getValueType();
4399 EVT ElVT = VT.getVectorElementType();
4400 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4401 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4402 VT.getVectorNumElements()/Factor);
4404 // Extract from UNDEF is UNDEF.
4405 if (Vec.getOpcode() == ISD::UNDEF)
4406 return DAG.getUNDEF(ResultVT);
4408 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4409 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4411 // This is the index of the first element of the vectorWidth-bit chunk
4413 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4416 // If the input is a buildvector just emit a smaller one.
4417 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4418 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4419 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4422 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4423 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4426 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4427 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4428 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4429 /// instructions or a simple subregister reference. Idx is an index in the
4430 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4431 /// lowering EXTRACT_VECTOR_ELT operations easier.
4432 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4433 SelectionDAG &DAG, SDLoc dl) {
4434 assert((Vec.getValueType().is256BitVector() ||
4435 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4436 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4439 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4440 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4441 SelectionDAG &DAG, SDLoc dl) {
4442 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4443 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4446 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4447 unsigned IdxVal, SelectionDAG &DAG,
4448 SDLoc dl, unsigned vectorWidth) {
4449 assert((vectorWidth == 128 || vectorWidth == 256) &&
4450 "Unsupported vector width");
4451 // Inserting UNDEF is Result
4452 if (Vec.getOpcode() == ISD::UNDEF)
4454 EVT VT = Vec.getValueType();
4455 EVT ElVT = VT.getVectorElementType();
4456 EVT ResultVT = Result.getValueType();
4458 // Insert the relevant vectorWidth bits.
4459 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4461 // This is the index of the first element of the vectorWidth-bit chunk
4463 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4466 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4467 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4470 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4471 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4472 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4473 /// simple superregister reference. Idx is an index in the 128 bits
4474 /// we want. It need not be aligned to a 128-bit boundary. That makes
4475 /// lowering INSERT_VECTOR_ELT operations easier.
4476 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4477 SelectionDAG &DAG, SDLoc dl) {
4478 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4480 // For insertion into the zero index (low half) of a 256-bit vector, it is
4481 // more efficient to generate a blend with immediate instead of an insert*128.
4482 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4483 // extend the subvector to the size of the result vector. Make sure that
4484 // we are not recursing on that node by checking for undef here.
4485 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4486 Result.getOpcode() != ISD::UNDEF) {
4487 EVT ResultVT = Result.getValueType();
4488 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4489 SDValue Undef = DAG.getUNDEF(ResultVT);
4490 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4493 // The blend instruction, and therefore its mask, depend on the data type.
4494 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4495 if (ScalarType.isFloatingPoint()) {
4496 // Choose either vblendps (float) or vblendpd (double).
4497 unsigned ScalarSize = ScalarType.getSizeInBits();
4498 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4499 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4500 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4501 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4504 const X86Subtarget &Subtarget =
4505 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4507 // AVX2 is needed for 256-bit integer blend support.
4508 // Integers must be cast to 32-bit because there is only vpblendd;
4509 // vpblendw can't be used for this because it has a handicapped mask.
4511 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4512 // is still more efficient than using the wrong domain vinsertf128 that
4513 // will be created by InsertSubVector().
4514 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4516 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4517 Vec256 = DAG.getBitcast(CastVT, Vec256);
4518 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4519 return DAG.getBitcast(ResultVT, Vec256);
4522 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4525 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4526 SelectionDAG &DAG, SDLoc dl) {
4527 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4528 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4531 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4532 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4533 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4534 /// large BUILD_VECTORS.
4535 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4536 unsigned NumElems, SelectionDAG &DAG,
4538 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4539 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4542 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4543 unsigned NumElems, SelectionDAG &DAG,
4545 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4546 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4549 /// Returns a vector of specified type with all bits set.
4550 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4551 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4552 /// Then bitcast to their original type, ensuring they get CSE'd.
4553 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4554 SelectionDAG &DAG, SDLoc dl) {
4555 assert(VT.isVector() && "Expected a vector type");
4557 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4559 if (VT.is512BitVector()) {
4560 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4561 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4562 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4563 } else if (VT.is256BitVector()) {
4564 if (Subtarget->hasInt256()) { // AVX2
4565 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4566 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4568 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4569 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4571 } else if (VT.is128BitVector()) {
4572 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4574 llvm_unreachable("Unexpected vector type");
4576 return DAG.getBitcast(VT, Vec);
4579 /// Returns a vector_shuffle node for an unpackl operation.
4580 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4582 unsigned NumElems = VT.getVectorNumElements();
4583 SmallVector<int, 8> Mask;
4584 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4586 Mask.push_back(i + NumElems);
4588 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4591 /// Returns a vector_shuffle node for an unpackh operation.
4592 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4594 unsigned NumElems = VT.getVectorNumElements();
4595 SmallVector<int, 8> Mask;
4596 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4597 Mask.push_back(i + Half);
4598 Mask.push_back(i + NumElems + Half);
4600 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4603 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4604 /// This produces a shuffle where the low element of V2 is swizzled into the
4605 /// zero/undef vector, landing at element Idx.
4606 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4607 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4609 const X86Subtarget *Subtarget,
4610 SelectionDAG &DAG) {
4611 MVT VT = V2.getSimpleValueType();
4613 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4614 unsigned NumElems = VT.getVectorNumElements();
4615 SmallVector<int, 16> MaskVec;
4616 for (unsigned i = 0; i != NumElems; ++i)
4617 // If this is the insertion idx, put the low elt of V2 here.
4618 MaskVec.push_back(i == Idx ? NumElems : i);
4619 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4622 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4623 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4624 /// uses one source. Note that this will set IsUnary for shuffles which use a
4625 /// single input multiple times, and in those cases it will
4626 /// adjust the mask to only have indices within that single input.
4627 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4628 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4629 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4630 unsigned NumElems = VT.getVectorNumElements();
4634 bool IsFakeUnary = false;
4635 switch(N->getOpcode()) {
4636 case X86ISD::BLENDI:
4637 ImmN = N->getOperand(N->getNumOperands()-1);
4638 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641 ImmN = N->getOperand(N->getNumOperands()-1);
4642 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4643 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4645 case X86ISD::UNPCKH:
4646 DecodeUNPCKHMask(VT, Mask);
4647 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4649 case X86ISD::UNPCKL:
4650 DecodeUNPCKLMask(VT, Mask);
4651 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4653 case X86ISD::MOVHLPS:
4654 DecodeMOVHLPSMask(NumElems, Mask);
4655 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4657 case X86ISD::MOVLHPS:
4658 DecodeMOVLHPSMask(NumElems, Mask);
4659 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4661 case X86ISD::PALIGNR:
4662 ImmN = N->getOperand(N->getNumOperands()-1);
4663 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4665 case X86ISD::PSHUFD:
4666 case X86ISD::VPERMILPI:
4667 ImmN = N->getOperand(N->getNumOperands()-1);
4668 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4671 case X86ISD::PSHUFHW:
4672 ImmN = N->getOperand(N->getNumOperands()-1);
4673 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4676 case X86ISD::PSHUFLW:
4677 ImmN = N->getOperand(N->getNumOperands()-1);
4678 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4681 case X86ISD::PSHUFB: {
4683 SDValue MaskNode = N->getOperand(1);
4684 while (MaskNode->getOpcode() == ISD::BITCAST)
4685 MaskNode = MaskNode->getOperand(0);
4687 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4688 // If we have a build-vector, then things are easy.
4689 EVT VT = MaskNode.getValueType();
4690 assert(VT.isVector() &&
4691 "Can't produce a non-vector with a build_vector!");
4692 if (!VT.isInteger())
4695 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4697 SmallVector<uint64_t, 32> RawMask;
4698 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4699 SDValue Op = MaskNode->getOperand(i);
4700 if (Op->getOpcode() == ISD::UNDEF) {
4701 RawMask.push_back((uint64_t)SM_SentinelUndef);
4704 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4707 APInt MaskElement = CN->getAPIntValue();
4709 // We now have to decode the element which could be any integer size and
4710 // extract each byte of it.
4711 for (int j = 0; j < NumBytesPerElement; ++j) {
4712 // Note that this is x86 and so always little endian: the low byte is
4713 // the first byte of the mask.
4714 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4715 MaskElement = MaskElement.lshr(8);
4718 DecodePSHUFBMask(RawMask, Mask);
4722 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4726 SDValue Ptr = MaskLoad->getBasePtr();
4727 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4728 Ptr->getOpcode() == X86ISD::WrapperRIP)
4729 Ptr = Ptr->getOperand(0);
4731 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4732 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4735 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4736 DecodePSHUFBMask(C, Mask);
4744 case X86ISD::VPERMI:
4745 ImmN = N->getOperand(N->getNumOperands()-1);
4746 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4751 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4753 case X86ISD::VPERM2X128:
4754 ImmN = N->getOperand(N->getNumOperands()-1);
4755 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4756 if (Mask.empty()) return false;
4757 // Mask only contains negative index if an element is zero.
4758 if (std::any_of(Mask.begin(), Mask.end(),
4759 [](int M){ return M == SM_SentinelZero; }))
4762 case X86ISD::MOVSLDUP:
4763 DecodeMOVSLDUPMask(VT, Mask);
4766 case X86ISD::MOVSHDUP:
4767 DecodeMOVSHDUPMask(VT, Mask);
4770 case X86ISD::MOVDDUP:
4771 DecodeMOVDDUPMask(VT, Mask);
4774 case X86ISD::MOVLHPD:
4775 case X86ISD::MOVLPD:
4776 case X86ISD::MOVLPS:
4777 // Not yet implemented
4779 case X86ISD::VPERMV: {
4781 SDValue MaskNode = N->getOperand(0);
4782 while (MaskNode->getOpcode() == ISD::BITCAST)
4783 MaskNode = MaskNode->getOperand(0);
4785 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4786 SmallVector<uint64_t, 32> RawMask;
4787 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4788 // If we have a build-vector, then things are easy.
4789 assert(MaskNode.getValueType().isInteger() &&
4790 MaskNode.getValueType().getVectorNumElements() ==
4791 VT.getVectorNumElements());
4793 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4794 SDValue Op = MaskNode->getOperand(i);
4795 if (Op->getOpcode() == ISD::UNDEF)
4796 RawMask.push_back((uint64_t)SM_SentinelUndef);
4797 else if (isa<ConstantSDNode>(Op)) {
4798 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4799 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4803 DecodeVPERMVMask(RawMask, Mask);
4806 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4807 unsigned NumEltsInMask = MaskNode->getNumOperands();
4808 MaskNode = MaskNode->getOperand(0);
4809 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4811 APInt MaskEltValue = CN->getAPIntValue();
4812 for (unsigned i = 0; i < NumEltsInMask; ++i)
4813 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4814 DecodeVPERMVMask(RawMask, Mask);
4817 // It may be a scalar load
4820 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4824 SDValue Ptr = MaskLoad->getBasePtr();
4825 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4826 Ptr->getOpcode() == X86ISD::WrapperRIP)
4827 Ptr = Ptr->getOperand(0);
4829 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4830 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4833 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4835 DecodeVPERMVMask(C, VT, Mask);
4842 case X86ISD::VPERMV3: {
4844 SDValue MaskNode = N->getOperand(1);
4845 while (MaskNode->getOpcode() == ISD::BITCAST)
4846 MaskNode = MaskNode->getOperand(1);
4848 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4849 // If we have a build-vector, then things are easy.
4850 assert(MaskNode.getValueType().isInteger() &&
4851 MaskNode.getValueType().getVectorNumElements() ==
4852 VT.getVectorNumElements());
4854 SmallVector<uint64_t, 32> RawMask;
4855 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4857 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4858 SDValue Op = MaskNode->getOperand(i);
4859 if (Op->getOpcode() == ISD::UNDEF)
4860 RawMask.push_back((uint64_t)SM_SentinelUndef);
4862 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4865 APInt MaskElement = CN->getAPIntValue();
4866 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4869 DecodeVPERMV3Mask(RawMask, Mask);
4873 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4877 SDValue Ptr = MaskLoad->getBasePtr();
4878 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4879 Ptr->getOpcode() == X86ISD::WrapperRIP)
4880 Ptr = Ptr->getOperand(0);
4882 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4883 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4886 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4888 DecodeVPERMV3Mask(C, VT, Mask);
4895 default: llvm_unreachable("unknown target shuffle node");
4898 // If we have a fake unary shuffle, the shuffle mask is spread across two
4899 // inputs that are actually the same node. Re-map the mask to always point
4900 // into the first input.
4903 if (M >= (int)Mask.size())
4909 /// Returns the scalar element that will make up the ith
4910 /// element of the result of the vector shuffle.
4911 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4914 return SDValue(); // Limit search depth.
4916 SDValue V = SDValue(N, 0);
4917 EVT VT = V.getValueType();
4918 unsigned Opcode = V.getOpcode();
4920 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4921 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4922 int Elt = SV->getMaskElt(Index);
4925 return DAG.getUNDEF(VT.getVectorElementType());
4927 unsigned NumElems = VT.getVectorNumElements();
4928 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4929 : SV->getOperand(1);
4930 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4933 // Recurse into target specific vector shuffles to find scalars.
4934 if (isTargetShuffle(Opcode)) {
4935 MVT ShufVT = V.getSimpleValueType();
4936 unsigned NumElems = ShufVT.getVectorNumElements();
4937 SmallVector<int, 16> ShuffleMask;
4940 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4943 int Elt = ShuffleMask[Index];
4945 return DAG.getUNDEF(ShufVT.getVectorElementType());
4947 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4949 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4953 // Actual nodes that may contain scalar elements
4954 if (Opcode == ISD::BITCAST) {
4955 V = V.getOperand(0);
4956 EVT SrcVT = V.getValueType();
4957 unsigned NumElems = VT.getVectorNumElements();
4959 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4963 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4964 return (Index == 0) ? V.getOperand(0)
4965 : DAG.getUNDEF(VT.getVectorElementType());
4967 if (V.getOpcode() == ISD::BUILD_VECTOR)
4968 return V.getOperand(Index);
4973 /// Custom lower build_vector of v16i8.
4974 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4975 unsigned NumNonZero, unsigned NumZero,
4977 const X86Subtarget* Subtarget,
4978 const TargetLowering &TLI) {
4986 // SSE4.1 - use PINSRB to insert each byte directly.
4987 if (Subtarget->hasSSE41()) {
4988 for (unsigned i = 0; i < 16; ++i) {
4989 bool isNonZero = (NonZeros & (1 << i)) != 0;
4993 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4995 V = DAG.getUNDEF(MVT::v16i8);
4998 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4999 MVT::v16i8, V, Op.getOperand(i),
5000 DAG.getIntPtrConstant(i, dl));
5007 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5008 for (unsigned i = 0; i < 16; ++i) {
5009 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5010 if (ThisIsNonZero && First) {
5012 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5014 V = DAG.getUNDEF(MVT::v8i16);
5019 SDValue ThisElt, LastElt;
5020 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5021 if (LastIsNonZero) {
5022 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5023 MVT::i16, Op.getOperand(i-1));
5025 if (ThisIsNonZero) {
5026 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5027 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5028 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5030 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5034 if (ThisElt.getNode())
5035 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5036 DAG.getIntPtrConstant(i/2, dl));
5040 return DAG.getBitcast(MVT::v16i8, V);
5043 /// Custom lower build_vector of v8i16.
5044 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5045 unsigned NumNonZero, unsigned NumZero,
5047 const X86Subtarget* Subtarget,
5048 const TargetLowering &TLI) {
5055 for (unsigned i = 0; i < 8; ++i) {
5056 bool isNonZero = (NonZeros & (1 << i)) != 0;
5060 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5062 V = DAG.getUNDEF(MVT::v8i16);
5065 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5066 MVT::v8i16, V, Op.getOperand(i),
5067 DAG.getIntPtrConstant(i, dl));
5074 /// Custom lower build_vector of v4i32 or v4f32.
5075 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5076 const X86Subtarget *Subtarget,
5077 const TargetLowering &TLI) {
5078 // Find all zeroable elements.
5079 std::bitset<4> Zeroable;
5080 for (int i=0; i < 4; ++i) {
5081 SDValue Elt = Op->getOperand(i);
5082 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5084 assert(Zeroable.size() - Zeroable.count() > 1 &&
5085 "We expect at least two non-zero elements!");
5087 // We only know how to deal with build_vector nodes where elements are either
5088 // zeroable or extract_vector_elt with constant index.
5089 SDValue FirstNonZero;
5090 unsigned FirstNonZeroIdx;
5091 for (unsigned i=0; i < 4; ++i) {
5094 SDValue Elt = Op->getOperand(i);
5095 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5096 !isa<ConstantSDNode>(Elt.getOperand(1)))
5098 // Make sure that this node is extracting from a 128-bit vector.
5099 MVT VT = Elt.getOperand(0).getSimpleValueType();
5100 if (!VT.is128BitVector())
5102 if (!FirstNonZero.getNode()) {
5104 FirstNonZeroIdx = i;
5108 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5109 SDValue V1 = FirstNonZero.getOperand(0);
5110 MVT VT = V1.getSimpleValueType();
5112 // See if this build_vector can be lowered as a blend with zero.
5114 unsigned EltMaskIdx, EltIdx;
5116 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5117 if (Zeroable[EltIdx]) {
5118 // The zero vector will be on the right hand side.
5119 Mask[EltIdx] = EltIdx+4;
5123 Elt = Op->getOperand(EltIdx);
5124 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5125 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5126 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5128 Mask[EltIdx] = EltIdx;
5132 // Let the shuffle legalizer deal with blend operations.
5133 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5134 if (V1.getSimpleValueType() != VT)
5135 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5136 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5139 // See if we can lower this build_vector to a INSERTPS.
5140 if (!Subtarget->hasSSE41())
5143 SDValue V2 = Elt.getOperand(0);
5144 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5147 bool CanFold = true;
5148 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5152 SDValue Current = Op->getOperand(i);
5153 SDValue SrcVector = Current->getOperand(0);
5156 CanFold = SrcVector == V1 &&
5157 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5163 assert(V1.getNode() && "Expected at least two non-zero elements!");
5164 if (V1.getSimpleValueType() != MVT::v4f32)
5165 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5166 if (V2.getSimpleValueType() != MVT::v4f32)
5167 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5169 // Ok, we can emit an INSERTPS instruction.
5170 unsigned ZMask = Zeroable.to_ulong();
5172 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5173 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5175 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5176 DAG.getIntPtrConstant(InsertPSMask, DL));
5177 return DAG.getBitcast(VT, Result);
5180 /// Return a vector logical shift node.
5181 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5182 unsigned NumBits, SelectionDAG &DAG,
5183 const TargetLowering &TLI, SDLoc dl) {
5184 assert(VT.is128BitVector() && "Unknown type for VShift");
5185 MVT ShVT = MVT::v2i64;
5186 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5187 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5188 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5189 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5190 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5191 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5195 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5197 // Check if the scalar load can be widened into a vector load. And if
5198 // the address is "base + cst" see if the cst can be "absorbed" into
5199 // the shuffle mask.
5200 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5201 SDValue Ptr = LD->getBasePtr();
5202 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5204 EVT PVT = LD->getValueType(0);
5205 if (PVT != MVT::i32 && PVT != MVT::f32)
5210 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5211 FI = FINode->getIndex();
5213 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5214 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5215 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5216 Offset = Ptr.getConstantOperandVal(1);
5217 Ptr = Ptr.getOperand(0);
5222 // FIXME: 256-bit vector instructions don't require a strict alignment,
5223 // improve this code to support it better.
5224 unsigned RequiredAlign = VT.getSizeInBits()/8;
5225 SDValue Chain = LD->getChain();
5226 // Make sure the stack object alignment is at least 16 or 32.
5227 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5228 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5229 if (MFI->isFixedObjectIndex(FI)) {
5230 // Can't change the alignment. FIXME: It's possible to compute
5231 // the exact stack offset and reference FI + adjust offset instead.
5232 // If someone *really* cares about this. That's the way to implement it.
5235 MFI->setObjectAlignment(FI, RequiredAlign);
5239 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5240 // Ptr + (Offset & ~15).
5243 if ((Offset % RequiredAlign) & 3)
5245 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5248 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5249 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5252 int EltNo = (Offset - StartOffset) >> 2;
5253 unsigned NumElems = VT.getVectorNumElements();
5255 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5256 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5257 LD->getPointerInfo().getWithOffset(StartOffset),
5258 false, false, false, 0);
5260 SmallVector<int, 8> Mask(NumElems, EltNo);
5262 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5268 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5269 /// elements can be replaced by a single large load which has the same value as
5270 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5272 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5274 /// FIXME: we'd also like to handle the case where the last elements are zero
5275 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5276 /// There's even a handy isZeroNode for that purpose.
5277 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5278 SDLoc &DL, SelectionDAG &DAG,
5279 bool isAfterLegalize) {
5280 unsigned NumElems = Elts.size();
5282 LoadSDNode *LDBase = nullptr;
5283 unsigned LastLoadedElt = -1U;
5285 // For each element in the initializer, see if we've found a load or an undef.
5286 // If we don't find an initial load element, or later load elements are
5287 // non-consecutive, bail out.
5288 for (unsigned i = 0; i < NumElems; ++i) {
5289 SDValue Elt = Elts[i];
5290 // Look through a bitcast.
5291 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5292 Elt = Elt.getOperand(0);
5293 if (!Elt.getNode() ||
5294 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5297 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5299 LDBase = cast<LoadSDNode>(Elt.getNode());
5303 if (Elt.getOpcode() == ISD::UNDEF)
5306 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5307 EVT LdVT = Elt.getValueType();
5308 // Each loaded element must be the correct fractional portion of the
5309 // requested vector load.
5310 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5312 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5317 // If we have found an entire vector of loads and undefs, then return a large
5318 // load of the entire vector width starting at the base pointer. If we found
5319 // consecutive loads for the low half, generate a vzext_load node.
5320 if (LastLoadedElt == NumElems - 1) {
5321 assert(LDBase && "Did not find base load for merging consecutive loads");
5322 EVT EltVT = LDBase->getValueType(0);
5323 // Ensure that the input vector size for the merged loads matches the
5324 // cumulative size of the input elements.
5325 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5328 if (isAfterLegalize &&
5329 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5332 SDValue NewLd = SDValue();
5334 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5335 LDBase->getPointerInfo(), LDBase->isVolatile(),
5336 LDBase->isNonTemporal(), LDBase->isInvariant(),
5337 LDBase->getAlignment());
5339 if (LDBase->hasAnyUseOfValue(1)) {
5340 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5342 SDValue(NewLd.getNode(), 1));
5343 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5344 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5345 SDValue(NewLd.getNode(), 1));
5351 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5352 //of a v4i32 / v4f32. It's probably worth generalizing.
5353 EVT EltVT = VT.getVectorElementType();
5354 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5355 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5356 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5357 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5359 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5360 LDBase->getPointerInfo(),
5361 LDBase->getAlignment(),
5362 false/*isVolatile*/, true/*ReadMem*/,
5365 // Make sure the newly-created LOAD is in the same position as LDBase in
5366 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5367 // update uses of LDBase's output chain to use the TokenFactor.
5368 if (LDBase->hasAnyUseOfValue(1)) {
5369 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5370 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5371 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5372 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5373 SDValue(ResNode.getNode(), 1));
5376 return DAG.getBitcast(VT, ResNode);
5381 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5382 /// to generate a splat value for the following cases:
5383 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5384 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5385 /// a scalar load, or a constant.
5386 /// The VBROADCAST node is returned when a pattern is found,
5387 /// or SDValue() otherwise.
5388 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5389 SelectionDAG &DAG) {
5390 // VBROADCAST requires AVX.
5391 // TODO: Splats could be generated for non-AVX CPUs using SSE
5392 // instructions, but there's less potential gain for only 128-bit vectors.
5393 if (!Subtarget->hasAVX())
5396 MVT VT = Op.getSimpleValueType();
5399 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5400 "Unsupported vector type for broadcast.");
5405 switch (Op.getOpcode()) {
5407 // Unknown pattern found.
5410 case ISD::BUILD_VECTOR: {
5411 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5412 BitVector UndefElements;
5413 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5415 // We need a splat of a single value to use broadcast, and it doesn't
5416 // make any sense if the value is only in one element of the vector.
5417 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5421 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5422 Ld.getOpcode() == ISD::ConstantFP);
5424 // Make sure that all of the users of a non-constant load are from the
5425 // BUILD_VECTOR node.
5426 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5431 case ISD::VECTOR_SHUFFLE: {
5432 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5434 // Shuffles must have a splat mask where the first element is
5436 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5439 SDValue Sc = Op.getOperand(0);
5440 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5441 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5443 if (!Subtarget->hasInt256())
5446 // Use the register form of the broadcast instruction available on AVX2.
5447 if (VT.getSizeInBits() >= 256)
5448 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5449 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5452 Ld = Sc.getOperand(0);
5453 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5454 Ld.getOpcode() == ISD::ConstantFP);
5456 // The scalar_to_vector node and the suspected
5457 // load node must have exactly one user.
5458 // Constants may have multiple users.
5460 // AVX-512 has register version of the broadcast
5461 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5462 Ld.getValueType().getSizeInBits() >= 32;
5463 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5470 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5471 bool IsGE256 = (VT.getSizeInBits() >= 256);
5473 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5474 // instruction to save 8 or more bytes of constant pool data.
5475 // TODO: If multiple splats are generated to load the same constant,
5476 // it may be detrimental to overall size. There needs to be a way to detect
5477 // that condition to know if this is truly a size win.
5478 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5480 // Handle broadcasting a single constant scalar from the constant pool
5482 // On Sandybridge (no AVX2), it is still better to load a constant vector
5483 // from the constant pool and not to broadcast it from a scalar.
5484 // But override that restriction when optimizing for size.
5485 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5486 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5487 EVT CVT = Ld.getValueType();
5488 assert(!CVT.isVector() && "Must not broadcast a vector type");
5490 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5491 // For size optimization, also splat v2f64 and v2i64, and for size opt
5492 // with AVX2, also splat i8 and i16.
5493 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5494 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5495 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5496 const Constant *C = nullptr;
5497 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5498 C = CI->getConstantIntValue();
5499 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5500 C = CF->getConstantFPValue();
5502 assert(C && "Invalid constant type");
5504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5506 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5507 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5509 CVT, dl, DAG.getEntryNode(), CP,
5510 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5511 false, false, Alignment);
5513 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5517 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5519 // Handle AVX2 in-register broadcasts.
5520 if (!IsLoad && Subtarget->hasInt256() &&
5521 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5522 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5524 // The scalar source must be a normal load.
5528 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5529 (Subtarget->hasVLX() && ScalarSize == 64))
5530 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5532 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5533 // double since there is no vbroadcastsd xmm
5534 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5535 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5536 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5539 // Unsupported broadcast.
5543 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5544 /// underlying vector and index.
5546 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5548 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5550 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5551 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5554 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5556 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5558 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5559 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5562 // In this case the vector is the extract_subvector expression and the index
5563 // is 2, as specified by the shuffle.
5564 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5565 SDValue ShuffleVec = SVOp->getOperand(0);
5566 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5567 assert(ShuffleVecVT.getVectorElementType() ==
5568 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5570 int ShuffleIdx = SVOp->getMaskElt(Idx);
5571 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5572 ExtractedFromVec = ShuffleVec;
5578 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5579 MVT VT = Op.getSimpleValueType();
5581 // Skip if insert_vec_elt is not supported.
5582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5583 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5587 unsigned NumElems = Op.getNumOperands();
5591 SmallVector<unsigned, 4> InsertIndices;
5592 SmallVector<int, 8> Mask(NumElems, -1);
5594 for (unsigned i = 0; i != NumElems; ++i) {
5595 unsigned Opc = Op.getOperand(i).getOpcode();
5597 if (Opc == ISD::UNDEF)
5600 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5601 // Quit if more than 1 elements need inserting.
5602 if (InsertIndices.size() > 1)
5605 InsertIndices.push_back(i);
5609 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5610 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5611 // Quit if non-constant index.
5612 if (!isa<ConstantSDNode>(ExtIdx))
5614 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5616 // Quit if extracted from vector of different type.
5617 if (ExtractedFromVec.getValueType() != VT)
5620 if (!VecIn1.getNode())
5621 VecIn1 = ExtractedFromVec;
5622 else if (VecIn1 != ExtractedFromVec) {
5623 if (!VecIn2.getNode())
5624 VecIn2 = ExtractedFromVec;
5625 else if (VecIn2 != ExtractedFromVec)
5626 // Quit if more than 2 vectors to shuffle
5630 if (ExtractedFromVec == VecIn1)
5632 else if (ExtractedFromVec == VecIn2)
5633 Mask[i] = Idx + NumElems;
5636 if (!VecIn1.getNode())
5639 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5640 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5641 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5642 unsigned Idx = InsertIndices[i];
5643 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5644 DAG.getIntPtrConstant(Idx, DL));
5650 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5651 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5652 Op.getScalarValueSizeInBits() == 1 &&
5653 "Can not convert non-constant vector");
5654 uint64_t Immediate = 0;
5655 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5656 SDValue In = Op.getOperand(idx);
5657 if (In.getOpcode() != ISD::UNDEF)
5658 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5662 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5663 return DAG.getConstant(Immediate, dl, VT);
5665 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5667 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5669 MVT VT = Op.getSimpleValueType();
5670 assert((VT.getVectorElementType() == MVT::i1) &&
5671 "Unexpected type in LowerBUILD_VECTORvXi1!");
5674 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5675 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5676 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5677 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5680 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5681 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5682 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5683 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5686 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5687 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5688 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5689 return DAG.getBitcast(VT, Imm);
5690 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5691 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5692 DAG.getIntPtrConstant(0, dl));
5695 // Vector has one or more non-const elements
5696 uint64_t Immediate = 0;
5697 SmallVector<unsigned, 16> NonConstIdx;
5698 bool IsSplat = true;
5699 bool HasConstElts = false;
5701 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5702 SDValue In = Op.getOperand(idx);
5703 if (In.getOpcode() == ISD::UNDEF)
5705 if (!isa<ConstantSDNode>(In))
5706 NonConstIdx.push_back(idx);
5708 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5709 HasConstElts = true;
5713 else if (In != Op.getOperand(SplatIdx))
5717 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5719 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5720 DAG.getConstant(1, dl, VT),
5721 DAG.getConstant(0, dl, VT));
5723 // insert elements one by one
5727 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5728 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5730 else if (HasConstElts)
5731 Imm = DAG.getConstant(0, dl, VT);
5733 Imm = DAG.getUNDEF(VT);
5734 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5735 DstVec = DAG.getBitcast(VT, Imm);
5737 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5738 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5739 DAG.getIntPtrConstant(0, dl));
5742 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5743 unsigned InsertIdx = NonConstIdx[i];
5744 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5745 Op.getOperand(InsertIdx),
5746 DAG.getIntPtrConstant(InsertIdx, dl));
5751 /// \brief Return true if \p N implements a horizontal binop and return the
5752 /// operands for the horizontal binop into V0 and V1.
5754 /// This is a helper function of LowerToHorizontalOp().
5755 /// This function checks that the build_vector \p N in input implements a
5756 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5757 /// operation to match.
5758 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5759 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5760 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5763 /// This function only analyzes elements of \p N whose indices are
5764 /// in range [BaseIdx, LastIdx).
5765 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5767 unsigned BaseIdx, unsigned LastIdx,
5768 SDValue &V0, SDValue &V1) {
5769 EVT VT = N->getValueType(0);
5771 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5772 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5773 "Invalid Vector in input!");
5775 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5776 bool CanFold = true;
5777 unsigned ExpectedVExtractIdx = BaseIdx;
5778 unsigned NumElts = LastIdx - BaseIdx;
5779 V0 = DAG.getUNDEF(VT);
5780 V1 = DAG.getUNDEF(VT);
5782 // Check if N implements a horizontal binop.
5783 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5784 SDValue Op = N->getOperand(i + BaseIdx);
5787 if (Op->getOpcode() == ISD::UNDEF) {
5788 // Update the expected vector extract index.
5789 if (i * 2 == NumElts)
5790 ExpectedVExtractIdx = BaseIdx;
5791 ExpectedVExtractIdx += 2;
5795 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5800 SDValue Op0 = Op.getOperand(0);
5801 SDValue Op1 = Op.getOperand(1);
5803 // Try to match the following pattern:
5804 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5805 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5806 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5807 Op0.getOperand(0) == Op1.getOperand(0) &&
5808 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5809 isa<ConstantSDNode>(Op1.getOperand(1)));
5813 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5814 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5816 if (i * 2 < NumElts) {
5817 if (V0.getOpcode() == ISD::UNDEF) {
5818 V0 = Op0.getOperand(0);
5819 if (V0.getValueType() != VT)
5823 if (V1.getOpcode() == ISD::UNDEF) {
5824 V1 = Op0.getOperand(0);
5825 if (V1.getValueType() != VT)
5828 if (i * 2 == NumElts)
5829 ExpectedVExtractIdx = BaseIdx;
5832 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5833 if (I0 == ExpectedVExtractIdx)
5834 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5835 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5836 // Try to match the following dag sequence:
5837 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5838 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5842 ExpectedVExtractIdx += 2;
5848 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5849 /// a concat_vector.
5851 /// This is a helper function of LowerToHorizontalOp().
5852 /// This function expects two 256-bit vectors called V0 and V1.
5853 /// At first, each vector is split into two separate 128-bit vectors.
5854 /// Then, the resulting 128-bit vectors are used to implement two
5855 /// horizontal binary operations.
5857 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5859 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5860 /// the two new horizontal binop.
5861 /// When Mode is set, the first horizontal binop dag node would take as input
5862 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5863 /// horizontal binop dag node would take as input the lower 128-bit of V1
5864 /// and the upper 128-bit of V1.
5866 /// HADD V0_LO, V0_HI
5867 /// HADD V1_LO, V1_HI
5869 /// Otherwise, the first horizontal binop dag node takes as input the lower
5870 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5871 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5873 /// HADD V0_LO, V1_LO
5874 /// HADD V0_HI, V1_HI
5876 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5877 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5878 /// the upper 128-bits of the result.
5879 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5880 SDLoc DL, SelectionDAG &DAG,
5881 unsigned X86Opcode, bool Mode,
5882 bool isUndefLO, bool isUndefHI) {
5883 EVT VT = V0.getValueType();
5884 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5885 "Invalid nodes in input!");
5887 unsigned NumElts = VT.getVectorNumElements();
5888 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5889 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5890 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5891 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5892 EVT NewVT = V0_LO.getValueType();
5894 SDValue LO = DAG.getUNDEF(NewVT);
5895 SDValue HI = DAG.getUNDEF(NewVT);
5898 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5899 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5900 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5901 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5902 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5904 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5905 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5906 V1_LO->getOpcode() != ISD::UNDEF))
5907 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5909 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5910 V1_HI->getOpcode() != ISD::UNDEF))
5911 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5914 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5917 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5919 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5920 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5921 EVT VT = BV->getValueType(0);
5922 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5923 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5927 unsigned NumElts = VT.getVectorNumElements();
5928 SDValue InVec0 = DAG.getUNDEF(VT);
5929 SDValue InVec1 = DAG.getUNDEF(VT);
5931 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5932 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5934 // Odd-numbered elements in the input build vector are obtained from
5935 // adding two integer/float elements.
5936 // Even-numbered elements in the input build vector are obtained from
5937 // subtracting two integer/float elements.
5938 unsigned ExpectedOpcode = ISD::FSUB;
5939 unsigned NextExpectedOpcode = ISD::FADD;
5940 bool AddFound = false;
5941 bool SubFound = false;
5943 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5944 SDValue Op = BV->getOperand(i);
5946 // Skip 'undef' values.
5947 unsigned Opcode = Op.getOpcode();
5948 if (Opcode == ISD::UNDEF) {
5949 std::swap(ExpectedOpcode, NextExpectedOpcode);
5953 // Early exit if we found an unexpected opcode.
5954 if (Opcode != ExpectedOpcode)
5957 SDValue Op0 = Op.getOperand(0);
5958 SDValue Op1 = Op.getOperand(1);
5960 // Try to match the following pattern:
5961 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5962 // Early exit if we cannot match that sequence.
5963 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5964 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5965 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5966 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5967 Op0.getOperand(1) != Op1.getOperand(1))
5970 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5974 // We found a valid add/sub node. Update the information accordingly.
5980 // Update InVec0 and InVec1.
5981 if (InVec0.getOpcode() == ISD::UNDEF) {
5982 InVec0 = Op0.getOperand(0);
5983 if (InVec0.getValueType() != VT)
5986 if (InVec1.getOpcode() == ISD::UNDEF) {
5987 InVec1 = Op1.getOperand(0);
5988 if (InVec1.getValueType() != VT)
5992 // Make sure that operands in input to each add/sub node always
5993 // come from a same pair of vectors.
5994 if (InVec0 != Op0.getOperand(0)) {
5995 if (ExpectedOpcode == ISD::FSUB)
5998 // FADD is commutable. Try to commute the operands
5999 // and then test again.
6000 std::swap(Op0, Op1);
6001 if (InVec0 != Op0.getOperand(0))
6005 if (InVec1 != Op1.getOperand(0))
6008 // Update the pair of expected opcodes.
6009 std::swap(ExpectedOpcode, NextExpectedOpcode);
6012 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6013 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6014 InVec1.getOpcode() != ISD::UNDEF)
6015 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6020 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6021 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6022 const X86Subtarget *Subtarget,
6023 SelectionDAG &DAG) {
6024 EVT VT = BV->getValueType(0);
6025 unsigned NumElts = VT.getVectorNumElements();
6026 unsigned NumUndefsLO = 0;
6027 unsigned NumUndefsHI = 0;
6028 unsigned Half = NumElts/2;
6030 // Count the number of UNDEF operands in the build_vector in input.
6031 for (unsigned i = 0, e = Half; i != e; ++i)
6032 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6035 for (unsigned i = Half, e = NumElts; i != e; ++i)
6036 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6039 // Early exit if this is either a build_vector of all UNDEFs or all the
6040 // operands but one are UNDEF.
6041 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6045 SDValue InVec0, InVec1;
6046 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6047 // Try to match an SSE3 float HADD/HSUB.
6048 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6049 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6051 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6052 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6053 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6054 // Try to match an SSSE3 integer HADD/HSUB.
6055 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6056 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6058 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6059 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6062 if (!Subtarget->hasAVX())
6065 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6066 // Try to match an AVX horizontal add/sub of packed single/double
6067 // precision floating point values from 256-bit vectors.
6068 SDValue InVec2, InVec3;
6069 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6070 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6071 ((InVec0.getOpcode() == ISD::UNDEF ||
6072 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6073 ((InVec1.getOpcode() == ISD::UNDEF ||
6074 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6075 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6077 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6078 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6079 ((InVec0.getOpcode() == ISD::UNDEF ||
6080 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6081 ((InVec1.getOpcode() == ISD::UNDEF ||
6082 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6083 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6084 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6085 // Try to match an AVX2 horizontal add/sub of signed integers.
6086 SDValue InVec2, InVec3;
6088 bool CanFold = true;
6090 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6091 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6092 ((InVec0.getOpcode() == ISD::UNDEF ||
6093 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6094 ((InVec1.getOpcode() == ISD::UNDEF ||
6095 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6096 X86Opcode = X86ISD::HADD;
6097 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6098 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6099 ((InVec0.getOpcode() == ISD::UNDEF ||
6100 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6101 ((InVec1.getOpcode() == ISD::UNDEF ||
6102 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6103 X86Opcode = X86ISD::HSUB;
6108 // Fold this build_vector into a single horizontal add/sub.
6109 // Do this only if the target has AVX2.
6110 if (Subtarget->hasAVX2())
6111 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6113 // Do not try to expand this build_vector into a pair of horizontal
6114 // add/sub if we can emit a pair of scalar add/sub.
6115 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6118 // Convert this build_vector into a pair of horizontal binop followed by
6120 bool isUndefLO = NumUndefsLO == Half;
6121 bool isUndefHI = NumUndefsHI == Half;
6122 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6123 isUndefLO, isUndefHI);
6127 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6128 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6130 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6131 X86Opcode = X86ISD::HADD;
6132 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6133 X86Opcode = X86ISD::HSUB;
6134 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6135 X86Opcode = X86ISD::FHADD;
6136 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6137 X86Opcode = X86ISD::FHSUB;
6141 // Don't try to expand this build_vector into a pair of horizontal add/sub
6142 // if we can simply emit a pair of scalar add/sub.
6143 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6146 // Convert this build_vector into two horizontal add/sub followed by
6148 bool isUndefLO = NumUndefsLO == Half;
6149 bool isUndefHI = NumUndefsHI == Half;
6150 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6151 isUndefLO, isUndefHI);
6158 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6161 MVT VT = Op.getSimpleValueType();
6162 MVT ExtVT = VT.getVectorElementType();
6163 unsigned NumElems = Op.getNumOperands();
6165 // Generate vectors for predicate vectors.
6166 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6167 return LowerBUILD_VECTORvXi1(Op, DAG);
6169 // Vectors containing all zeros can be matched by pxor and xorps later
6170 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6171 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6172 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6173 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6176 return getZeroVector(VT, Subtarget, DAG, dl);
6179 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6180 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6181 // vpcmpeqd on 256-bit vectors.
6182 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6183 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6186 if (!VT.is512BitVector())
6187 return getOnesVector(VT, Subtarget, DAG, dl);
6190 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6191 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6193 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6194 return HorizontalOp;
6195 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6198 unsigned EVTBits = ExtVT.getSizeInBits();
6200 unsigned NumZero = 0;
6201 unsigned NumNonZero = 0;
6202 unsigned NonZeros = 0;
6203 bool IsAllConstants = true;
6204 SmallSet<SDValue, 8> Values;
6205 for (unsigned i = 0; i < NumElems; ++i) {
6206 SDValue Elt = Op.getOperand(i);
6207 if (Elt.getOpcode() == ISD::UNDEF)
6210 if (Elt.getOpcode() != ISD::Constant &&
6211 Elt.getOpcode() != ISD::ConstantFP)
6212 IsAllConstants = false;
6213 if (X86::isZeroNode(Elt))
6216 NonZeros |= (1 << i);
6221 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6222 if (NumNonZero == 0)
6223 return DAG.getUNDEF(VT);
6225 // Special case for single non-zero, non-undef, element.
6226 if (NumNonZero == 1) {
6227 unsigned Idx = countTrailingZeros(NonZeros);
6228 SDValue Item = Op.getOperand(Idx);
6230 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6231 // the value are obviously zero, truncate the value to i32 and do the
6232 // insertion that way. Only do this if the value is non-constant or if the
6233 // value is a constant being inserted into element 0. It is cheaper to do
6234 // a constant pool load than it is to do a movd + shuffle.
6235 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6236 (!IsAllConstants || Idx == 0)) {
6237 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6239 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6240 EVT VecVT = MVT::v4i32;
6242 // Truncate the value (which may itself be a constant) to i32, and
6243 // convert it to a vector with movd (S2V+shuffle to zero extend).
6244 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6245 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6246 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6247 Item, Idx * 2, true, Subtarget, DAG));
6251 // If we have a constant or non-constant insertion into the low element of
6252 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6253 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6254 // depending on what the source datatype is.
6257 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6259 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6260 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6261 if (VT.is512BitVector()) {
6262 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6263 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6264 Item, DAG.getIntPtrConstant(0, dl));
6266 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6267 "Expected an SSE value type!");
6268 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6269 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6270 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6273 // We can't directly insert an i8 or i16 into a vector, so zero extend
6275 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6276 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6277 if (VT.is256BitVector()) {
6278 if (Subtarget->hasAVX()) {
6279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6280 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6282 // Without AVX, we need to extend to a 128-bit vector and then
6283 // insert into the 256-bit vector.
6284 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6285 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6286 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6289 assert(VT.is128BitVector() && "Expected an SSE value type!");
6290 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6291 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6293 return DAG.getBitcast(VT, Item);
6297 // Is it a vector logical left shift?
6298 if (NumElems == 2 && Idx == 1 &&
6299 X86::isZeroNode(Op.getOperand(0)) &&
6300 !X86::isZeroNode(Op.getOperand(1))) {
6301 unsigned NumBits = VT.getSizeInBits();
6302 return getVShift(true, VT,
6303 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6304 VT, Op.getOperand(1)),
6305 NumBits/2, DAG, *this, dl);
6308 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6311 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6312 // is a non-constant being inserted into an element other than the low one,
6313 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6314 // movd/movss) to move this into the low element, then shuffle it into
6316 if (EVTBits == 32) {
6317 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6318 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6322 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6323 if (Values.size() == 1) {
6324 if (EVTBits == 32) {
6325 // Instead of a shuffle like this:
6326 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6327 // Check if it's possible to issue this instead.
6328 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6329 unsigned Idx = countTrailingZeros(NonZeros);
6330 SDValue Item = Op.getOperand(Idx);
6331 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6332 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6337 // A vector full of immediates; various special cases are already
6338 // handled, so this is best done with a single constant-pool load.
6342 // For AVX-length vectors, see if we can use a vector load to get all of the
6343 // elements, otherwise build the individual 128-bit pieces and use
6344 // shuffles to put them in place.
6345 if (VT.is256BitVector() || VT.is512BitVector()) {
6346 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6348 // Check for a build vector of consecutive loads.
6349 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6352 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6354 // Build both the lower and upper subvector.
6355 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6356 makeArrayRef(&V[0], NumElems/2));
6357 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6358 makeArrayRef(&V[NumElems / 2], NumElems/2));
6360 // Recreate the wider vector with the lower and upper part.
6361 if (VT.is256BitVector())
6362 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6363 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6366 // Let legalizer expand 2-wide build_vectors.
6367 if (EVTBits == 64) {
6368 if (NumNonZero == 1) {
6369 // One half is zero or undef.
6370 unsigned Idx = countTrailingZeros(NonZeros);
6371 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6372 Op.getOperand(Idx));
6373 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6378 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6379 if (EVTBits == 8 && NumElems == 16)
6380 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6384 if (EVTBits == 16 && NumElems == 8)
6385 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6389 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6390 if (EVTBits == 32 && NumElems == 4)
6391 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6394 // If element VT is == 32 bits, turn it into a number of shuffles.
6395 SmallVector<SDValue, 8> V(NumElems);
6396 if (NumElems == 4 && NumZero > 0) {
6397 for (unsigned i = 0; i < 4; ++i) {
6398 bool isZero = !(NonZeros & (1 << i));
6400 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6402 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6405 for (unsigned i = 0; i < 2; ++i) {
6406 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6409 V[i] = V[i*2]; // Must be a zero vector.
6412 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6415 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6418 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6423 bool Reverse1 = (NonZeros & 0x3) == 2;
6424 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6428 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6429 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6431 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6434 if (Values.size() > 1 && VT.is128BitVector()) {
6435 // Check for a build vector of consecutive loads.
6436 for (unsigned i = 0; i < NumElems; ++i)
6437 V[i] = Op.getOperand(i);
6439 // Check for elements which are consecutive loads.
6440 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6443 // Check for a build vector from mostly shuffle plus few inserting.
6444 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6447 // For SSE 4.1, use insertps to put the high elements into the low element.
6448 if (Subtarget->hasSSE41()) {
6450 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6451 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6453 Result = DAG.getUNDEF(VT);
6455 for (unsigned i = 1; i < NumElems; ++i) {
6456 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6457 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6458 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6463 // Otherwise, expand into a number of unpckl*, start by extending each of
6464 // our (non-undef) elements to the full vector width with the element in the
6465 // bottom slot of the vector (which generates no code for SSE).
6466 for (unsigned i = 0; i < NumElems; ++i) {
6467 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6468 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6470 V[i] = DAG.getUNDEF(VT);
6473 // Next, we iteratively mix elements, e.g. for v4f32:
6474 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6475 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6476 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6477 unsigned EltStride = NumElems >> 1;
6478 while (EltStride != 0) {
6479 for (unsigned i = 0; i < EltStride; ++i) {
6480 // If V[i+EltStride] is undef and this is the first round of mixing,
6481 // then it is safe to just drop this shuffle: V[i] is already in the
6482 // right place, the one element (since it's the first round) being
6483 // inserted as undef can be dropped. This isn't safe for successive
6484 // rounds because they will permute elements within both vectors.
6485 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6486 EltStride == NumElems/2)
6489 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6498 // 256-bit AVX can use the vinsertf128 instruction
6499 // to create 256-bit vectors from two other 128-bit ones.
6500 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6502 MVT ResVT = Op.getSimpleValueType();
6504 assert((ResVT.is256BitVector() ||
6505 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6507 SDValue V1 = Op.getOperand(0);
6508 SDValue V2 = Op.getOperand(1);
6509 unsigned NumElems = ResVT.getVectorNumElements();
6510 if (ResVT.is256BitVector())
6511 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6513 if (Op.getNumOperands() == 4) {
6514 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6515 ResVT.getVectorNumElements()/2);
6516 SDValue V3 = Op.getOperand(2);
6517 SDValue V4 = Op.getOperand(3);
6518 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6519 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6521 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6524 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6525 const X86Subtarget *Subtarget,
6526 SelectionDAG & DAG) {
6528 MVT ResVT = Op.getSimpleValueType();
6529 unsigned NumOfOperands = Op.getNumOperands();
6531 assert(isPowerOf2_32(NumOfOperands) &&
6532 "Unexpected number of operands in CONCAT_VECTORS");
6534 if (NumOfOperands > 2) {
6535 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6536 ResVT.getVectorNumElements()/2);
6537 SmallVector<SDValue, 2> Ops;
6538 for (unsigned i = 0; i < NumOfOperands/2; i++)
6539 Ops.push_back(Op.getOperand(i));
6540 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6542 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6543 Ops.push_back(Op.getOperand(i));
6544 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6545 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6548 SDValue V1 = Op.getOperand(0);
6549 SDValue V2 = Op.getOperand(1);
6550 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6551 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6553 if (IsZeroV1 && IsZeroV2)
6554 return getZeroVector(ResVT, Subtarget, DAG, dl);
6556 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6557 SDValue Undef = DAG.getUNDEF(ResVT);
6558 unsigned NumElems = ResVT.getVectorNumElements();
6559 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6561 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6562 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6566 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6567 // Zero the upper bits of V1
6568 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6569 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6572 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6575 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6576 const X86Subtarget *Subtarget,
6577 SelectionDAG &DAG) {
6578 MVT VT = Op.getSimpleValueType();
6579 if (VT.getVectorElementType() == MVT::i1)
6580 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6582 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6583 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6584 Op.getNumOperands() == 4)));
6586 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6587 // from two other 128-bit ones.
6589 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6590 return LowerAVXCONCAT_VECTORS(Op, DAG);
6593 //===----------------------------------------------------------------------===//
6594 // Vector shuffle lowering
6596 // This is an experimental code path for lowering vector shuffles on x86. It is
6597 // designed to handle arbitrary vector shuffles and blends, gracefully
6598 // degrading performance as necessary. It works hard to recognize idiomatic
6599 // shuffles and lower them to optimal instruction patterns without leaving
6600 // a framework that allows reasonably efficient handling of all vector shuffle
6602 //===----------------------------------------------------------------------===//
6604 /// \brief Tiny helper function to identify a no-op mask.
6606 /// This is a somewhat boring predicate function. It checks whether the mask
6607 /// array input, which is assumed to be a single-input shuffle mask of the kind
6608 /// used by the X86 shuffle instructions (not a fully general
6609 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6610 /// in-place shuffle are 'no-op's.
6611 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6612 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6613 if (Mask[i] != -1 && Mask[i] != i)
6618 /// \brief Helper function to classify a mask as a single-input mask.
6620 /// This isn't a generic single-input test because in the vector shuffle
6621 /// lowering we canonicalize single inputs to be the first input operand. This
6622 /// means we can more quickly test for a single input by only checking whether
6623 /// an input from the second operand exists. We also assume that the size of
6624 /// mask corresponds to the size of the input vectors which isn't true in the
6625 /// fully general case.
6626 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6628 if (M >= (int)Mask.size())
6633 /// \brief Test whether there are elements crossing 128-bit lanes in this
6636 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6637 /// and we routinely test for these.
6638 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6639 int LaneSize = 128 / VT.getScalarSizeInBits();
6640 int Size = Mask.size();
6641 for (int i = 0; i < Size; ++i)
6642 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6647 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6649 /// This checks a shuffle mask to see if it is performing the same
6650 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6651 /// that it is also not lane-crossing. It may however involve a blend from the
6652 /// same lane of a second vector.
6654 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6655 /// non-trivial to compute in the face of undef lanes. The representation is
6656 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6657 /// entries from both V1 and V2 inputs to the wider mask.
6659 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6660 SmallVectorImpl<int> &RepeatedMask) {
6661 int LaneSize = 128 / VT.getScalarSizeInBits();
6662 RepeatedMask.resize(LaneSize, -1);
6663 int Size = Mask.size();
6664 for (int i = 0; i < Size; ++i) {
6667 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6668 // This entry crosses lanes, so there is no way to model this shuffle.
6671 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6672 if (RepeatedMask[i % LaneSize] == -1)
6673 // This is the first non-undef entry in this slot of a 128-bit lane.
6674 RepeatedMask[i % LaneSize] =
6675 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6676 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6677 // Found a mismatch with the repeated mask.
6683 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6686 /// This is a fast way to test a shuffle mask against a fixed pattern:
6688 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6690 /// It returns true if the mask is exactly as wide as the argument list, and
6691 /// each element of the mask is either -1 (signifying undef) or the value given
6692 /// in the argument.
6693 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6694 ArrayRef<int> ExpectedMask) {
6695 if (Mask.size() != ExpectedMask.size())
6698 int Size = Mask.size();
6700 // If the values are build vectors, we can look through them to find
6701 // equivalent inputs that make the shuffles equivalent.
6702 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6703 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6705 for (int i = 0; i < Size; ++i)
6706 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6707 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6708 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6709 if (!MaskBV || !ExpectedBV ||
6710 MaskBV->getOperand(Mask[i] % Size) !=
6711 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6718 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6720 /// This helper function produces an 8-bit shuffle immediate corresponding to
6721 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6722 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6725 /// NB: We rely heavily on "undef" masks preserving the input lane.
6726 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6727 SelectionDAG &DAG) {
6728 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6729 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6730 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6731 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6732 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6735 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6736 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6737 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6738 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6739 return DAG.getConstant(Imm, DL, MVT::i8);
6742 /// \brief Compute whether each element of a shuffle is zeroable.
6744 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6745 /// Either it is an undef element in the shuffle mask, the element of the input
6746 /// referenced is undef, or the element of the input referenced is known to be
6747 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6748 /// as many lanes with this technique as possible to simplify the remaining
6750 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6751 SDValue V1, SDValue V2) {
6752 SmallBitVector Zeroable(Mask.size(), false);
6754 while (V1.getOpcode() == ISD::BITCAST)
6755 V1 = V1->getOperand(0);
6756 while (V2.getOpcode() == ISD::BITCAST)
6757 V2 = V2->getOperand(0);
6759 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6760 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6762 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6764 // Handle the easy cases.
6765 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6770 // If this is an index into a build_vector node (which has the same number
6771 // of elements), dig out the input value and use it.
6772 SDValue V = M < Size ? V1 : V2;
6773 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6776 SDValue Input = V.getOperand(M % Size);
6777 // The UNDEF opcode check really should be dead code here, but not quite
6778 // worth asserting on (it isn't invalid, just unexpected).
6779 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6786 // X86 has dedicated unpack instructions that can handle specific blend
6787 // operations: UNPCKH and UNPCKL.
6788 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6789 SDValue V1, SDValue V2,
6790 SelectionDAG &DAG) {
6791 int NumElts = VT.getVectorNumElements();
6792 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6793 SmallVector<int, 8> Unpckl;
6794 SmallVector<int, 8> Unpckh;
6796 for (int i = 0; i < NumElts; ++i) {
6797 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6798 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6799 int HiPos = LoPos + NumEltsInLane / 2;
6800 Unpckl.push_back(LoPos);
6801 Unpckh.push_back(HiPos);
6804 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6805 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6806 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6807 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6809 // Commute and try again.
6810 ShuffleVectorSDNode::commuteMask(Unpckl);
6811 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6812 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6814 ShuffleVectorSDNode::commuteMask(Unpckh);
6815 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6816 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6821 /// \brief Try to emit a bitmask instruction for a shuffle.
6823 /// This handles cases where we can model a blend exactly as a bitmask due to
6824 /// one of the inputs being zeroable.
6825 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6826 SDValue V2, ArrayRef<int> Mask,
6827 SelectionDAG &DAG) {
6828 MVT EltVT = VT.getScalarType();
6829 int NumEltBits = EltVT.getSizeInBits();
6830 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6831 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6832 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6834 if (EltVT.isFloatingPoint()) {
6835 Zero = DAG.getBitcast(EltVT, Zero);
6836 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6838 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6839 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6841 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6844 if (Mask[i] % Size != i)
6845 return SDValue(); // Not a blend.
6847 V = Mask[i] < Size ? V1 : V2;
6848 else if (V != (Mask[i] < Size ? V1 : V2))
6849 return SDValue(); // Can only let one input through the mask.
6851 VMaskOps[i] = AllOnes;
6854 return SDValue(); // No non-zeroable elements!
6856 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6857 V = DAG.getNode(VT.isFloatingPoint()
6858 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6863 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6865 /// This is used as a fallback approach when first class blend instructions are
6866 /// unavailable. Currently it is only suitable for integer vectors, but could
6867 /// be generalized for floating point vectors if desirable.
6868 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6869 SDValue V2, ArrayRef<int> Mask,
6870 SelectionDAG &DAG) {
6871 assert(VT.isInteger() && "Only supports integer vector types!");
6872 MVT EltVT = VT.getScalarType();
6873 int NumEltBits = EltVT.getSizeInBits();
6874 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6875 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6877 SmallVector<SDValue, 16> MaskOps;
6878 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6879 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6880 return SDValue(); // Shuffled input!
6881 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6884 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6885 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6886 // We have to cast V2 around.
6887 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6888 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6889 DAG.getBitcast(MaskVT, V1Mask),
6890 DAG.getBitcast(MaskVT, V2)));
6891 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6894 /// \brief Try to emit a blend instruction for a shuffle.
6896 /// This doesn't do any checks for the availability of instructions for blending
6897 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6898 /// be matched in the backend with the type given. What it does check for is
6899 /// that the shuffle mask is in fact a blend.
6900 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6901 SDValue V2, ArrayRef<int> Mask,
6902 const X86Subtarget *Subtarget,
6903 SelectionDAG &DAG) {
6904 unsigned BlendMask = 0;
6905 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6906 if (Mask[i] >= Size) {
6907 if (Mask[i] != i + Size)
6908 return SDValue(); // Shuffled V2 input!
6909 BlendMask |= 1u << i;
6912 if (Mask[i] >= 0 && Mask[i] != i)
6913 return SDValue(); // Shuffled V1 input!
6915 switch (VT.SimpleTy) {
6920 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6921 DAG.getConstant(BlendMask, DL, MVT::i8));
6925 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6929 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6930 // that instruction.
6931 if (Subtarget->hasAVX2()) {
6932 // Scale the blend by the number of 32-bit dwords per element.
6933 int Scale = VT.getScalarSizeInBits() / 32;
6935 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6936 if (Mask[i] >= Size)
6937 for (int j = 0; j < Scale; ++j)
6938 BlendMask |= 1u << (i * Scale + j);
6940 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6941 V1 = DAG.getBitcast(BlendVT, V1);
6942 V2 = DAG.getBitcast(BlendVT, V2);
6943 return DAG.getBitcast(
6944 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6945 DAG.getConstant(BlendMask, DL, MVT::i8)));
6949 // For integer shuffles we need to expand the mask and cast the inputs to
6950 // v8i16s prior to blending.
6951 int Scale = 8 / VT.getVectorNumElements();
6953 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6954 if (Mask[i] >= Size)
6955 for (int j = 0; j < Scale; ++j)
6956 BlendMask |= 1u << (i * Scale + j);
6958 V1 = DAG.getBitcast(MVT::v8i16, V1);
6959 V2 = DAG.getBitcast(MVT::v8i16, V2);
6960 return DAG.getBitcast(VT,
6961 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6962 DAG.getConstant(BlendMask, DL, MVT::i8)));
6966 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6967 SmallVector<int, 8> RepeatedMask;
6968 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6969 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6970 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6972 for (int i = 0; i < 8; ++i)
6973 if (RepeatedMask[i] >= 16)
6974 BlendMask |= 1u << i;
6975 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6976 DAG.getConstant(BlendMask, DL, MVT::i8));
6982 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6983 "256-bit byte-blends require AVX2 support!");
6985 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6986 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6989 // Scale the blend by the number of bytes per element.
6990 int Scale = VT.getScalarSizeInBits() / 8;
6992 // This form of blend is always done on bytes. Compute the byte vector
6994 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6996 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6997 // mix of LLVM's code generator and the x86 backend. We tell the code
6998 // generator that boolean values in the elements of an x86 vector register
6999 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7000 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7001 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7002 // of the element (the remaining are ignored) and 0 in that high bit would
7003 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7004 // the LLVM model for boolean values in vector elements gets the relevant
7005 // bit set, it is set backwards and over constrained relative to x86's
7007 SmallVector<SDValue, 32> VSELECTMask;
7008 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7009 for (int j = 0; j < Scale; ++j)
7010 VSELECTMask.push_back(
7011 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7012 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7015 V1 = DAG.getBitcast(BlendVT, V1);
7016 V2 = DAG.getBitcast(BlendVT, V2);
7017 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7018 DAG.getNode(ISD::BUILD_VECTOR, DL,
7019 BlendVT, VSELECTMask),
7024 llvm_unreachable("Not a supported integer vector type!");
7028 /// \brief Try to lower as a blend of elements from two inputs followed by
7029 /// a single-input permutation.
7031 /// This matches the pattern where we can blend elements from two inputs and
7032 /// then reduce the shuffle to a single-input permutation.
7033 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7036 SelectionDAG &DAG) {
7037 // We build up the blend mask while checking whether a blend is a viable way
7038 // to reduce the shuffle.
7039 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7040 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7042 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7046 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7048 if (BlendMask[Mask[i] % Size] == -1)
7049 BlendMask[Mask[i] % Size] = Mask[i];
7050 else if (BlendMask[Mask[i] % Size] != Mask[i])
7051 return SDValue(); // Can't blend in the needed input!
7053 PermuteMask[i] = Mask[i] % Size;
7056 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7057 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7060 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7061 /// blends and permutes.
7063 /// This matches the extremely common pattern for handling combined
7064 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7065 /// operations. It will try to pick the best arrangement of shuffles and
7067 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7071 SelectionDAG &DAG) {
7072 // Shuffle the input elements into the desired positions in V1 and V2 and
7073 // blend them together.
7074 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7075 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7076 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7077 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7078 if (Mask[i] >= 0 && Mask[i] < Size) {
7079 V1Mask[i] = Mask[i];
7081 } else if (Mask[i] >= Size) {
7082 V2Mask[i] = Mask[i] - Size;
7083 BlendMask[i] = i + Size;
7086 // Try to lower with the simpler initial blend strategy unless one of the
7087 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7088 // shuffle may be able to fold with a load or other benefit. However, when
7089 // we'll have to do 2x as many shuffles in order to achieve this, blending
7090 // first is a better strategy.
7091 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7092 if (SDValue BlendPerm =
7093 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7096 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7097 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7098 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7101 /// \brief Try to lower a vector shuffle as a byte rotation.
7103 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7104 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7105 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7106 /// try to generically lower a vector shuffle through such an pattern. It
7107 /// does not check for the profitability of lowering either as PALIGNR or
7108 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7109 /// This matches shuffle vectors that look like:
7111 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7113 /// Essentially it concatenates V1 and V2, shifts right by some number of
7114 /// elements, and takes the low elements as the result. Note that while this is
7115 /// specified as a *right shift* because x86 is little-endian, it is a *left
7116 /// rotate* of the vector lanes.
7117 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7120 const X86Subtarget *Subtarget,
7121 SelectionDAG &DAG) {
7122 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7124 int NumElts = Mask.size();
7125 int NumLanes = VT.getSizeInBits() / 128;
7126 int NumLaneElts = NumElts / NumLanes;
7128 // We need to detect various ways of spelling a rotation:
7129 // [11, 12, 13, 14, 15, 0, 1, 2]
7130 // [-1, 12, 13, 14, -1, -1, 1, -1]
7131 // [-1, -1, -1, -1, -1, -1, 1, 2]
7132 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7133 // [-1, 4, 5, 6, -1, -1, 9, -1]
7134 // [-1, 4, 5, 6, -1, -1, -1, -1]
7137 for (int l = 0; l < NumElts; l += NumLaneElts) {
7138 for (int i = 0; i < NumLaneElts; ++i) {
7139 if (Mask[l + i] == -1)
7141 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7143 // Get the mod-Size index and lane correct it.
7144 int LaneIdx = (Mask[l + i] % NumElts) - l;
7145 // Make sure it was in this lane.
7146 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7149 // Determine where a rotated vector would have started.
7150 int StartIdx = i - LaneIdx;
7152 // The identity rotation isn't interesting, stop.
7155 // If we found the tail of a vector the rotation must be the missing
7156 // front. If we found the head of a vector, it must be how much of the
7158 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7161 Rotation = CandidateRotation;
7162 else if (Rotation != CandidateRotation)
7163 // The rotations don't match, so we can't match this mask.
7166 // Compute which value this mask is pointing at.
7167 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7169 // Compute which of the two target values this index should be assigned
7170 // to. This reflects whether the high elements are remaining or the low
7171 // elements are remaining.
7172 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7174 // Either set up this value if we've not encountered it before, or check
7175 // that it remains consistent.
7178 else if (TargetV != MaskV)
7179 // This may be a rotation, but it pulls from the inputs in some
7180 // unsupported interleaving.
7185 // Check that we successfully analyzed the mask, and normalize the results.
7186 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7187 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7193 // The actual rotate instruction rotates bytes, so we need to scale the
7194 // rotation based on how many bytes are in the vector lane.
7195 int Scale = 16 / NumLaneElts;
7197 // SSSE3 targets can use the palignr instruction.
7198 if (Subtarget->hasSSSE3()) {
7199 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7200 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7201 Lo = DAG.getBitcast(AlignVT, Lo);
7202 Hi = DAG.getBitcast(AlignVT, Hi);
7204 return DAG.getBitcast(
7205 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7206 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7209 assert(VT.getSizeInBits() == 128 &&
7210 "Rotate-based lowering only supports 128-bit lowering!");
7211 assert(Mask.size() <= 16 &&
7212 "Can shuffle at most 16 bytes in a 128-bit vector!");
7214 // Default SSE2 implementation
7215 int LoByteShift = 16 - Rotation * Scale;
7216 int HiByteShift = Rotation * Scale;
7218 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7219 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7220 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7222 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7223 DAG.getConstant(LoByteShift, DL, MVT::i8));
7224 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7225 DAG.getConstant(HiByteShift, DL, MVT::i8));
7226 return DAG.getBitcast(VT,
7227 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7230 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7232 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7233 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7234 /// matches elements from one of the input vectors shuffled to the left or
7235 /// right with zeroable elements 'shifted in'. It handles both the strictly
7236 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7239 /// PSHL : (little-endian) left bit shift.
7240 /// [ zz, 0, zz, 2 ]
7241 /// [ -1, 4, zz, -1 ]
7242 /// PSRL : (little-endian) right bit shift.
7244 /// [ -1, -1, 7, zz]
7245 /// PSLLDQ : (little-endian) left byte shift
7246 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7247 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7248 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7249 /// PSRLDQ : (little-endian) right byte shift
7250 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7251 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7252 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7253 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7254 SDValue V2, ArrayRef<int> Mask,
7255 SelectionDAG &DAG) {
7256 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7258 int Size = Mask.size();
7259 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7261 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7262 for (int i = 0; i < Size; i += Scale)
7263 for (int j = 0; j < Shift; ++j)
7264 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7270 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7271 for (int i = 0; i != Size; i += Scale) {
7272 unsigned Pos = Left ? i + Shift : i;
7273 unsigned Low = Left ? i : i + Shift;
7274 unsigned Len = Scale - Shift;
7275 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7276 Low + (V == V1 ? 0 : Size)))
7280 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7281 bool ByteShift = ShiftEltBits > 64;
7282 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7283 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7284 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7286 // Normalize the scale for byte shifts to still produce an i64 element
7288 Scale = ByteShift ? Scale / 2 : Scale;
7290 // We need to round trip through the appropriate type for the shift.
7291 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7292 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7293 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7294 "Illegal integer vector type");
7295 V = DAG.getBitcast(ShiftVT, V);
7297 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7298 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7299 return DAG.getBitcast(VT, V);
7302 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7303 // keep doubling the size of the integer elements up to that. We can
7304 // then shift the elements of the integer vector by whole multiples of
7305 // their width within the elements of the larger integer vector. Test each
7306 // multiple to see if we can find a match with the moved element indices
7307 // and that the shifted in elements are all zeroable.
7308 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7309 for (int Shift = 1; Shift != Scale; ++Shift)
7310 for (bool Left : {true, false})
7311 if (CheckZeros(Shift, Scale, Left))
7312 for (SDValue V : {V1, V2})
7313 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7320 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7321 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7322 SDValue V2, ArrayRef<int> Mask,
7323 SelectionDAG &DAG) {
7324 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7325 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7327 int Size = Mask.size();
7328 int HalfSize = Size / 2;
7329 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7331 // Upper half must be undefined.
7332 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7335 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7336 // Remainder of lower half result is zero and upper half is all undef.
7337 auto LowerAsEXTRQ = [&]() {
7338 // Determine the extraction length from the part of the
7339 // lower half that isn't zeroable.
7341 for (; Len > 0; --Len)
7342 if (!Zeroable[Len - 1])
7344 assert(Len > 0 && "Zeroable shuffle mask");
7346 // Attempt to match first Len sequential elements from the lower half.
7349 for (int i = 0; i != Len; ++i) {
7353 SDValue &V = (M < Size ? V1 : V2);
7356 // All mask elements must be in the lower half.
7360 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7371 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7372 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7373 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7374 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7375 DAG.getConstant(BitLen, DL, MVT::i8),
7376 DAG.getConstant(BitIdx, DL, MVT::i8));
7379 if (SDValue ExtrQ = LowerAsEXTRQ())
7382 // INSERTQ: Extract lowest Len elements from lower half of second source and
7383 // insert over first source, starting at Idx.
7384 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7385 auto LowerAsInsertQ = [&]() {
7386 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7389 // Attempt to match first source from mask before insertion point.
7390 if (isUndefInRange(Mask, 0, Idx)) {
7392 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7394 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7400 // Extend the extraction length looking to match both the insertion of
7401 // the second source and the remaining elements of the first.
7402 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7407 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7409 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7415 // Match the remaining elements of the lower half.
7416 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7418 } else if ((!Base || (Base == V1)) &&
7419 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7421 } else if ((!Base || (Base == V2)) &&
7422 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7429 // We may not have a base (first source) - this can safely be undefined.
7431 Base = DAG.getUNDEF(VT);
7433 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7434 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7435 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7436 DAG.getConstant(BitLen, DL, MVT::i8),
7437 DAG.getConstant(BitIdx, DL, MVT::i8));
7444 if (SDValue InsertQ = LowerAsInsertQ())
7450 /// \brief Lower a vector shuffle as a zero or any extension.
7452 /// Given a specific number of elements, element bit width, and extension
7453 /// stride, produce either a zero or any extension based on the available
7454 /// features of the subtarget. The extended elements are consecutive and
7455 /// begin and can start from an offseted element index in the input; to
7456 /// avoid excess shuffling the offset must either being in the bottom lane
7457 /// or at the start of a higher lane. All extended elements must be from
7459 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7460 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7461 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7462 assert(Scale > 1 && "Need a scale to extend.");
7463 int EltBits = VT.getScalarSizeInBits();
7464 int NumElements = VT.getVectorNumElements();
7465 int NumEltsPerLane = 128 / EltBits;
7466 int OffsetLane = Offset / NumEltsPerLane;
7467 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7468 "Only 8, 16, and 32 bit elements can be extended.");
7469 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7470 assert(0 <= Offset && "Extension offset must be positive.");
7471 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7472 "Extension offset must be in the first lane or start an upper lane.");
7474 // Check that an index is in same lane as the base offset.
7475 auto SafeOffset = [&](int Idx) {
7476 return OffsetLane == (Idx / NumEltsPerLane);
7479 // Shift along an input so that the offset base moves to the first element.
7480 auto ShuffleOffset = [&](SDValue V) {
7484 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7485 for (int i = 0; i * Scale < NumElements; ++i) {
7486 int SrcIdx = i + Offset;
7487 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7489 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7492 // Found a valid zext mask! Try various lowering strategies based on the
7493 // input type and available ISA extensions.
7494 if (Subtarget->hasSSE41()) {
7495 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7496 // PUNPCK will catch this in a later shuffle match.
7497 if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7499 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7500 NumElements / Scale);
7501 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7502 return DAG.getBitcast(VT, InputV);
7505 assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7507 // For any extends we can cheat for larger element sizes and use shuffle
7508 // instructions that can fold with a load and/or copy.
7509 if (AnyExt && EltBits == 32) {
7510 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7512 return DAG.getBitcast(
7513 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7514 DAG.getBitcast(MVT::v4i32, InputV),
7515 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7517 if (AnyExt && EltBits == 16 && Scale > 2) {
7518 int PSHUFDMask[4] = {Offset / 2, -1,
7519 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7520 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7521 DAG.getBitcast(MVT::v4i32, InputV),
7522 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7523 int PSHUFWMask[4] = {1, -1, -1, -1};
7524 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7525 return DAG.getBitcast(
7526 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7527 DAG.getBitcast(MVT::v8i16, InputV),
7528 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7531 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7533 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7534 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7535 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7537 int LoIdx = Offset * EltBits;
7538 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7539 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7540 DAG.getConstant(EltBits, DL, MVT::i8),
7541 DAG.getConstant(LoIdx, DL, MVT::i8)));
7543 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7544 !SafeOffset(Offset + 1))
7545 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7547 int HiIdx = (Offset + 1) * EltBits;
7548 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7549 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7550 DAG.getConstant(EltBits, DL, MVT::i8),
7551 DAG.getConstant(HiIdx, DL, MVT::i8)));
7552 return DAG.getNode(ISD::BITCAST, DL, VT,
7553 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7556 // If this would require more than 2 unpack instructions to expand, use
7557 // pshufb when available. We can only use more than 2 unpack instructions
7558 // when zero extending i8 elements which also makes it easier to use pshufb.
7559 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7560 assert(NumElements == 16 && "Unexpected byte vector width!");
7561 SDValue PSHUFBMask[16];
7562 for (int i = 0; i < 16; ++i) {
7563 int Idx = Offset + (i / Scale);
7564 PSHUFBMask[i] = DAG.getConstant(
7565 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7567 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7568 return DAG.getBitcast(VT,
7569 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7570 DAG.getNode(ISD::BUILD_VECTOR, DL,
7571 MVT::v16i8, PSHUFBMask)));
7574 // If we are extending from an offset, ensure we start on a boundary that
7575 // we can unpack from.
7576 int AlignToUnpack = Offset % (NumElements / Scale);
7577 if (AlignToUnpack) {
7578 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7579 for (int i = AlignToUnpack; i < NumElements; ++i)
7580 ShMask[i - AlignToUnpack] = i;
7581 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7582 Offset -= AlignToUnpack;
7585 // Otherwise emit a sequence of unpacks.
7587 unsigned UnpackLoHi = X86ISD::UNPCKL;
7588 if (Offset >= (NumElements / 2)) {
7589 UnpackLoHi = X86ISD::UNPCKH;
7590 Offset -= (NumElements / 2);
7593 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7594 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7595 : getZeroVector(InputVT, Subtarget, DAG, DL);
7596 InputV = DAG.getBitcast(InputVT, InputV);
7597 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7601 } while (Scale > 1);
7602 return DAG.getBitcast(VT, InputV);
7605 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7607 /// This routine will try to do everything in its power to cleverly lower
7608 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7609 /// check for the profitability of this lowering, it tries to aggressively
7610 /// match this pattern. It will use all of the micro-architectural details it
7611 /// can to emit an efficient lowering. It handles both blends with all-zero
7612 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7613 /// masking out later).
7615 /// The reason we have dedicated lowering for zext-style shuffles is that they
7616 /// are both incredibly common and often quite performance sensitive.
7617 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7618 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7619 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7620 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7622 int Bits = VT.getSizeInBits();
7623 int NumLanes = Bits / 128;
7624 int NumElements = VT.getVectorNumElements();
7625 int NumEltsPerLane = NumElements / NumLanes;
7626 assert(VT.getScalarSizeInBits() <= 32 &&
7627 "Exceeds 32-bit integer zero extension limit");
7628 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7630 // Define a helper function to check a particular ext-scale and lower to it if
7632 auto Lower = [&](int Scale) -> SDValue {
7637 for (int i = 0; i < NumElements; ++i) {
7640 continue; // Valid anywhere but doesn't tell us anything.
7641 if (i % Scale != 0) {
7642 // Each of the extended elements need to be zeroable.
7646 // We no longer are in the anyext case.
7651 // Each of the base elements needs to be consecutive indices into the
7652 // same input vector.
7653 SDValue V = M < NumElements ? V1 : V2;
7654 M = M % NumElements;
7657 Offset = M - (i / Scale);
7658 } else if (InputV != V)
7659 return SDValue(); // Flip-flopping inputs.
7661 // Offset must start in the lowest 128-bit lane or at the start of an
7663 // FIXME: Is it ever worth allowing a negative base offset?
7664 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7665 (Offset % NumEltsPerLane) == 0))
7668 // If we are offsetting, all referenced entries must come from the same
7670 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7673 if ((M % NumElements) != (Offset + (i / Scale)))
7674 return SDValue(); // Non-consecutive strided elements.
7678 // If we fail to find an input, we have a zero-shuffle which should always
7679 // have already been handled.
7680 // FIXME: Maybe handle this here in case during blending we end up with one?
7684 // If we are offsetting, don't extend if we only match a single input, we
7685 // can always do better by using a basic PSHUF or PUNPCK.
7686 if (Offset != 0 && Matches < 2)
7689 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7690 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7693 // The widest scale possible for extending is to a 64-bit integer.
7694 assert(Bits % 64 == 0 &&
7695 "The number of bits in a vector must be divisible by 64 on x86!");
7696 int NumExtElements = Bits / 64;
7698 // Each iteration, try extending the elements half as much, but into twice as
7700 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7701 assert(NumElements % NumExtElements == 0 &&
7702 "The input vector size must be divisible by the extended size.");
7703 if (SDValue V = Lower(NumElements / NumExtElements))
7707 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7711 // Returns one of the source operands if the shuffle can be reduced to a
7712 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7713 auto CanZExtLowHalf = [&]() {
7714 for (int i = NumElements / 2; i != NumElements; ++i)
7717 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7719 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7724 if (SDValue V = CanZExtLowHalf()) {
7725 V = DAG.getBitcast(MVT::v2i64, V);
7726 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7727 return DAG.getBitcast(VT, V);
7730 // No viable ext lowering found.
7734 /// \brief Try to get a scalar value for a specific element of a vector.
7736 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7737 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7738 SelectionDAG &DAG) {
7739 MVT VT = V.getSimpleValueType();
7740 MVT EltVT = VT.getVectorElementType();
7741 while (V.getOpcode() == ISD::BITCAST)
7742 V = V.getOperand(0);
7743 // If the bitcasts shift the element size, we can't extract an equivalent
7745 MVT NewVT = V.getSimpleValueType();
7746 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7749 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7750 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7751 // Ensure the scalar operand is the same size as the destination.
7752 // FIXME: Add support for scalar truncation where possible.
7753 SDValue S = V.getOperand(Idx);
7754 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7755 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7761 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7763 /// This is particularly important because the set of instructions varies
7764 /// significantly based on whether the operand is a load or not.
7765 static bool isShuffleFoldableLoad(SDValue V) {
7766 while (V.getOpcode() == ISD::BITCAST)
7767 V = V.getOperand(0);
7769 return ISD::isNON_EXTLoad(V.getNode());
7772 /// \brief Try to lower insertion of a single element into a zero vector.
7774 /// This is a common pattern that we have especially efficient patterns to lower
7775 /// across all subtarget feature sets.
7776 static SDValue lowerVectorShuffleAsElementInsertion(
7777 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7778 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7779 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7781 MVT EltVT = VT.getVectorElementType();
7783 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7784 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7786 bool IsV1Zeroable = true;
7787 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7788 if (i != V2Index && !Zeroable[i]) {
7789 IsV1Zeroable = false;
7793 // Check for a single input from a SCALAR_TO_VECTOR node.
7794 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7795 // all the smarts here sunk into that routine. However, the current
7796 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7797 // vector shuffle lowering is dead.
7798 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7800 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7801 // We need to zext the scalar if it is smaller than an i32.
7802 V2S = DAG.getBitcast(EltVT, V2S);
7803 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7804 // Using zext to expand a narrow element won't work for non-zero
7809 // Zero-extend directly to i32.
7811 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7813 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7814 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7815 EltVT == MVT::i16) {
7816 // Either not inserting from the low element of the input or the input
7817 // element size is too small to use VZEXT_MOVL to clear the high bits.
7821 if (!IsV1Zeroable) {
7822 // If V1 can't be treated as a zero vector we have fewer options to lower
7823 // this. We can't support integer vectors or non-zero targets cheaply, and
7824 // the V1 elements can't be permuted in any way.
7825 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7826 if (!VT.isFloatingPoint() || V2Index != 0)
7828 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7829 V1Mask[V2Index] = -1;
7830 if (!isNoopShuffleMask(V1Mask))
7832 // This is essentially a special case blend operation, but if we have
7833 // general purpose blend operations, they are always faster. Bail and let
7834 // the rest of the lowering handle these as blends.
7835 if (Subtarget->hasSSE41())
7838 // Otherwise, use MOVSD or MOVSS.
7839 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7840 "Only two types of floating point element types to handle!");
7841 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7845 // This lowering only works for the low element with floating point vectors.
7846 if (VT.isFloatingPoint() && V2Index != 0)
7849 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7851 V2 = DAG.getBitcast(VT, V2);
7854 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7855 // the desired position. Otherwise it is more efficient to do a vector
7856 // shift left. We know that we can do a vector shift left because all
7857 // the inputs are zero.
7858 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7859 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7860 V2Shuffle[V2Index] = 0;
7861 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7863 V2 = DAG.getBitcast(MVT::v2i64, V2);
7865 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7866 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7867 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7868 DAG.getDataLayout(), VT)));
7869 V2 = DAG.getBitcast(VT, V2);
7875 /// \brief Try to lower broadcast of a single element.
7877 /// For convenience, this code also bundles all of the subtarget feature set
7878 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7879 /// a convenient way to factor it out.
7880 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7882 const X86Subtarget *Subtarget,
7883 SelectionDAG &DAG) {
7884 if (!Subtarget->hasAVX())
7886 if (VT.isInteger() && !Subtarget->hasAVX2())
7889 // Check that the mask is a broadcast.
7890 int BroadcastIdx = -1;
7892 if (M >= 0 && BroadcastIdx == -1)
7894 else if (M >= 0 && M != BroadcastIdx)
7897 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7898 "a sorted mask where the broadcast "
7901 // Go up the chain of (vector) values to find a scalar load that we can
7902 // combine with the broadcast.
7904 switch (V.getOpcode()) {
7905 case ISD::CONCAT_VECTORS: {
7906 int OperandSize = Mask.size() / V.getNumOperands();
7907 V = V.getOperand(BroadcastIdx / OperandSize);
7908 BroadcastIdx %= OperandSize;
7912 case ISD::INSERT_SUBVECTOR: {
7913 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7914 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7918 int BeginIdx = (int)ConstantIdx->getZExtValue();
7920 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7921 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7922 BroadcastIdx -= BeginIdx;
7933 // Check if this is a broadcast of a scalar. We special case lowering
7934 // for scalars so that we can more effectively fold with loads.
7935 // First, look through bitcast: if the original value has a larger element
7936 // type than the shuffle, the broadcast element is in essence truncated.
7937 // Make that explicit to ease folding.
7938 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7939 EVT EltVT = VT.getVectorElementType();
7940 SDValue V0 = V.getOperand(0);
7941 EVT V0VT = V0.getValueType();
7943 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7944 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7945 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7946 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7951 // Also check the simpler case, where we can directly reuse the scalar.
7952 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7953 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7954 V = V.getOperand(BroadcastIdx);
7956 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7957 // Only AVX2 has register broadcasts.
7958 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7960 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7961 // We can't broadcast from a vector register without AVX2, and we can only
7962 // broadcast from the zero-element of a vector register.
7966 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7969 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7970 // INSERTPS when the V1 elements are already in the correct locations
7971 // because otherwise we can just always use two SHUFPS instructions which
7972 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7973 // perform INSERTPS if a single V1 element is out of place and all V2
7974 // elements are zeroable.
7975 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7977 SelectionDAG &DAG) {
7978 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7979 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7980 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7981 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7983 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7986 int V1DstIndex = -1;
7987 int V2DstIndex = -1;
7988 bool V1UsedInPlace = false;
7990 for (int i = 0; i < 4; ++i) {
7991 // Synthesize a zero mask from the zeroable elements (includes undefs).
7997 // Flag if we use any V1 inputs in place.
7999 V1UsedInPlace = true;
8003 // We can only insert a single non-zeroable element.
8004 if (V1DstIndex != -1 || V2DstIndex != -1)
8008 // V1 input out of place for insertion.
8011 // V2 input for insertion.
8016 // Don't bother if we have no (non-zeroable) element for insertion.
8017 if (V1DstIndex == -1 && V2DstIndex == -1)
8020 // Determine element insertion src/dst indices. The src index is from the
8021 // start of the inserted vector, not the start of the concatenated vector.
8022 unsigned V2SrcIndex = 0;
8023 if (V1DstIndex != -1) {
8024 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8025 // and don't use the original V2 at all.
8026 V2SrcIndex = Mask[V1DstIndex];
8027 V2DstIndex = V1DstIndex;
8030 V2SrcIndex = Mask[V2DstIndex] - 4;
8033 // If no V1 inputs are used in place, then the result is created only from
8034 // the zero mask and the V2 insertion - so remove V1 dependency.
8036 V1 = DAG.getUNDEF(MVT::v4f32);
8038 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8039 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8041 // Insert the V2 element into the desired position.
8043 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8044 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8047 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8048 /// UNPCK instruction.
8050 /// This specifically targets cases where we end up with alternating between
8051 /// the two inputs, and so can permute them into something that feeds a single
8052 /// UNPCK instruction. Note that this routine only targets integer vectors
8053 /// because for floating point vectors we have a generalized SHUFPS lowering
8054 /// strategy that handles everything that doesn't *exactly* match an unpack,
8055 /// making this clever lowering unnecessary.
8056 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8057 SDValue V1, SDValue V2,
8059 SelectionDAG &DAG) {
8060 assert(!VT.isFloatingPoint() &&
8061 "This routine only supports integer vectors.");
8062 assert(!isSingleInputShuffleMask(Mask) &&
8063 "This routine should only be used when blending two inputs.");
8064 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8066 int Size = Mask.size();
8068 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8069 return M >= 0 && M % Size < Size / 2;
8071 int NumHiInputs = std::count_if(
8072 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8074 bool UnpackLo = NumLoInputs >= NumHiInputs;
8076 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8077 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8078 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8080 for (int i = 0; i < Size; ++i) {
8084 // Each element of the unpack contains Scale elements from this mask.
8085 int UnpackIdx = i / Scale;
8087 // We only handle the case where V1 feeds the first slots of the unpack.
8088 // We rely on canonicalization to ensure this is the case.
8089 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8092 // Setup the mask for this input. The indexing is tricky as we have to
8093 // handle the unpack stride.
8094 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8095 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8099 // If we will have to shuffle both inputs to use the unpack, check whether
8100 // we can just unpack first and shuffle the result. If so, skip this unpack.
8101 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8102 !isNoopShuffleMask(V2Mask))
8105 // Shuffle the inputs into place.
8106 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8107 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8109 // Cast the inputs to the type we will use to unpack them.
8110 V1 = DAG.getBitcast(UnpackVT, V1);
8111 V2 = DAG.getBitcast(UnpackVT, V2);
8113 // Unpack the inputs and cast the result back to the desired type.
8114 return DAG.getBitcast(
8115 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8119 // We try each unpack from the largest to the smallest to try and find one
8120 // that fits this mask.
8121 int OrigNumElements = VT.getVectorNumElements();
8122 int OrigScalarSize = VT.getScalarSizeInBits();
8123 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8124 int Scale = ScalarSize / OrigScalarSize;
8125 int NumElements = OrigNumElements / Scale;
8126 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8127 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8131 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8133 if (NumLoInputs == 0 || NumHiInputs == 0) {
8134 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8135 "We have to have *some* inputs!");
8136 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8138 // FIXME: We could consider the total complexity of the permute of each
8139 // possible unpacking. Or at the least we should consider how many
8140 // half-crossings are created.
8141 // FIXME: We could consider commuting the unpacks.
8143 SmallVector<int, 32> PermMask;
8144 PermMask.assign(Size, -1);
8145 for (int i = 0; i < Size; ++i) {
8149 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8152 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8154 return DAG.getVectorShuffle(
8155 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8157 DAG.getUNDEF(VT), PermMask);
8163 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8165 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8166 /// support for floating point shuffles but not integer shuffles. These
8167 /// instructions will incur a domain crossing penalty on some chips though so
8168 /// it is better to avoid lowering through this for integer vectors where
8170 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8171 const X86Subtarget *Subtarget,
8172 SelectionDAG &DAG) {
8174 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8175 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8176 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8177 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8178 ArrayRef<int> Mask = SVOp->getMask();
8179 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8181 if (isSingleInputShuffleMask(Mask)) {
8182 // Use low duplicate instructions for masks that match their pattern.
8183 if (Subtarget->hasSSE3())
8184 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8185 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8187 // Straight shuffle of a single input vector. Simulate this by using the
8188 // single input as both of the "inputs" to this instruction..
8189 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8191 if (Subtarget->hasAVX()) {
8192 // If we have AVX, we can use VPERMILPS which will allow folding a load
8193 // into the shuffle.
8194 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8195 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8198 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8199 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8201 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8202 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8204 // If we have a single input, insert that into V1 if we can do so cheaply.
8205 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8206 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8207 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8209 // Try inverting the insertion since for v2 masks it is easy to do and we
8210 // can't reliably sort the mask one way or the other.
8211 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8212 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8213 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8214 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8218 // Try to use one of the special instruction patterns to handle two common
8219 // blend patterns if a zero-blend above didn't work.
8220 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8221 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8222 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8223 // We can either use a special instruction to load over the low double or
8224 // to move just the low double.
8226 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8228 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8230 if (Subtarget->hasSSE41())
8231 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8235 // Use dedicated unpack instructions for masks that match their pattern.
8237 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8240 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8241 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8242 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8245 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8247 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8248 /// the integer unit to minimize domain crossing penalties. However, for blends
8249 /// it falls back to the floating point shuffle operation with appropriate bit
8251 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8252 const X86Subtarget *Subtarget,
8253 SelectionDAG &DAG) {
8255 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8256 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8257 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8258 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8259 ArrayRef<int> Mask = SVOp->getMask();
8260 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8262 if (isSingleInputShuffleMask(Mask)) {
8263 // Check for being able to broadcast a single element.
8264 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8265 Mask, Subtarget, DAG))
8268 // Straight shuffle of a single input vector. For everything from SSE2
8269 // onward this has a single fast instruction with no scary immediates.
8270 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8271 V1 = DAG.getBitcast(MVT::v4i32, V1);
8272 int WidenedMask[4] = {
8273 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8274 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8275 return DAG.getBitcast(
8277 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8278 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8280 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8281 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8282 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8283 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8285 // If we have a blend of two PACKUS operations an the blend aligns with the
8286 // low and half halves, we can just merge the PACKUS operations. This is
8287 // particularly important as it lets us merge shuffles that this routine itself
8289 auto GetPackNode = [](SDValue V) {
8290 while (V.getOpcode() == ISD::BITCAST)
8291 V = V.getOperand(0);
8293 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8295 if (SDValue V1Pack = GetPackNode(V1))
8296 if (SDValue V2Pack = GetPackNode(V2))
8297 return DAG.getBitcast(MVT::v2i64,
8298 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8299 Mask[0] == 0 ? V1Pack.getOperand(0)
8300 : V1Pack.getOperand(1),
8301 Mask[1] == 2 ? V2Pack.getOperand(0)
8302 : V2Pack.getOperand(1)));
8304 // Try to use shift instructions.
8306 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8309 // When loading a scalar and then shuffling it into a vector we can often do
8310 // the insertion cheaply.
8311 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8312 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8314 // Try inverting the insertion since for v2 masks it is easy to do and we
8315 // can't reliably sort the mask one way or the other.
8316 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8317 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8318 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8321 // We have different paths for blend lowering, but they all must use the
8322 // *exact* same predicate.
8323 bool IsBlendSupported = Subtarget->hasSSE41();
8324 if (IsBlendSupported)
8325 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8329 // Use dedicated unpack instructions for masks that match their pattern.
8331 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8334 // Try to use byte rotation instructions.
8335 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8336 if (Subtarget->hasSSSE3())
8337 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8338 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8341 // If we have direct support for blends, we should lower by decomposing into
8342 // a permute. That will be faster than the domain cross.
8343 if (IsBlendSupported)
8344 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8347 // We implement this with SHUFPD which is pretty lame because it will likely
8348 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8349 // However, all the alternatives are still more cycles and newer chips don't
8350 // have this problem. It would be really nice if x86 had better shuffles here.
8351 V1 = DAG.getBitcast(MVT::v2f64, V1);
8352 V2 = DAG.getBitcast(MVT::v2f64, V2);
8353 return DAG.getBitcast(MVT::v2i64,
8354 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8357 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8359 /// This is used to disable more specialized lowerings when the shufps lowering
8360 /// will happen to be efficient.
8361 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8362 // This routine only handles 128-bit shufps.
8363 assert(Mask.size() == 4 && "Unsupported mask size!");
8365 // To lower with a single SHUFPS we need to have the low half and high half
8366 // each requiring a single input.
8367 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8369 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8375 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8377 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8378 /// It makes no assumptions about whether this is the *best* lowering, it simply
8380 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8381 ArrayRef<int> Mask, SDValue V1,
8382 SDValue V2, SelectionDAG &DAG) {
8383 SDValue LowV = V1, HighV = V2;
8384 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8387 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8389 if (NumV2Elements == 1) {
8391 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8394 // Compute the index adjacent to V2Index and in the same half by toggling
8396 int V2AdjIndex = V2Index ^ 1;
8398 if (Mask[V2AdjIndex] == -1) {
8399 // Handles all the cases where we have a single V2 element and an undef.
8400 // This will only ever happen in the high lanes because we commute the
8401 // vector otherwise.
8403 std::swap(LowV, HighV);
8404 NewMask[V2Index] -= 4;
8406 // Handle the case where the V2 element ends up adjacent to a V1 element.
8407 // To make this work, blend them together as the first step.
8408 int V1Index = V2AdjIndex;
8409 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8410 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8411 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8413 // Now proceed to reconstruct the final blend as we have the necessary
8414 // high or low half formed.
8421 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8422 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8424 } else if (NumV2Elements == 2) {
8425 if (Mask[0] < 4 && Mask[1] < 4) {
8426 // Handle the easy case where we have V1 in the low lanes and V2 in the
8430 } else if (Mask[2] < 4 && Mask[3] < 4) {
8431 // We also handle the reversed case because this utility may get called
8432 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8433 // arrange things in the right direction.
8439 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8440 // trying to place elements directly, just blend them and set up the final
8441 // shuffle to place them.
8443 // The first two blend mask elements are for V1, the second two are for
8445 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8446 Mask[2] < 4 ? Mask[2] : Mask[3],
8447 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8448 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8449 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8450 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8452 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8455 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8456 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8457 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8458 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8461 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8462 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8465 /// \brief Lower 4-lane 32-bit floating point shuffles.
8467 /// Uses instructions exclusively from the floating point unit to minimize
8468 /// domain crossing penalties, as these are sufficient to implement all v4f32
8470 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8471 const X86Subtarget *Subtarget,
8472 SelectionDAG &DAG) {
8474 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8475 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8476 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8477 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8478 ArrayRef<int> Mask = SVOp->getMask();
8479 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8482 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8484 if (NumV2Elements == 0) {
8485 // Check for being able to broadcast a single element.
8486 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8487 Mask, Subtarget, DAG))
8490 // Use even/odd duplicate instructions for masks that match their pattern.
8491 if (Subtarget->hasSSE3()) {
8492 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8493 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8494 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8495 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8498 if (Subtarget->hasAVX()) {
8499 // If we have AVX, we can use VPERMILPS which will allow folding a load
8500 // into the shuffle.
8501 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8502 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8505 // Otherwise, use a straight shuffle of a single input vector. We pass the
8506 // input vector to both operands to simulate this with a SHUFPS.
8507 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8508 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8511 // There are special ways we can lower some single-element blends. However, we
8512 // have custom ways we can lower more complex single-element blends below that
8513 // we defer to if both this and BLENDPS fail to match, so restrict this to
8514 // when the V2 input is targeting element 0 of the mask -- that is the fast
8516 if (NumV2Elements == 1 && Mask[0] >= 4)
8517 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8518 Mask, Subtarget, DAG))
8521 if (Subtarget->hasSSE41()) {
8522 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8526 // Use INSERTPS if we can complete the shuffle efficiently.
8527 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8530 if (!isSingleSHUFPSMask(Mask))
8531 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8532 DL, MVT::v4f32, V1, V2, Mask, DAG))
8536 // Use dedicated unpack instructions for masks that match their pattern.
8538 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8541 // Otherwise fall back to a SHUFPS lowering strategy.
8542 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8545 /// \brief Lower 4-lane i32 vector shuffles.
8547 /// We try to handle these with integer-domain shuffles where we can, but for
8548 /// blends we use the floating point domain blend instructions.
8549 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8550 const X86Subtarget *Subtarget,
8551 SelectionDAG &DAG) {
8553 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8554 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8555 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8556 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8557 ArrayRef<int> Mask = SVOp->getMask();
8558 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8560 // Whenever we can lower this as a zext, that instruction is strictly faster
8561 // than any alternative. It also allows us to fold memory operands into the
8562 // shuffle in many cases.
8563 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8564 Mask, Subtarget, DAG))
8568 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8570 if (NumV2Elements == 0) {
8571 // Check for being able to broadcast a single element.
8572 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8573 Mask, Subtarget, DAG))
8576 // Straight shuffle of a single input vector. For everything from SSE2
8577 // onward this has a single fast instruction with no scary immediates.
8578 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8579 // but we aren't actually going to use the UNPCK instruction because doing
8580 // so prevents folding a load into this instruction or making a copy.
8581 const int UnpackLoMask[] = {0, 0, 1, 1};
8582 const int UnpackHiMask[] = {2, 2, 3, 3};
8583 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8584 Mask = UnpackLoMask;
8585 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8586 Mask = UnpackHiMask;
8588 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8589 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8592 // Try to use shift instructions.
8594 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8597 // There are special ways we can lower some single-element blends.
8598 if (NumV2Elements == 1)
8599 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8600 Mask, Subtarget, DAG))
8603 // We have different paths for blend lowering, but they all must use the
8604 // *exact* same predicate.
8605 bool IsBlendSupported = Subtarget->hasSSE41();
8606 if (IsBlendSupported)
8607 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8611 if (SDValue Masked =
8612 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8615 // Use dedicated unpack instructions for masks that match their pattern.
8617 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8620 // Try to use byte rotation instructions.
8621 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8622 if (Subtarget->hasSSSE3())
8623 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8624 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8627 // If we have direct support for blends, we should lower by decomposing into
8628 // a permute. That will be faster than the domain cross.
8629 if (IsBlendSupported)
8630 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8633 // Try to lower by permuting the inputs into an unpack instruction.
8634 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8638 // We implement this with SHUFPS because it can blend from two vectors.
8639 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8640 // up the inputs, bypassing domain shift penalties that we would encur if we
8641 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8643 return DAG.getBitcast(
8645 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8646 DAG.getBitcast(MVT::v4f32, V2), Mask));
8649 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8650 /// shuffle lowering, and the most complex part.
8652 /// The lowering strategy is to try to form pairs of input lanes which are
8653 /// targeted at the same half of the final vector, and then use a dword shuffle
8654 /// to place them onto the right half, and finally unpack the paired lanes into
8655 /// their final position.
8657 /// The exact breakdown of how to form these dword pairs and align them on the
8658 /// correct sides is really tricky. See the comments within the function for
8659 /// more of the details.
8661 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8662 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8663 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8664 /// vector, form the analogous 128-bit 8-element Mask.
8665 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8666 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8667 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8668 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8669 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8671 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8672 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8673 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8675 SmallVector<int, 4> LoInputs;
8676 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8677 [](int M) { return M >= 0; });
8678 std::sort(LoInputs.begin(), LoInputs.end());
8679 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8680 SmallVector<int, 4> HiInputs;
8681 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8682 [](int M) { return M >= 0; });
8683 std::sort(HiInputs.begin(), HiInputs.end());
8684 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8686 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8687 int NumHToL = LoInputs.size() - NumLToL;
8689 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8690 int NumHToH = HiInputs.size() - NumLToH;
8691 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8692 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8693 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8694 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8696 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8697 // such inputs we can swap two of the dwords across the half mark and end up
8698 // with <=2 inputs to each half in each half. Once there, we can fall through
8699 // to the generic code below. For example:
8701 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8702 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8704 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8705 // and an existing 2-into-2 on the other half. In this case we may have to
8706 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8707 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8708 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8709 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8710 // half than the one we target for fixing) will be fixed when we re-enter this
8711 // path. We will also combine away any sequence of PSHUFD instructions that
8712 // result into a single instruction. Here is an example of the tricky case:
8714 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8715 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8717 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8719 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8720 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8722 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8723 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8725 // The result is fine to be handled by the generic logic.
8726 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8727 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8728 int AOffset, int BOffset) {
8729 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8730 "Must call this with A having 3 or 1 inputs from the A half.");
8731 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8732 "Must call this with B having 1 or 3 inputs from the B half.");
8733 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8734 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8736 bool ThreeAInputs = AToAInputs.size() == 3;
8738 // Compute the index of dword with only one word among the three inputs in
8739 // a half by taking the sum of the half with three inputs and subtracting
8740 // the sum of the actual three inputs. The difference is the remaining
8743 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8744 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8745 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8746 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8747 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8748 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8749 int TripleNonInputIdx =
8750 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8751 TripleDWord = TripleNonInputIdx / 2;
8753 // We use xor with one to compute the adjacent DWord to whichever one the
8755 OneInputDWord = (OneInput / 2) ^ 1;
8757 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8758 // and BToA inputs. If there is also such a problem with the BToB and AToB
8759 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8760 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8761 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8762 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8763 // Compute how many inputs will be flipped by swapping these DWords. We
8765 // to balance this to ensure we don't form a 3-1 shuffle in the other
8767 int NumFlippedAToBInputs =
8768 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8769 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8770 int NumFlippedBToBInputs =
8771 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8772 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8773 if ((NumFlippedAToBInputs == 1 &&
8774 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8775 (NumFlippedBToBInputs == 1 &&
8776 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8777 // We choose whether to fix the A half or B half based on whether that
8778 // half has zero flipped inputs. At zero, we may not be able to fix it
8779 // with that half. We also bias towards fixing the B half because that
8780 // will more commonly be the high half, and we have to bias one way.
8781 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8782 ArrayRef<int> Inputs) {
8783 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8784 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8785 PinnedIdx ^ 1) != Inputs.end();
8786 // Determine whether the free index is in the flipped dword or the
8787 // unflipped dword based on where the pinned index is. We use this bit
8788 // in an xor to conditionally select the adjacent dword.
8789 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8790 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8791 FixFreeIdx) != Inputs.end();
8792 if (IsFixIdxInput == IsFixFreeIdxInput)
8794 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8795 FixFreeIdx) != Inputs.end();
8796 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8797 "We need to be changing the number of flipped inputs!");
8798 int PSHUFHalfMask[] = {0, 1, 2, 3};
8799 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8800 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8802 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8805 if (M != -1 && M == FixIdx)
8807 else if (M != -1 && M == FixFreeIdx)
8810 if (NumFlippedBToBInputs != 0) {
8812 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8813 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8815 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8816 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8817 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8822 int PSHUFDMask[] = {0, 1, 2, 3};
8823 PSHUFDMask[ADWord] = BDWord;
8824 PSHUFDMask[BDWord] = ADWord;
8827 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8828 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8830 // Adjust the mask to match the new locations of A and B.
8832 if (M != -1 && M/2 == ADWord)
8833 M = 2 * BDWord + M % 2;
8834 else if (M != -1 && M/2 == BDWord)
8835 M = 2 * ADWord + M % 2;
8837 // Recurse back into this routine to re-compute state now that this isn't
8838 // a 3 and 1 problem.
8839 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8842 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8843 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8844 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8845 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8847 // At this point there are at most two inputs to the low and high halves from
8848 // each half. That means the inputs can always be grouped into dwords and
8849 // those dwords can then be moved to the correct half with a dword shuffle.
8850 // We use at most one low and one high word shuffle to collect these paired
8851 // inputs into dwords, and finally a dword shuffle to place them.
8852 int PSHUFLMask[4] = {-1, -1, -1, -1};
8853 int PSHUFHMask[4] = {-1, -1, -1, -1};
8854 int PSHUFDMask[4] = {-1, -1, -1, -1};
8856 // First fix the masks for all the inputs that are staying in their
8857 // original halves. This will then dictate the targets of the cross-half
8859 auto fixInPlaceInputs =
8860 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8861 MutableArrayRef<int> SourceHalfMask,
8862 MutableArrayRef<int> HalfMask, int HalfOffset) {
8863 if (InPlaceInputs.empty())
8865 if (InPlaceInputs.size() == 1) {
8866 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8867 InPlaceInputs[0] - HalfOffset;
8868 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8871 if (IncomingInputs.empty()) {
8872 // Just fix all of the in place inputs.
8873 for (int Input : InPlaceInputs) {
8874 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8875 PSHUFDMask[Input / 2] = Input / 2;
8880 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8881 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8882 InPlaceInputs[0] - HalfOffset;
8883 // Put the second input next to the first so that they are packed into
8884 // a dword. We find the adjacent index by toggling the low bit.
8885 int AdjIndex = InPlaceInputs[0] ^ 1;
8886 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8887 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8888 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8890 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8891 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8893 // Now gather the cross-half inputs and place them into a free dword of
8894 // their target half.
8895 // FIXME: This operation could almost certainly be simplified dramatically to
8896 // look more like the 3-1 fixing operation.
8897 auto moveInputsToRightHalf = [&PSHUFDMask](
8898 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8899 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8900 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8902 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8903 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8905 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8907 int LowWord = Word & ~1;
8908 int HighWord = Word | 1;
8909 return isWordClobbered(SourceHalfMask, LowWord) ||
8910 isWordClobbered(SourceHalfMask, HighWord);
8913 if (IncomingInputs.empty())
8916 if (ExistingInputs.empty()) {
8917 // Map any dwords with inputs from them into the right half.
8918 for (int Input : IncomingInputs) {
8919 // If the source half mask maps over the inputs, turn those into
8920 // swaps and use the swapped lane.
8921 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8922 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8923 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8924 Input - SourceOffset;
8925 // We have to swap the uses in our half mask in one sweep.
8926 for (int &M : HalfMask)
8927 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8929 else if (M == Input)
8930 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8932 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8933 Input - SourceOffset &&
8934 "Previous placement doesn't match!");
8936 // Note that this correctly re-maps both when we do a swap and when
8937 // we observe the other side of the swap above. We rely on that to
8938 // avoid swapping the members of the input list directly.
8939 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8942 // Map the input's dword into the correct half.
8943 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8944 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8946 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8948 "Previous placement doesn't match!");
8951 // And just directly shift any other-half mask elements to be same-half
8952 // as we will have mirrored the dword containing the element into the
8953 // same position within that half.
8954 for (int &M : HalfMask)
8955 if (M >= SourceOffset && M < SourceOffset + 4) {
8956 M = M - SourceOffset + DestOffset;
8957 assert(M >= 0 && "This should never wrap below zero!");
8962 // Ensure we have the input in a viable dword of its current half. This
8963 // is particularly tricky because the original position may be clobbered
8964 // by inputs being moved and *staying* in that half.
8965 if (IncomingInputs.size() == 1) {
8966 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8967 int InputFixed = std::find(std::begin(SourceHalfMask),
8968 std::end(SourceHalfMask), -1) -
8969 std::begin(SourceHalfMask) + SourceOffset;
8970 SourceHalfMask[InputFixed - SourceOffset] =
8971 IncomingInputs[0] - SourceOffset;
8972 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8974 IncomingInputs[0] = InputFixed;
8976 } else if (IncomingInputs.size() == 2) {
8977 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8978 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8979 // We have two non-adjacent or clobbered inputs we need to extract from
8980 // the source half. To do this, we need to map them into some adjacent
8981 // dword slot in the source mask.
8982 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8983 IncomingInputs[1] - SourceOffset};
8985 // If there is a free slot in the source half mask adjacent to one of
8986 // the inputs, place the other input in it. We use (Index XOR 1) to
8987 // compute an adjacent index.
8988 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8989 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8990 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8991 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8992 InputsFixed[1] = InputsFixed[0] ^ 1;
8993 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8994 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8995 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8996 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8997 InputsFixed[0] = InputsFixed[1] ^ 1;
8998 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8999 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9000 // The two inputs are in the same DWord but it is clobbered and the
9001 // adjacent DWord isn't used at all. Move both inputs to the free
9003 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9004 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9005 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9006 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9008 // The only way we hit this point is if there is no clobbering
9009 // (because there are no off-half inputs to this half) and there is no
9010 // free slot adjacent to one of the inputs. In this case, we have to
9011 // swap an input with a non-input.
9012 for (int i = 0; i < 4; ++i)
9013 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9014 "We can't handle any clobbers here!");
9015 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9016 "Cannot have adjacent inputs here!");
9018 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9019 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9021 // We also have to update the final source mask in this case because
9022 // it may need to undo the above swap.
9023 for (int &M : FinalSourceHalfMask)
9024 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9025 M = InputsFixed[1] + SourceOffset;
9026 else if (M == InputsFixed[1] + SourceOffset)
9027 M = (InputsFixed[0] ^ 1) + SourceOffset;
9029 InputsFixed[1] = InputsFixed[0] ^ 1;
9032 // Point everything at the fixed inputs.
9033 for (int &M : HalfMask)
9034 if (M == IncomingInputs[0])
9035 M = InputsFixed[0] + SourceOffset;
9036 else if (M == IncomingInputs[1])
9037 M = InputsFixed[1] + SourceOffset;
9039 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9040 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9043 llvm_unreachable("Unhandled input size!");
9046 // Now hoist the DWord down to the right half.
9047 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9048 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9049 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9050 for (int &M : HalfMask)
9051 for (int Input : IncomingInputs)
9053 M = FreeDWord * 2 + Input % 2;
9055 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9056 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9057 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9058 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9060 // Now enact all the shuffles we've computed to move the inputs into their
9062 if (!isNoopShuffleMask(PSHUFLMask))
9063 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9064 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9065 if (!isNoopShuffleMask(PSHUFHMask))
9066 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9067 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9068 if (!isNoopShuffleMask(PSHUFDMask))
9071 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9072 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9074 // At this point, each half should contain all its inputs, and we can then
9075 // just shuffle them into their final position.
9076 assert(std::count_if(LoMask.begin(), LoMask.end(),
9077 [](int M) { return M >= 4; }) == 0 &&
9078 "Failed to lift all the high half inputs to the low mask!");
9079 assert(std::count_if(HiMask.begin(), HiMask.end(),
9080 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9081 "Failed to lift all the low half inputs to the high mask!");
9083 // Do a half shuffle for the low mask.
9084 if (!isNoopShuffleMask(LoMask))
9085 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9086 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9088 // Do a half shuffle with the high mask after shifting its values down.
9089 for (int &M : HiMask)
9092 if (!isNoopShuffleMask(HiMask))
9093 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9094 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9099 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9100 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9101 SDValue V2, ArrayRef<int> Mask,
9102 SelectionDAG &DAG, bool &V1InUse,
9104 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9110 int Size = Mask.size();
9111 int Scale = 16 / Size;
9112 for (int i = 0; i < 16; ++i) {
9113 if (Mask[i / Scale] == -1) {
9114 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9116 const int ZeroMask = 0x80;
9117 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9119 int V2Idx = Mask[i / Scale] < Size
9121 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9122 if (Zeroable[i / Scale])
9123 V1Idx = V2Idx = ZeroMask;
9124 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9125 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9126 V1InUse |= (ZeroMask != V1Idx);
9127 V2InUse |= (ZeroMask != V2Idx);
9132 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9133 DAG.getBitcast(MVT::v16i8, V1),
9134 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9136 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9137 DAG.getBitcast(MVT::v16i8, V2),
9138 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9140 // If we need shuffled inputs from both, blend the two.
9142 if (V1InUse && V2InUse)
9143 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9145 V = V1InUse ? V1 : V2;
9147 // Cast the result back to the correct type.
9148 return DAG.getBitcast(VT, V);
9151 /// \brief Generic lowering of 8-lane i16 shuffles.
9153 /// This handles both single-input shuffles and combined shuffle/blends with
9154 /// two inputs. The single input shuffles are immediately delegated to
9155 /// a dedicated lowering routine.
9157 /// The blends are lowered in one of three fundamental ways. If there are few
9158 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9159 /// of the input is significantly cheaper when lowered as an interleaving of
9160 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9161 /// halves of the inputs separately (making them have relatively few inputs)
9162 /// and then concatenate them.
9163 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9164 const X86Subtarget *Subtarget,
9165 SelectionDAG &DAG) {
9167 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9168 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9169 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9170 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9171 ArrayRef<int> OrigMask = SVOp->getMask();
9172 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9173 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9174 MutableArrayRef<int> Mask(MaskStorage);
9176 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9178 // Whenever we can lower this as a zext, that instruction is strictly faster
9179 // than any alternative.
9180 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9181 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9184 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9186 auto isV2 = [](int M) { return M >= 8; };
9188 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9190 if (NumV2Inputs == 0) {
9191 // Check for being able to broadcast a single element.
9192 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9193 Mask, Subtarget, DAG))
9196 // Try to use shift instructions.
9198 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9201 // Use dedicated unpack instructions for masks that match their pattern.
9203 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9206 // Try to use byte rotation instructions.
9207 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9208 Mask, Subtarget, DAG))
9211 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9215 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9216 "All single-input shuffles should be canonicalized to be V1-input "
9219 // Try to use shift instructions.
9221 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9224 // See if we can use SSE4A Extraction / Insertion.
9225 if (Subtarget->hasSSE4A())
9226 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9229 // There are special ways we can lower some single-element blends.
9230 if (NumV2Inputs == 1)
9231 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9232 Mask, Subtarget, DAG))
9235 // We have different paths for blend lowering, but they all must use the
9236 // *exact* same predicate.
9237 bool IsBlendSupported = Subtarget->hasSSE41();
9238 if (IsBlendSupported)
9239 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9243 if (SDValue Masked =
9244 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9247 // Use dedicated unpack instructions for masks that match their pattern.
9249 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9252 // Try to use byte rotation instructions.
9253 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9254 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9257 if (SDValue BitBlend =
9258 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9261 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9265 // If we can't directly blend but can use PSHUFB, that will be better as it
9266 // can both shuffle and set up the inefficient blend.
9267 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9268 bool V1InUse, V2InUse;
9269 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9273 // We can always bit-blend if we have to so the fallback strategy is to
9274 // decompose into single-input permutes and blends.
9275 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9279 /// \brief Check whether a compaction lowering can be done by dropping even
9280 /// elements and compute how many times even elements must be dropped.
9282 /// This handles shuffles which take every Nth element where N is a power of
9283 /// two. Example shuffle masks:
9285 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9286 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9287 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9288 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9289 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9290 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9292 /// Any of these lanes can of course be undef.
9294 /// This routine only supports N <= 3.
9295 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9298 /// \returns N above, or the number of times even elements must be dropped if
9299 /// there is such a number. Otherwise returns zero.
9300 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9301 // Figure out whether we're looping over two inputs or just one.
9302 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9304 // The modulus for the shuffle vector entries is based on whether this is
9305 // a single input or not.
9306 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9307 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9308 "We should only be called with masks with a power-of-2 size!");
9310 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9312 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9313 // and 2^3 simultaneously. This is because we may have ambiguity with
9314 // partially undef inputs.
9315 bool ViableForN[3] = {true, true, true};
9317 for (int i = 0, e = Mask.size(); i < e; ++i) {
9318 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9323 bool IsAnyViable = false;
9324 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9325 if (ViableForN[j]) {
9328 // The shuffle mask must be equal to (i * 2^N) % M.
9329 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9332 ViableForN[j] = false;
9334 // Early exit if we exhaust the possible powers of two.
9339 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9343 // Return 0 as there is no viable power of two.
9347 /// \brief Generic lowering of v16i8 shuffles.
9349 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9350 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9351 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9352 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9354 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9355 const X86Subtarget *Subtarget,
9356 SelectionDAG &DAG) {
9358 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9359 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9360 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9361 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9362 ArrayRef<int> Mask = SVOp->getMask();
9363 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9365 // Try to use shift instructions.
9367 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9370 // Try to use byte rotation instructions.
9371 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9372 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9375 // Try to use a zext lowering.
9376 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9377 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9380 // See if we can use SSE4A Extraction / Insertion.
9381 if (Subtarget->hasSSE4A())
9382 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9386 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9388 // For single-input shuffles, there are some nicer lowering tricks we can use.
9389 if (NumV2Elements == 0) {
9390 // Check for being able to broadcast a single element.
9391 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9392 Mask, Subtarget, DAG))
9395 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9396 // Notably, this handles splat and partial-splat shuffles more efficiently.
9397 // However, it only makes sense if the pre-duplication shuffle simplifies
9398 // things significantly. Currently, this means we need to be able to
9399 // express the pre-duplication shuffle as an i16 shuffle.
9401 // FIXME: We should check for other patterns which can be widened into an
9402 // i16 shuffle as well.
9403 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9404 for (int i = 0; i < 16; i += 2)
9405 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9410 auto tryToWidenViaDuplication = [&]() -> SDValue {
9411 if (!canWidenViaDuplication(Mask))
9413 SmallVector<int, 4> LoInputs;
9414 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9415 [](int M) { return M >= 0 && M < 8; });
9416 std::sort(LoInputs.begin(), LoInputs.end());
9417 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9419 SmallVector<int, 4> HiInputs;
9420 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9421 [](int M) { return M >= 8; });
9422 std::sort(HiInputs.begin(), HiInputs.end());
9423 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9426 bool TargetLo = LoInputs.size() >= HiInputs.size();
9427 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9428 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9430 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9431 SmallDenseMap<int, int, 8> LaneMap;
9432 for (int I : InPlaceInputs) {
9433 PreDupI16Shuffle[I/2] = I/2;
9436 int j = TargetLo ? 0 : 4, je = j + 4;
9437 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9438 // Check if j is already a shuffle of this input. This happens when
9439 // there are two adjacent bytes after we move the low one.
9440 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9441 // If we haven't yet mapped the input, search for a slot into which
9443 while (j < je && PreDupI16Shuffle[j] != -1)
9447 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9450 // Map this input with the i16 shuffle.
9451 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9454 // Update the lane map based on the mapping we ended up with.
9455 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9457 V1 = DAG.getBitcast(
9459 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9460 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9462 // Unpack the bytes to form the i16s that will be shuffled into place.
9463 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9464 MVT::v16i8, V1, V1);
9466 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9467 for (int i = 0; i < 16; ++i)
9468 if (Mask[i] != -1) {
9469 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9470 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9471 if (PostDupI16Shuffle[i / 2] == -1)
9472 PostDupI16Shuffle[i / 2] = MappedMask;
9474 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9475 "Conflicting entrties in the original shuffle!");
9477 return DAG.getBitcast(
9479 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9480 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9482 if (SDValue V = tryToWidenViaDuplication())
9486 if (SDValue Masked =
9487 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9490 // Use dedicated unpack instructions for masks that match their pattern.
9492 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9495 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9496 // with PSHUFB. It is important to do this before we attempt to generate any
9497 // blends but after all of the single-input lowerings. If the single input
9498 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9499 // want to preserve that and we can DAG combine any longer sequences into
9500 // a PSHUFB in the end. But once we start blending from multiple inputs,
9501 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9502 // and there are *very* few patterns that would actually be faster than the
9503 // PSHUFB approach because of its ability to zero lanes.
9505 // FIXME: The only exceptions to the above are blends which are exact
9506 // interleavings with direct instructions supporting them. We currently don't
9507 // handle those well here.
9508 if (Subtarget->hasSSSE3()) {
9509 bool V1InUse = false;
9510 bool V2InUse = false;
9512 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9513 DAG, V1InUse, V2InUse);
9515 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9516 // do so. This avoids using them to handle blends-with-zero which is
9517 // important as a single pshufb is significantly faster for that.
9518 if (V1InUse && V2InUse) {
9519 if (Subtarget->hasSSE41())
9520 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9521 Mask, Subtarget, DAG))
9524 // We can use an unpack to do the blending rather than an or in some
9525 // cases. Even though the or may be (very minorly) more efficient, we
9526 // preference this lowering because there are common cases where part of
9527 // the complexity of the shuffles goes away when we do the final blend as
9529 // FIXME: It might be worth trying to detect if the unpack-feeding
9530 // shuffles will both be pshufb, in which case we shouldn't bother with
9532 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9533 DL, MVT::v16i8, V1, V2, Mask, DAG))
9540 // There are special ways we can lower some single-element blends.
9541 if (NumV2Elements == 1)
9542 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9543 Mask, Subtarget, DAG))
9546 if (SDValue BitBlend =
9547 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9550 // Check whether a compaction lowering can be done. This handles shuffles
9551 // which take every Nth element for some even N. See the helper function for
9554 // We special case these as they can be particularly efficiently handled with
9555 // the PACKUSB instruction on x86 and they show up in common patterns of
9556 // rearranging bytes to truncate wide elements.
9557 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9558 // NumEvenDrops is the power of two stride of the elements. Another way of
9559 // thinking about it is that we need to drop the even elements this many
9560 // times to get the original input.
9561 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9563 // First we need to zero all the dropped bytes.
9564 assert(NumEvenDrops <= 3 &&
9565 "No support for dropping even elements more than 3 times.");
9566 // We use the mask type to pick which bytes are preserved based on how many
9567 // elements are dropped.
9568 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9569 SDValue ByteClearMask = DAG.getBitcast(
9570 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9571 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9573 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9575 // Now pack things back together.
9576 V1 = DAG.getBitcast(MVT::v8i16, V1);
9577 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9578 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9579 for (int i = 1; i < NumEvenDrops; ++i) {
9580 Result = DAG.getBitcast(MVT::v8i16, Result);
9581 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9587 // Handle multi-input cases by blending single-input shuffles.
9588 if (NumV2Elements > 0)
9589 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9592 // The fallback path for single-input shuffles widens this into two v8i16
9593 // vectors with unpacks, shuffles those, and then pulls them back together
9597 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9598 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9599 for (int i = 0; i < 16; ++i)
9601 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9603 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9605 SDValue VLoHalf, VHiHalf;
9606 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9607 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9609 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9610 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9611 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9612 [](int M) { return M >= 0 && M % 2 == 1; })) {
9613 // Use a mask to drop the high bytes.
9614 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9615 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9616 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9618 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9619 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9621 // Squash the masks to point directly into VLoHalf.
9622 for (int &M : LoBlendMask)
9625 for (int &M : HiBlendMask)
9629 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9630 // VHiHalf so that we can blend them as i16s.
9631 VLoHalf = DAG.getBitcast(
9632 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9633 VHiHalf = DAG.getBitcast(
9634 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9637 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9638 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9640 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9643 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9645 /// This routine breaks down the specific type of 128-bit shuffle and
9646 /// dispatches to the lowering routines accordingly.
9647 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9648 MVT VT, const X86Subtarget *Subtarget,
9649 SelectionDAG &DAG) {
9650 switch (VT.SimpleTy) {
9652 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9654 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9656 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9658 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9660 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9662 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9665 llvm_unreachable("Unimplemented!");
9669 /// \brief Helper function to test whether a shuffle mask could be
9670 /// simplified by widening the elements being shuffled.
9672 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9673 /// leaves it in an unspecified state.
9675 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9676 /// shuffle masks. The latter have the special property of a '-2' representing
9677 /// a zero-ed lane of a vector.
9678 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9679 SmallVectorImpl<int> &WidenedMask) {
9680 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9681 // If both elements are undef, its trivial.
9682 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9683 WidenedMask.push_back(SM_SentinelUndef);
9687 // Check for an undef mask and a mask value properly aligned to fit with
9688 // a pair of values. If we find such a case, use the non-undef mask's value.
9689 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9690 WidenedMask.push_back(Mask[i + 1] / 2);
9693 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9694 WidenedMask.push_back(Mask[i] / 2);
9698 // When zeroing, we need to spread the zeroing across both lanes to widen.
9699 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9700 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9701 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9702 WidenedMask.push_back(SM_SentinelZero);
9708 // Finally check if the two mask values are adjacent and aligned with
9710 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9711 WidenedMask.push_back(Mask[i] / 2);
9715 // Otherwise we can't safely widen the elements used in this shuffle.
9718 assert(WidenedMask.size() == Mask.size() / 2 &&
9719 "Incorrect size of mask after widening the elements!");
9724 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9726 /// This routine just extracts two subvectors, shuffles them independently, and
9727 /// then concatenates them back together. This should work effectively with all
9728 /// AVX vector shuffle types.
9729 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9730 SDValue V2, ArrayRef<int> Mask,
9731 SelectionDAG &DAG) {
9732 assert(VT.getSizeInBits() >= 256 &&
9733 "Only for 256-bit or wider vector shuffles!");
9734 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9735 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9737 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9738 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9740 int NumElements = VT.getVectorNumElements();
9741 int SplitNumElements = NumElements / 2;
9742 MVT ScalarVT = VT.getScalarType();
9743 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9745 // Rather than splitting build-vectors, just build two narrower build
9746 // vectors. This helps shuffling with splats and zeros.
9747 auto SplitVector = [&](SDValue V) {
9748 while (V.getOpcode() == ISD::BITCAST)
9749 V = V->getOperand(0);
9751 MVT OrigVT = V.getSimpleValueType();
9752 int OrigNumElements = OrigVT.getVectorNumElements();
9753 int OrigSplitNumElements = OrigNumElements / 2;
9754 MVT OrigScalarVT = OrigVT.getScalarType();
9755 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9759 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9761 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9762 DAG.getIntPtrConstant(0, DL));
9763 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9764 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9767 SmallVector<SDValue, 16> LoOps, HiOps;
9768 for (int i = 0; i < OrigSplitNumElements; ++i) {
9769 LoOps.push_back(BV->getOperand(i));
9770 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9772 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9773 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9775 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9776 DAG.getBitcast(SplitVT, HiV));
9779 SDValue LoV1, HiV1, LoV2, HiV2;
9780 std::tie(LoV1, HiV1) = SplitVector(V1);
9781 std::tie(LoV2, HiV2) = SplitVector(V2);
9783 // Now create two 4-way blends of these half-width vectors.
9784 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9785 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9786 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9787 for (int i = 0; i < SplitNumElements; ++i) {
9788 int M = HalfMask[i];
9789 if (M >= NumElements) {
9790 if (M >= NumElements + SplitNumElements)
9794 V2BlendMask.push_back(M - NumElements);
9795 V1BlendMask.push_back(-1);
9796 BlendMask.push_back(SplitNumElements + i);
9797 } else if (M >= 0) {
9798 if (M >= SplitNumElements)
9802 V2BlendMask.push_back(-1);
9803 V1BlendMask.push_back(M);
9804 BlendMask.push_back(i);
9806 V2BlendMask.push_back(-1);
9807 V1BlendMask.push_back(-1);
9808 BlendMask.push_back(-1);
9812 // Because the lowering happens after all combining takes place, we need to
9813 // manually combine these blend masks as much as possible so that we create
9814 // a minimal number of high-level vector shuffle nodes.
9816 // First try just blending the halves of V1 or V2.
9817 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9818 return DAG.getUNDEF(SplitVT);
9819 if (!UseLoV2 && !UseHiV2)
9820 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9821 if (!UseLoV1 && !UseHiV1)
9822 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9824 SDValue V1Blend, V2Blend;
9825 if (UseLoV1 && UseHiV1) {
9827 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9829 // We only use half of V1 so map the usage down into the final blend mask.
9830 V1Blend = UseLoV1 ? LoV1 : HiV1;
9831 for (int i = 0; i < SplitNumElements; ++i)
9832 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9833 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9835 if (UseLoV2 && UseHiV2) {
9837 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9839 // We only use half of V2 so map the usage down into the final blend mask.
9840 V2Blend = UseLoV2 ? LoV2 : HiV2;
9841 for (int i = 0; i < SplitNumElements; ++i)
9842 if (BlendMask[i] >= SplitNumElements)
9843 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9845 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9847 SDValue Lo = HalfBlend(LoMask);
9848 SDValue Hi = HalfBlend(HiMask);
9849 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9852 /// \brief Either split a vector in halves or decompose the shuffles and the
9855 /// This is provided as a good fallback for many lowerings of non-single-input
9856 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9857 /// between splitting the shuffle into 128-bit components and stitching those
9858 /// back together vs. extracting the single-input shuffles and blending those
9860 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9861 SDValue V2, ArrayRef<int> Mask,
9862 SelectionDAG &DAG) {
9863 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9864 "lower single-input shuffles as it "
9865 "could then recurse on itself.");
9866 int Size = Mask.size();
9868 // If this can be modeled as a broadcast of two elements followed by a blend,
9869 // prefer that lowering. This is especially important because broadcasts can
9870 // often fold with memory operands.
9871 auto DoBothBroadcast = [&] {
9872 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9875 if (V2BroadcastIdx == -1)
9876 V2BroadcastIdx = M - Size;
9877 else if (M - Size != V2BroadcastIdx)
9879 } else if (M >= 0) {
9880 if (V1BroadcastIdx == -1)
9882 else if (M != V1BroadcastIdx)
9887 if (DoBothBroadcast())
9888 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9891 // If the inputs all stem from a single 128-bit lane of each input, then we
9892 // split them rather than blending because the split will decompose to
9893 // unusually few instructions.
9894 int LaneCount = VT.getSizeInBits() / 128;
9895 int LaneSize = Size / LaneCount;
9896 SmallBitVector LaneInputs[2];
9897 LaneInputs[0].resize(LaneCount, false);
9898 LaneInputs[1].resize(LaneCount, false);
9899 for (int i = 0; i < Size; ++i)
9901 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9902 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9903 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9905 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9906 // that the decomposed single-input shuffles don't end up here.
9907 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9910 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9911 /// a permutation and blend of those lanes.
9913 /// This essentially blends the out-of-lane inputs to each lane into the lane
9914 /// from a permuted copy of the vector. This lowering strategy results in four
9915 /// instructions in the worst case for a single-input cross lane shuffle which
9916 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9917 /// of. Special cases for each particular shuffle pattern should be handled
9918 /// prior to trying this lowering.
9919 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9920 SDValue V1, SDValue V2,
9922 SelectionDAG &DAG) {
9923 // FIXME: This should probably be generalized for 512-bit vectors as well.
9924 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9925 int LaneSize = Mask.size() / 2;
9927 // If there are only inputs from one 128-bit lane, splitting will in fact be
9928 // less expensive. The flags track whether the given lane contains an element
9929 // that crosses to another lane.
9930 bool LaneCrossing[2] = {false, false};
9931 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9932 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9933 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9934 if (!LaneCrossing[0] || !LaneCrossing[1])
9935 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9937 if (isSingleInputShuffleMask(Mask)) {
9938 SmallVector<int, 32> FlippedBlendMask;
9939 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9940 FlippedBlendMask.push_back(
9941 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9943 : Mask[i] % LaneSize +
9944 (i / LaneSize) * LaneSize + Size));
9946 // Flip the vector, and blend the results which should now be in-lane. The
9947 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9948 // 5 for the high source. The value 3 selects the high half of source 2 and
9949 // the value 2 selects the low half of source 2. We only use source 2 to
9950 // allow folding it into a memory operand.
9951 unsigned PERMMask = 3 | 2 << 4;
9952 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9953 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9954 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9957 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9958 // will be handled by the above logic and a blend of the results, much like
9959 // other patterns in AVX.
9960 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9963 /// \brief Handle lowering 2-lane 128-bit shuffles.
9964 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9965 SDValue V2, ArrayRef<int> Mask,
9966 const X86Subtarget *Subtarget,
9967 SelectionDAG &DAG) {
9968 // TODO: If minimizing size and one of the inputs is a zero vector and the
9969 // the zero vector has only one use, we could use a VPERM2X128 to save the
9970 // instruction bytes needed to explicitly generate the zero vector.
9972 // Blends are faster and handle all the non-lane-crossing cases.
9973 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9977 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9978 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9980 // If either input operand is a zero vector, use VPERM2X128 because its mask
9981 // allows us to replace the zero input with an implicit zero.
9982 if (!IsV1Zero && !IsV2Zero) {
9983 // Check for patterns which can be matched with a single insert of a 128-bit
9985 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9986 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9987 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9988 VT.getVectorNumElements() / 2);
9989 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9990 DAG.getIntPtrConstant(0, DL));
9991 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9992 OnlyUsesV1 ? V1 : V2,
9993 DAG.getIntPtrConstant(0, DL));
9994 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9998 // Otherwise form a 128-bit permutation. After accounting for undefs,
9999 // convert the 64-bit shuffle mask selection values into 128-bit
10000 // selection bits by dividing the indexes by 2 and shifting into positions
10001 // defined by a vperm2*128 instruction's immediate control byte.
10003 // The immediate permute control byte looks like this:
10004 // [1:0] - select 128 bits from sources for low half of destination
10006 // [3] - zero low half of destination
10007 // [5:4] - select 128 bits from sources for high half of destination
10009 // [7] - zero high half of destination
10011 int MaskLO = Mask[0];
10012 if (MaskLO == SM_SentinelUndef)
10013 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10015 int MaskHI = Mask[2];
10016 if (MaskHI == SM_SentinelUndef)
10017 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10019 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10021 // If either input is a zero vector, replace it with an undef input.
10022 // Shuffle mask values < 4 are selecting elements of V1.
10023 // Shuffle mask values >= 4 are selecting elements of V2.
10024 // Adjust each half of the permute mask by clearing the half that was
10025 // selecting the zero vector and setting the zero mask bit.
10027 V1 = DAG.getUNDEF(VT);
10029 PermMask = (PermMask & 0xf0) | 0x08;
10031 PermMask = (PermMask & 0x0f) | 0x80;
10034 V2 = DAG.getUNDEF(VT);
10036 PermMask = (PermMask & 0xf0) | 0x08;
10038 PermMask = (PermMask & 0x0f) | 0x80;
10041 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10042 DAG.getConstant(PermMask, DL, MVT::i8));
10045 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10046 /// shuffling each lane.
10048 /// This will only succeed when the result of fixing the 128-bit lanes results
10049 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10050 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10051 /// the lane crosses early and then use simpler shuffles within each lane.
10053 /// FIXME: It might be worthwhile at some point to support this without
10054 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10055 /// in x86 only floating point has interesting non-repeating shuffles, and even
10056 /// those are still *marginally* more expensive.
10057 static SDValue lowerVectorShuffleByMerging128BitLanes(
10058 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10059 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10060 assert(!isSingleInputShuffleMask(Mask) &&
10061 "This is only useful with multiple inputs.");
10063 int Size = Mask.size();
10064 int LaneSize = 128 / VT.getScalarSizeInBits();
10065 int NumLanes = Size / LaneSize;
10066 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10068 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10069 // check whether the in-128-bit lane shuffles share a repeating pattern.
10070 SmallVector<int, 4> Lanes;
10071 Lanes.resize(NumLanes, -1);
10072 SmallVector<int, 4> InLaneMask;
10073 InLaneMask.resize(LaneSize, -1);
10074 for (int i = 0; i < Size; ++i) {
10078 int j = i / LaneSize;
10080 if (Lanes[j] < 0) {
10081 // First entry we've seen for this lane.
10082 Lanes[j] = Mask[i] / LaneSize;
10083 } else if (Lanes[j] != Mask[i] / LaneSize) {
10084 // This doesn't match the lane selected previously!
10088 // Check that within each lane we have a consistent shuffle mask.
10089 int k = i % LaneSize;
10090 if (InLaneMask[k] < 0) {
10091 InLaneMask[k] = Mask[i] % LaneSize;
10092 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10093 // This doesn't fit a repeating in-lane mask.
10098 // First shuffle the lanes into place.
10099 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10100 VT.getSizeInBits() / 64);
10101 SmallVector<int, 8> LaneMask;
10102 LaneMask.resize(NumLanes * 2, -1);
10103 for (int i = 0; i < NumLanes; ++i)
10104 if (Lanes[i] >= 0) {
10105 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10106 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10109 V1 = DAG.getBitcast(LaneVT, V1);
10110 V2 = DAG.getBitcast(LaneVT, V2);
10111 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10113 // Cast it back to the type we actually want.
10114 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10116 // Now do a simple shuffle that isn't lane crossing.
10117 SmallVector<int, 8> NewMask;
10118 NewMask.resize(Size, -1);
10119 for (int i = 0; i < Size; ++i)
10121 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10122 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10123 "Must not introduce lane crosses at this point!");
10125 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10128 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10131 /// This returns true if the elements from a particular input are already in the
10132 /// slot required by the given mask and require no permutation.
10133 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10134 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10135 int Size = Mask.size();
10136 for (int i = 0; i < Size; ++i)
10137 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10143 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10144 ArrayRef<int> Mask, SDValue V1,
10145 SDValue V2, SelectionDAG &DAG) {
10147 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10148 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10149 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10150 int NumElts = VT.getVectorNumElements();
10151 bool ShufpdMask = true;
10152 bool CommutableMask = true;
10153 unsigned Immediate = 0;
10154 for (int i = 0; i < NumElts; ++i) {
10157 int Val = (i & 6) + NumElts * (i & 1);
10158 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10159 if (Mask[i] < Val || Mask[i] > Val + 1)
10160 ShufpdMask = false;
10161 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10162 CommutableMask = false;
10163 Immediate |= (Mask[i] % 2) << i;
10166 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10167 DAG.getConstant(Immediate, DL, MVT::i8));
10168 if (CommutableMask)
10169 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10170 DAG.getConstant(Immediate, DL, MVT::i8));
10174 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10176 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10177 /// isn't available.
10178 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10179 const X86Subtarget *Subtarget,
10180 SelectionDAG &DAG) {
10182 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10183 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10184 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10185 ArrayRef<int> Mask = SVOp->getMask();
10186 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10188 SmallVector<int, 4> WidenedMask;
10189 if (canWidenShuffleElements(Mask, WidenedMask))
10190 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10193 if (isSingleInputShuffleMask(Mask)) {
10194 // Check for being able to broadcast a single element.
10195 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10196 Mask, Subtarget, DAG))
10199 // Use low duplicate instructions for masks that match their pattern.
10200 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10201 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10203 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10204 // Non-half-crossing single input shuffles can be lowerid with an
10205 // interleaved permutation.
10206 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10207 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10208 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10209 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10212 // With AVX2 we have direct support for this permutation.
10213 if (Subtarget->hasAVX2())
10214 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10215 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10217 // Otherwise, fall back.
10218 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10222 // Use dedicated unpack instructions for masks that match their pattern.
10224 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10227 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10231 // Check if the blend happens to exactly fit that of SHUFPD.
10233 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10236 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10237 // shuffle. However, if we have AVX2 and either inputs are already in place,
10238 // we will be able to shuffle even across lanes the other input in a single
10239 // instruction so skip this pattern.
10240 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10241 isShuffleMaskInputInPlace(1, Mask))))
10242 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10243 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10246 // If we have AVX2 then we always want to lower with a blend because an v4 we
10247 // can fully permute the elements.
10248 if (Subtarget->hasAVX2())
10249 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10252 // Otherwise fall back on generic lowering.
10253 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10256 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10258 /// This routine is only called when we have AVX2 and thus a reasonable
10259 /// instruction set for v4i64 shuffling..
10260 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10261 const X86Subtarget *Subtarget,
10262 SelectionDAG &DAG) {
10264 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10265 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10266 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10267 ArrayRef<int> Mask = SVOp->getMask();
10268 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10269 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10271 SmallVector<int, 4> WidenedMask;
10272 if (canWidenShuffleElements(Mask, WidenedMask))
10273 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10276 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10280 // Check for being able to broadcast a single element.
10281 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10282 Mask, Subtarget, DAG))
10285 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10286 // use lower latency instructions that will operate on both 128-bit lanes.
10287 SmallVector<int, 2> RepeatedMask;
10288 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10289 if (isSingleInputShuffleMask(Mask)) {
10290 int PSHUFDMask[] = {-1, -1, -1, -1};
10291 for (int i = 0; i < 2; ++i)
10292 if (RepeatedMask[i] >= 0) {
10293 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10294 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10296 return DAG.getBitcast(
10298 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10299 DAG.getBitcast(MVT::v8i32, V1),
10300 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10304 // AVX2 provides a direct instruction for permuting a single input across
10306 if (isSingleInputShuffleMask(Mask))
10307 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10308 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10310 // Try to use shift instructions.
10311 if (SDValue Shift =
10312 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10315 // Use dedicated unpack instructions for masks that match their pattern.
10317 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10320 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10321 // shuffle. However, if we have AVX2 and either inputs are already in place,
10322 // we will be able to shuffle even across lanes the other input in a single
10323 // instruction so skip this pattern.
10324 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10325 isShuffleMaskInputInPlace(1, Mask))))
10326 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10327 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10330 // Otherwise fall back on generic blend lowering.
10331 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10335 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10337 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10338 /// isn't available.
10339 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10340 const X86Subtarget *Subtarget,
10341 SelectionDAG &DAG) {
10343 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10344 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10345 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10346 ArrayRef<int> Mask = SVOp->getMask();
10347 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10349 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10353 // Check for being able to broadcast a single element.
10354 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10355 Mask, Subtarget, DAG))
10358 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10359 // options to efficiently lower the shuffle.
10360 SmallVector<int, 4> RepeatedMask;
10361 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10362 assert(RepeatedMask.size() == 4 &&
10363 "Repeated masks must be half the mask width!");
10365 // Use even/odd duplicate instructions for masks that match their pattern.
10366 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10367 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10368 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10369 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10371 if (isSingleInputShuffleMask(Mask))
10372 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10373 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10375 // Use dedicated unpack instructions for masks that match their pattern.
10377 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10380 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10381 // have already handled any direct blends. We also need to squash the
10382 // repeated mask into a simulated v4f32 mask.
10383 for (int i = 0; i < 4; ++i)
10384 if (RepeatedMask[i] >= 8)
10385 RepeatedMask[i] -= 4;
10386 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10389 // If we have a single input shuffle with different shuffle patterns in the
10390 // two 128-bit lanes use the variable mask to VPERMILPS.
10391 if (isSingleInputShuffleMask(Mask)) {
10392 SDValue VPermMask[8];
10393 for (int i = 0; i < 8; ++i)
10394 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10395 : DAG.getConstant(Mask[i], DL, MVT::i32);
10396 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10397 return DAG.getNode(
10398 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10399 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10401 if (Subtarget->hasAVX2())
10402 return DAG.getNode(
10403 X86ISD::VPERMV, DL, MVT::v8f32,
10404 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10405 MVT::v8i32, VPermMask)),
10408 // Otherwise, fall back.
10409 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10413 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10415 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10416 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10419 // If we have AVX2 then we always want to lower with a blend because at v8 we
10420 // can fully permute the elements.
10421 if (Subtarget->hasAVX2())
10422 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10425 // Otherwise fall back on generic lowering.
10426 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10429 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10431 /// This routine is only called when we have AVX2 and thus a reasonable
10432 /// instruction set for v8i32 shuffling..
10433 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10434 const X86Subtarget *Subtarget,
10435 SelectionDAG &DAG) {
10437 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10438 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10439 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10440 ArrayRef<int> Mask = SVOp->getMask();
10441 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10442 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10444 // Whenever we can lower this as a zext, that instruction is strictly faster
10445 // than any alternative. It also allows us to fold memory operands into the
10446 // shuffle in many cases.
10447 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10448 Mask, Subtarget, DAG))
10451 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10455 // Check for being able to broadcast a single element.
10456 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10457 Mask, Subtarget, DAG))
10460 // If the shuffle mask is repeated in each 128-bit lane we can use more
10461 // efficient instructions that mirror the shuffles across the two 128-bit
10463 SmallVector<int, 4> RepeatedMask;
10464 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10465 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10466 if (isSingleInputShuffleMask(Mask))
10467 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10468 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10470 // Use dedicated unpack instructions for masks that match their pattern.
10472 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10476 // Try to use shift instructions.
10477 if (SDValue Shift =
10478 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10481 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10482 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10485 // If the shuffle patterns aren't repeated but it is a single input, directly
10486 // generate a cross-lane VPERMD instruction.
10487 if (isSingleInputShuffleMask(Mask)) {
10488 SDValue VPermMask[8];
10489 for (int i = 0; i < 8; ++i)
10490 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10491 : DAG.getConstant(Mask[i], DL, MVT::i32);
10492 return DAG.getNode(
10493 X86ISD::VPERMV, DL, MVT::v8i32,
10494 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10497 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10499 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10500 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10503 // Otherwise fall back on generic blend lowering.
10504 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10508 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10510 /// This routine is only called when we have AVX2 and thus a reasonable
10511 /// instruction set for v16i16 shuffling..
10512 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10513 const X86Subtarget *Subtarget,
10514 SelectionDAG &DAG) {
10516 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10517 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10518 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10519 ArrayRef<int> Mask = SVOp->getMask();
10520 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10521 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10523 // Whenever we can lower this as a zext, that instruction is strictly faster
10524 // than any alternative. It also allows us to fold memory operands into the
10525 // shuffle in many cases.
10526 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10527 Mask, Subtarget, DAG))
10530 // Check for being able to broadcast a single element.
10531 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10532 Mask, Subtarget, DAG))
10535 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10539 // Use dedicated unpack instructions for masks that match their pattern.
10541 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10544 // Try to use shift instructions.
10545 if (SDValue Shift =
10546 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10549 // Try to use byte rotation instructions.
10550 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10551 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10554 if (isSingleInputShuffleMask(Mask)) {
10555 // There are no generalized cross-lane shuffle operations available on i16
10557 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10558 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10561 SmallVector<int, 8> RepeatedMask;
10562 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10563 // As this is a single-input shuffle, the repeated mask should be
10564 // a strictly valid v8i16 mask that we can pass through to the v8i16
10565 // lowering to handle even the v16 case.
10566 return lowerV8I16GeneralSingleInputVectorShuffle(
10567 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10570 SDValue PSHUFBMask[32];
10571 for (int i = 0; i < 16; ++i) {
10572 if (Mask[i] == -1) {
10573 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10577 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10578 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10579 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10580 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10582 return DAG.getBitcast(MVT::v16i16,
10583 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10584 DAG.getBitcast(MVT::v32i8, V1),
10585 DAG.getNode(ISD::BUILD_VECTOR, DL,
10586 MVT::v32i8, PSHUFBMask)));
10589 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10591 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10592 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10595 // Otherwise fall back on generic lowering.
10596 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10599 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10601 /// This routine is only called when we have AVX2 and thus a reasonable
10602 /// instruction set for v32i8 shuffling..
10603 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10604 const X86Subtarget *Subtarget,
10605 SelectionDAG &DAG) {
10607 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10608 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10609 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10610 ArrayRef<int> Mask = SVOp->getMask();
10611 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10612 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10614 // Whenever we can lower this as a zext, that instruction is strictly faster
10615 // than any alternative. It also allows us to fold memory operands into the
10616 // shuffle in many cases.
10617 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10618 Mask, Subtarget, DAG))
10621 // Check for being able to broadcast a single element.
10622 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10623 Mask, Subtarget, DAG))
10626 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10630 // Use dedicated unpack instructions for masks that match their pattern.
10632 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10635 // Try to use shift instructions.
10636 if (SDValue Shift =
10637 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10640 // Try to use byte rotation instructions.
10641 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10642 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10645 if (isSingleInputShuffleMask(Mask)) {
10646 // There are no generalized cross-lane shuffle operations available on i8
10648 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10649 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10652 SDValue PSHUFBMask[32];
10653 for (int i = 0; i < 32; ++i)
10656 ? DAG.getUNDEF(MVT::i8)
10657 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10660 return DAG.getNode(
10661 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10662 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10665 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10667 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10668 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10671 // Otherwise fall back on generic lowering.
10672 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10675 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10677 /// This routine either breaks down the specific type of a 256-bit x86 vector
10678 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10679 /// together based on the available instructions.
10680 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10681 MVT VT, const X86Subtarget *Subtarget,
10682 SelectionDAG &DAG) {
10684 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10685 ArrayRef<int> Mask = SVOp->getMask();
10687 // If we have a single input to the zero element, insert that into V1 if we
10688 // can do so cheaply.
10689 int NumElts = VT.getVectorNumElements();
10690 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10691 return M >= NumElts;
10694 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10695 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10696 DL, VT, V1, V2, Mask, Subtarget, DAG))
10699 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10700 // can check for those subtargets here and avoid much of the subtarget
10701 // querying in the per-vector-type lowering routines. With AVX1 we have
10702 // essentially *zero* ability to manipulate a 256-bit vector with integer
10703 // types. Since we'll use floating point types there eventually, just
10704 // immediately cast everything to a float and operate entirely in that domain.
10705 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10706 int ElementBits = VT.getScalarSizeInBits();
10707 if (ElementBits < 32)
10708 // No floating point type available, decompose into 128-bit vectors.
10709 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10711 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10712 VT.getVectorNumElements());
10713 V1 = DAG.getBitcast(FpVT, V1);
10714 V2 = DAG.getBitcast(FpVT, V2);
10715 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10718 switch (VT.SimpleTy) {
10720 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10722 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10724 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10726 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10728 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10730 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10733 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10737 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10738 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10739 ArrayRef<int> Mask,
10740 SDValue V1, SDValue V2,
10741 SelectionDAG &DAG) {
10742 assert(VT.getScalarSizeInBits() == 64 &&
10743 "Unexpected element type size for 128bit shuffle.");
10745 // To handle 256 bit vector requires VLX and most probably
10746 // function lowerV2X128VectorShuffle() is better solution.
10747 assert(VT.getSizeInBits() == 512 &&
10748 "Unexpected vector size for 128bit shuffle.");
10750 SmallVector<int, 4> WidenedMask;
10751 if (!canWidenShuffleElements(Mask, WidenedMask))
10754 // Form a 128-bit permutation.
10755 // Convert the 64-bit shuffle mask selection values into 128-bit selection
10756 // bits defined by a vshuf64x2 instruction's immediate control byte.
10757 unsigned PermMask = 0, Imm = 0;
10758 unsigned ControlBitsNum = WidenedMask.size() / 2;
10760 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10761 if (WidenedMask[i] == SM_SentinelZero)
10764 // Use first element in place of undef mask.
10765 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10766 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10769 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10770 DAG.getConstant(PermMask, DL, MVT::i8));
10773 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10774 ArrayRef<int> Mask, SDValue V1,
10775 SDValue V2, SelectionDAG &DAG) {
10777 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10779 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10780 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10782 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10783 if (isSingleInputShuffleMask(Mask))
10784 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10786 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10789 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10790 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10791 const X86Subtarget *Subtarget,
10792 SelectionDAG &DAG) {
10794 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10795 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10796 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10797 ArrayRef<int> Mask = SVOp->getMask();
10798 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10800 if (SDValue Shuf128 =
10801 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10804 if (SDValue Unpck =
10805 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10808 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10811 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10812 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10813 const X86Subtarget *Subtarget,
10814 SelectionDAG &DAG) {
10816 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10817 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10818 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10819 ArrayRef<int> Mask = SVOp->getMask();
10820 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10822 if (SDValue Unpck =
10823 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10826 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10829 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10830 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10831 const X86Subtarget *Subtarget,
10832 SelectionDAG &DAG) {
10834 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10835 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10836 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10837 ArrayRef<int> Mask = SVOp->getMask();
10838 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10840 if (SDValue Shuf128 =
10841 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10844 if (SDValue Unpck =
10845 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10848 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10851 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10852 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10853 const X86Subtarget *Subtarget,
10854 SelectionDAG &DAG) {
10856 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10857 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10858 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10859 ArrayRef<int> Mask = SVOp->getMask();
10860 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10862 if (SDValue Unpck =
10863 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10866 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10869 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10870 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10871 const X86Subtarget *Subtarget,
10872 SelectionDAG &DAG) {
10874 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10875 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10876 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10877 ArrayRef<int> Mask = SVOp->getMask();
10878 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10879 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10881 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10884 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10885 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10886 const X86Subtarget *Subtarget,
10887 SelectionDAG &DAG) {
10889 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10890 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10892 ArrayRef<int> Mask = SVOp->getMask();
10893 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10894 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10896 // FIXME: Implement direct support for this type!
10897 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10900 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10902 /// This routine either breaks down the specific type of a 512-bit x86 vector
10903 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10904 /// together based on the available instructions.
10905 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10906 MVT VT, const X86Subtarget *Subtarget,
10907 SelectionDAG &DAG) {
10909 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10910 ArrayRef<int> Mask = SVOp->getMask();
10911 assert(Subtarget->hasAVX512() &&
10912 "Cannot lower 512-bit vectors w/ basic ISA!");
10914 // Check for being able to broadcast a single element.
10915 if (SDValue Broadcast =
10916 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10919 // Dispatch to each element type for lowering. If we don't have supprot for
10920 // specific element type shuffles at 512 bits, immediately split them and
10921 // lower them. Each lowering routine of a given type is allowed to assume that
10922 // the requisite ISA extensions for that element type are available.
10923 switch (VT.SimpleTy) {
10925 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10927 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10929 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10931 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10933 if (Subtarget->hasBWI())
10934 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10937 if (Subtarget->hasBWI())
10938 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10942 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10945 // Otherwise fall back on splitting.
10946 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10949 // Lower vXi1 vector shuffles.
10950 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10951 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10952 // vector, shuffle and then truncate it back.
10953 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10954 MVT VT, const X86Subtarget *Subtarget,
10955 SelectionDAG &DAG) {
10957 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10958 ArrayRef<int> Mask = SVOp->getMask();
10959 assert(Subtarget->hasAVX512() &&
10960 "Cannot lower 512-bit vectors w/o basic ISA!");
10962 switch (VT.SimpleTy) {
10964 llvm_unreachable("Expected a vector of i1 elements");
10966 ExtVT = MVT::v2i64;
10969 ExtVT = MVT::v4i32;
10972 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10975 ExtVT = MVT::v16i32;
10978 ExtVT = MVT::v32i16;
10981 ExtVT = MVT::v64i8;
10985 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10986 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10987 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10988 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10990 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10993 V2 = DAG.getUNDEF(ExtVT);
10994 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10995 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10996 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10997 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10999 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11000 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11001 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11003 /// \brief Top-level lowering for x86 vector shuffles.
11005 /// This handles decomposition, canonicalization, and lowering of all x86
11006 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11007 /// above in helper routines. The canonicalization attempts to widen shuffles
11008 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11009 /// s.t. only one of the two inputs needs to be tested, etc.
11010 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11011 SelectionDAG &DAG) {
11012 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11013 ArrayRef<int> Mask = SVOp->getMask();
11014 SDValue V1 = Op.getOperand(0);
11015 SDValue V2 = Op.getOperand(1);
11016 MVT VT = Op.getSimpleValueType();
11017 int NumElements = VT.getVectorNumElements();
11019 bool Is1BitVector = (VT.getScalarType() == MVT::i1);
11021 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11022 "Can't lower MMX shuffles");
11024 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11025 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11026 if (V1IsUndef && V2IsUndef)
11027 return DAG.getUNDEF(VT);
11029 // When we create a shuffle node we put the UNDEF node to second operand,
11030 // but in some cases the first operand may be transformed to UNDEF.
11031 // In this case we should just commute the node.
11033 return DAG.getCommutedVectorShuffle(*SVOp);
11035 // Check for non-undef masks pointing at an undef vector and make the masks
11036 // undef as well. This makes it easier to match the shuffle based solely on
11040 if (M >= NumElements) {
11041 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11042 for (int &M : NewMask)
11043 if (M >= NumElements)
11045 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11048 // We actually see shuffles that are entirely re-arrangements of a set of
11049 // zero inputs. This mostly happens while decomposing complex shuffles into
11050 // simple ones. Directly lower these as a buildvector of zeros.
11051 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11052 if (Zeroable.all())
11053 return getZeroVector(VT, Subtarget, DAG, dl);
11055 // Try to collapse shuffles into using a vector type with fewer elements but
11056 // wider element types. We cap this to not form integers or floating point
11057 // elements wider than 64 bits, but it might be interesting to form i128
11058 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11059 SmallVector<int, 16> WidenedMask;
11060 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11061 canWidenShuffleElements(Mask, WidenedMask)) {
11062 MVT NewEltVT = VT.isFloatingPoint()
11063 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11064 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11065 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11066 // Make sure that the new vector type is legal. For example, v2f64 isn't
11068 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11069 V1 = DAG.getBitcast(NewVT, V1);
11070 V2 = DAG.getBitcast(NewVT, V2);
11071 return DAG.getBitcast(
11072 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11076 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11077 for (int M : SVOp->getMask())
11079 ++NumUndefElements;
11080 else if (M < NumElements)
11085 // Commute the shuffle as needed such that more elements come from V1 than
11086 // V2. This allows us to match the shuffle pattern strictly on how many
11087 // elements come from V1 without handling the symmetric cases.
11088 if (NumV2Elements > NumV1Elements)
11089 return DAG.getCommutedVectorShuffle(*SVOp);
11091 // When the number of V1 and V2 elements are the same, try to minimize the
11092 // number of uses of V2 in the low half of the vector. When that is tied,
11093 // ensure that the sum of indices for V1 is equal to or lower than the sum
11094 // indices for V2. When those are equal, try to ensure that the number of odd
11095 // indices for V1 is lower than the number of odd indices for V2.
11096 if (NumV1Elements == NumV2Elements) {
11097 int LowV1Elements = 0, LowV2Elements = 0;
11098 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11099 if (M >= NumElements)
11103 if (LowV2Elements > LowV1Elements) {
11104 return DAG.getCommutedVectorShuffle(*SVOp);
11105 } else if (LowV2Elements == LowV1Elements) {
11106 int SumV1Indices = 0, SumV2Indices = 0;
11107 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11108 if (SVOp->getMask()[i] >= NumElements)
11110 else if (SVOp->getMask()[i] >= 0)
11112 if (SumV2Indices < SumV1Indices) {
11113 return DAG.getCommutedVectorShuffle(*SVOp);
11114 } else if (SumV2Indices == SumV1Indices) {
11115 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11116 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11117 if (SVOp->getMask()[i] >= NumElements)
11118 NumV2OddIndices += i % 2;
11119 else if (SVOp->getMask()[i] >= 0)
11120 NumV1OddIndices += i % 2;
11121 if (NumV2OddIndices < NumV1OddIndices)
11122 return DAG.getCommutedVectorShuffle(*SVOp);
11127 // For each vector width, delegate to a specialized lowering routine.
11128 if (VT.getSizeInBits() == 128)
11129 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11131 if (VT.getSizeInBits() == 256)
11132 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11134 if (VT.getSizeInBits() == 512)
11135 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11138 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11139 llvm_unreachable("Unimplemented!");
11142 // This function assumes its argument is a BUILD_VECTOR of constants or
11143 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11145 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11146 unsigned &MaskValue) {
11148 unsigned NumElems = BuildVector->getNumOperands();
11150 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11151 // We don't handle the >2 lanes case right now.
11152 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11156 unsigned NumElemsInLane = NumElems / NumLanes;
11158 // Blend for v16i16 should be symmetric for the both lanes.
11159 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11160 SDValue EltCond = BuildVector->getOperand(i);
11161 SDValue SndLaneEltCond =
11162 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11164 int Lane1Cond = -1, Lane2Cond = -1;
11165 if (isa<ConstantSDNode>(EltCond))
11166 Lane1Cond = !isZero(EltCond);
11167 if (isa<ConstantSDNode>(SndLaneEltCond))
11168 Lane2Cond = !isZero(SndLaneEltCond);
11170 unsigned LaneMask = 0;
11171 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11172 // Lane1Cond != 0, means we want the first argument.
11173 // Lane1Cond == 0, means we want the second argument.
11174 // The encoding of this argument is 0 for the first argument, 1
11175 // for the second. Therefore, invert the condition.
11176 LaneMask = !Lane1Cond << i;
11177 else if (Lane1Cond < 0)
11178 LaneMask = !Lane2Cond << i;
11182 MaskValue |= LaneMask;
11184 MaskValue |= LaneMask << NumElemsInLane;
11189 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11190 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11191 const X86Subtarget *Subtarget,
11192 SelectionDAG &DAG) {
11193 SDValue Cond = Op.getOperand(0);
11194 SDValue LHS = Op.getOperand(1);
11195 SDValue RHS = Op.getOperand(2);
11197 MVT VT = Op.getSimpleValueType();
11199 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11201 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11203 // Only non-legal VSELECTs reach this lowering, convert those into generic
11204 // shuffles and re-use the shuffle lowering path for blends.
11205 SmallVector<int, 32> Mask;
11206 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11207 SDValue CondElt = CondBV->getOperand(i);
11209 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11211 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11214 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11215 // A vselect where all conditions and data are constants can be optimized into
11216 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11217 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11218 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11219 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11222 // Try to lower this to a blend-style vector shuffle. This can handle all
11223 // constant condition cases.
11224 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11227 // Variable blends are only legal from SSE4.1 onward.
11228 if (!Subtarget->hasSSE41())
11231 // Only some types will be legal on some subtargets. If we can emit a legal
11232 // VSELECT-matching blend, return Op, and but if we need to expand, return
11234 switch (Op.getSimpleValueType().SimpleTy) {
11236 // Most of the vector types have blends past SSE4.1.
11240 // The byte blends for AVX vectors were introduced only in AVX2.
11241 if (Subtarget->hasAVX2())
11248 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11249 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11252 // FIXME: We should custom lower this by fixing the condition and using i8
11258 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11259 MVT VT = Op.getSimpleValueType();
11262 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11265 if (VT.getSizeInBits() == 8) {
11266 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11267 Op.getOperand(0), Op.getOperand(1));
11268 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11269 DAG.getValueType(VT));
11270 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11273 if (VT.getSizeInBits() == 16) {
11274 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11275 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11277 return DAG.getNode(
11278 ISD::TRUNCATE, dl, MVT::i16,
11279 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11280 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11281 Op.getOperand(1)));
11282 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11283 Op.getOperand(0), Op.getOperand(1));
11284 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11285 DAG.getValueType(VT));
11286 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11289 if (VT == MVT::f32) {
11290 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11291 // the result back to FR32 register. It's only worth matching if the
11292 // result has a single use which is a store or a bitcast to i32. And in
11293 // the case of a store, it's not worth it if the index is a constant 0,
11294 // because a MOVSSmr can be used instead, which is smaller and faster.
11295 if (!Op.hasOneUse())
11297 SDNode *User = *Op.getNode()->use_begin();
11298 if ((User->getOpcode() != ISD::STORE ||
11299 (isa<ConstantSDNode>(Op.getOperand(1)) &&
11300 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11301 (User->getOpcode() != ISD::BITCAST ||
11302 User->getValueType(0) != MVT::i32))
11304 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11305 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11307 return DAG.getBitcast(MVT::f32, Extract);
11310 if (VT == MVT::i32 || VT == MVT::i64) {
11311 // ExtractPS/pextrq works with constant index.
11312 if (isa<ConstantSDNode>(Op.getOperand(1)))
11318 /// Extract one bit from mask vector, like v16i1 or v8i1.
11319 /// AVX-512 feature.
11321 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11322 SDValue Vec = Op.getOperand(0);
11324 MVT VecVT = Vec.getSimpleValueType();
11325 SDValue Idx = Op.getOperand(1);
11326 MVT EltVT = Op.getSimpleValueType();
11328 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11329 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11330 "Unexpected vector type in ExtractBitFromMaskVector");
11332 // variable index can't be handled in mask registers,
11333 // extend vector to VR512
11334 if (!isa<ConstantSDNode>(Idx)) {
11335 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11336 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11337 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11338 ExtVT.getVectorElementType(), Ext, Idx);
11339 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11342 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11343 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11344 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11345 rc = getRegClassFor(MVT::v16i1);
11346 unsigned MaxSift = rc->getSize()*8 - 1;
11347 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11348 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11349 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11350 DAG.getConstant(MaxSift, dl, MVT::i8));
11351 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11352 DAG.getIntPtrConstant(0, dl));
11356 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11357 SelectionDAG &DAG) const {
11359 SDValue Vec = Op.getOperand(0);
11360 MVT VecVT = Vec.getSimpleValueType();
11361 SDValue Idx = Op.getOperand(1);
11363 if (Op.getSimpleValueType() == MVT::i1)
11364 return ExtractBitFromMaskVector(Op, DAG);
11366 if (!isa<ConstantSDNode>(Idx)) {
11367 if (VecVT.is512BitVector() ||
11368 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11369 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11372 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11373 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11374 MaskEltVT.getSizeInBits());
11376 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11377 auto PtrVT = getPointerTy(DAG.getDataLayout());
11378 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11379 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11380 DAG.getConstant(0, dl, PtrVT));
11381 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11382 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11383 DAG.getConstant(0, dl, PtrVT));
11388 // If this is a 256-bit vector result, first extract the 128-bit vector and
11389 // then extract the element from the 128-bit vector.
11390 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11392 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11393 // Get the 128-bit vector.
11394 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11395 MVT EltVT = VecVT.getVectorElementType();
11397 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11399 //if (IdxVal >= NumElems/2)
11400 // IdxVal -= NumElems/2;
11401 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11402 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11403 DAG.getConstant(IdxVal, dl, MVT::i32));
11406 assert(VecVT.is128BitVector() && "Unexpected vector length");
11408 if (Subtarget->hasSSE41())
11409 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11412 MVT VT = Op.getSimpleValueType();
11413 // TODO: handle v16i8.
11414 if (VT.getSizeInBits() == 16) {
11415 SDValue Vec = Op.getOperand(0);
11416 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11418 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11419 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11420 DAG.getBitcast(MVT::v4i32, Vec),
11421 Op.getOperand(1)));
11422 // Transform it so it match pextrw which produces a 32-bit result.
11423 MVT EltVT = MVT::i32;
11424 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11425 Op.getOperand(0), Op.getOperand(1));
11426 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11427 DAG.getValueType(VT));
11428 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11431 if (VT.getSizeInBits() == 32) {
11432 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11436 // SHUFPS the element to the lowest double word, then movss.
11437 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11438 MVT VVT = Op.getOperand(0).getSimpleValueType();
11439 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11440 DAG.getUNDEF(VVT), Mask);
11441 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11442 DAG.getIntPtrConstant(0, dl));
11445 if (VT.getSizeInBits() == 64) {
11446 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11447 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11448 // to match extract_elt for f64.
11449 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11453 // UNPCKHPD the element to the lowest double word, then movsd.
11454 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11455 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11456 int Mask[2] = { 1, -1 };
11457 MVT VVT = Op.getOperand(0).getSimpleValueType();
11458 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11459 DAG.getUNDEF(VVT), Mask);
11460 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11461 DAG.getIntPtrConstant(0, dl));
11467 /// Insert one bit to mask vector, like v16i1 or v8i1.
11468 /// AVX-512 feature.
11470 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11472 SDValue Vec = Op.getOperand(0);
11473 SDValue Elt = Op.getOperand(1);
11474 SDValue Idx = Op.getOperand(2);
11475 MVT VecVT = Vec.getSimpleValueType();
11477 if (!isa<ConstantSDNode>(Idx)) {
11478 // Non constant index. Extend source and destination,
11479 // insert element and then truncate the result.
11480 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11481 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11482 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11483 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11484 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11485 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11488 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11489 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11491 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11492 DAG.getConstant(IdxVal, dl, MVT::i8));
11493 if (Vec.getOpcode() == ISD::UNDEF)
11495 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11498 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11499 SelectionDAG &DAG) const {
11500 MVT VT = Op.getSimpleValueType();
11501 MVT EltVT = VT.getVectorElementType();
11503 if (EltVT == MVT::i1)
11504 return InsertBitToMaskVector(Op, DAG);
11507 SDValue N0 = Op.getOperand(0);
11508 SDValue N1 = Op.getOperand(1);
11509 SDValue N2 = Op.getOperand(2);
11510 if (!isa<ConstantSDNode>(N2))
11512 auto *N2C = cast<ConstantSDNode>(N2);
11513 unsigned IdxVal = N2C->getZExtValue();
11515 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11516 // into that, and then insert the subvector back into the result.
11517 if (VT.is256BitVector() || VT.is512BitVector()) {
11518 // With a 256-bit vector, we can insert into the zero element efficiently
11519 // using a blend if we have AVX or AVX2 and the right data type.
11520 if (VT.is256BitVector() && IdxVal == 0) {
11521 // TODO: It is worthwhile to cast integer to floating point and back
11522 // and incur a domain crossing penalty if that's what we'll end up
11523 // doing anyway after extracting to a 128-bit vector.
11524 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11525 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11526 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11527 N2 = DAG.getIntPtrConstant(1, dl);
11528 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11532 // Get the desired 128-bit vector chunk.
11533 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11535 // Insert the element into the desired chunk.
11536 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11537 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11539 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11540 DAG.getConstant(IdxIn128, dl, MVT::i32));
11542 // Insert the changed part back into the bigger vector
11543 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11545 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11547 if (Subtarget->hasSSE41()) {
11548 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11550 if (VT == MVT::v8i16) {
11551 Opc = X86ISD::PINSRW;
11553 assert(VT == MVT::v16i8);
11554 Opc = X86ISD::PINSRB;
11557 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11559 if (N1.getValueType() != MVT::i32)
11560 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11561 if (N2.getValueType() != MVT::i32)
11562 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11563 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11566 if (EltVT == MVT::f32) {
11567 // Bits [7:6] of the constant are the source select. This will always be
11568 // zero here. The DAG Combiner may combine an extract_elt index into
11569 // these bits. For example (insert (extract, 3), 2) could be matched by
11570 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11571 // Bits [5:4] of the constant are the destination select. This is the
11572 // value of the incoming immediate.
11573 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11574 // combine either bitwise AND or insert of float 0.0 to set these bits.
11576 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11577 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11578 // If this is an insertion of 32-bits into the low 32-bits of
11579 // a vector, we prefer to generate a blend with immediate rather
11580 // than an insertps. Blends are simpler operations in hardware and so
11581 // will always have equal or better performance than insertps.
11582 // But if optimizing for size and there's a load folding opportunity,
11583 // generate insertps because blendps does not have a 32-bit memory
11585 N2 = DAG.getIntPtrConstant(1, dl);
11586 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11587 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11589 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11590 // Create this as a scalar to vector..
11591 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11592 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11595 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11596 // PINSR* works with constant index.
11601 if (EltVT == MVT::i8)
11604 if (EltVT.getSizeInBits() == 16) {
11605 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11606 // as its second argument.
11607 if (N1.getValueType() != MVT::i32)
11608 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11609 if (N2.getValueType() != MVT::i32)
11610 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11611 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11616 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11618 MVT OpVT = Op.getSimpleValueType();
11620 // If this is a 256-bit vector result, first insert into a 128-bit
11621 // vector and then insert into the 256-bit vector.
11622 if (!OpVT.is128BitVector()) {
11623 // Insert into a 128-bit vector.
11624 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11625 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11626 OpVT.getVectorNumElements() / SizeFactor);
11628 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11630 // Insert the 128-bit vector.
11631 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11634 if (OpVT == MVT::v1i64 &&
11635 Op.getOperand(0).getValueType() == MVT::i64)
11636 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11638 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11639 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11640 return DAG.getBitcast(
11641 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11644 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11645 // a simple subregister reference or explicit instructions to grab
11646 // upper bits of a vector.
11647 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11648 SelectionDAG &DAG) {
11650 SDValue In = Op.getOperand(0);
11651 SDValue Idx = Op.getOperand(1);
11652 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11653 MVT ResVT = Op.getSimpleValueType();
11654 MVT InVT = In.getSimpleValueType();
11656 if (Subtarget->hasFp256()) {
11657 if (ResVT.is128BitVector() &&
11658 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11659 isa<ConstantSDNode>(Idx)) {
11660 return Extract128BitVector(In, IdxVal, DAG, dl);
11662 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11663 isa<ConstantSDNode>(Idx)) {
11664 return Extract256BitVector(In, IdxVal, DAG, dl);
11670 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11671 // simple superregister reference or explicit instructions to insert
11672 // the upper bits of a vector.
11673 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11674 SelectionDAG &DAG) {
11675 if (!Subtarget->hasAVX())
11679 SDValue Vec = Op.getOperand(0);
11680 SDValue SubVec = Op.getOperand(1);
11681 SDValue Idx = Op.getOperand(2);
11683 if (!isa<ConstantSDNode>(Idx))
11686 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11687 MVT OpVT = Op.getSimpleValueType();
11688 MVT SubVecVT = SubVec.getSimpleValueType();
11690 // Fold two 16-byte subvector loads into one 32-byte load:
11691 // (insert_subvector (insert_subvector undef, (load addr), 0),
11692 // (load addr + 16), Elts/2)
11694 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11695 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11696 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11697 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11698 if (Idx2 && Idx2->getZExtValue() == 0) {
11699 SDValue SubVec2 = Vec.getOperand(1);
11700 // If needed, look through a bitcast to get to the load.
11701 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11702 SubVec2 = SubVec2.getOperand(0);
11704 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11706 unsigned Alignment = FirstLd->getAlignment();
11707 unsigned AS = FirstLd->getAddressSpace();
11708 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11709 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11710 OpVT, AS, Alignment, &Fast) && Fast) {
11711 SDValue Ops[] = { SubVec2, SubVec };
11712 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11719 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11720 SubVecVT.is128BitVector())
11721 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11723 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11724 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11726 if (OpVT.getVectorElementType() == MVT::i1) {
11727 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11729 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11730 SDValue Undef = DAG.getUNDEF(OpVT);
11731 unsigned NumElems = OpVT.getVectorNumElements();
11732 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11734 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11735 // Zero upper bits of the Vec
11736 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11737 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11739 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11741 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11742 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11745 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11747 // Zero upper bits of the Vec2
11748 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11749 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11750 // Zero lower bits of the Vec
11751 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11752 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11753 // Merge them together
11754 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11760 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11761 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11762 // one of the above mentioned nodes. It has to be wrapped because otherwise
11763 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11764 // be used to form addressing mode. These wrapped nodes will be selected
11767 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11768 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11770 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11771 // global base reg.
11772 unsigned char OpFlag = 0;
11773 unsigned WrapperKind = X86ISD::Wrapper;
11774 CodeModel::Model M = DAG.getTarget().getCodeModel();
11776 if (Subtarget->isPICStyleRIPRel() &&
11777 (M == CodeModel::Small || M == CodeModel::Kernel))
11778 WrapperKind = X86ISD::WrapperRIP;
11779 else if (Subtarget->isPICStyleGOT())
11780 OpFlag = X86II::MO_GOTOFF;
11781 else if (Subtarget->isPICStyleStubPIC())
11782 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11784 auto PtrVT = getPointerTy(DAG.getDataLayout());
11785 SDValue Result = DAG.getTargetConstantPool(
11786 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11788 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11789 // With PIC, the address is actually $g + Offset.
11792 DAG.getNode(ISD::ADD, DL, PtrVT,
11793 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11799 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11800 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11802 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11803 // global base reg.
11804 unsigned char OpFlag = 0;
11805 unsigned WrapperKind = X86ISD::Wrapper;
11806 CodeModel::Model M = DAG.getTarget().getCodeModel();
11808 if (Subtarget->isPICStyleRIPRel() &&
11809 (M == CodeModel::Small || M == CodeModel::Kernel))
11810 WrapperKind = X86ISD::WrapperRIP;
11811 else if (Subtarget->isPICStyleGOT())
11812 OpFlag = X86II::MO_GOTOFF;
11813 else if (Subtarget->isPICStyleStubPIC())
11814 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11816 auto PtrVT = getPointerTy(DAG.getDataLayout());
11817 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11819 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11821 // With PIC, the address is actually $g + Offset.
11824 DAG.getNode(ISD::ADD, DL, PtrVT,
11825 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11831 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11832 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11834 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11835 // global base reg.
11836 unsigned char OpFlag = 0;
11837 unsigned WrapperKind = X86ISD::Wrapper;
11838 CodeModel::Model M = DAG.getTarget().getCodeModel();
11840 if (Subtarget->isPICStyleRIPRel() &&
11841 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11842 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11843 OpFlag = X86II::MO_GOTPCREL;
11844 WrapperKind = X86ISD::WrapperRIP;
11845 } else if (Subtarget->isPICStyleGOT()) {
11846 OpFlag = X86II::MO_GOT;
11847 } else if (Subtarget->isPICStyleStubPIC()) {
11848 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11849 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11850 OpFlag = X86II::MO_DARWIN_NONLAZY;
11853 auto PtrVT = getPointerTy(DAG.getDataLayout());
11854 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11857 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11859 // With PIC, the address is actually $g + Offset.
11860 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11861 !Subtarget->is64Bit()) {
11863 DAG.getNode(ISD::ADD, DL, PtrVT,
11864 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11867 // For symbols that require a load from a stub to get the address, emit the
11869 if (isGlobalStubReference(OpFlag))
11870 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11871 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11872 false, false, false, 0);
11878 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11879 // Create the TargetBlockAddressAddress node.
11880 unsigned char OpFlags =
11881 Subtarget->ClassifyBlockAddressReference();
11882 CodeModel::Model M = DAG.getTarget().getCodeModel();
11883 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11884 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11886 auto PtrVT = getPointerTy(DAG.getDataLayout());
11887 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11889 if (Subtarget->isPICStyleRIPRel() &&
11890 (M == CodeModel::Small || M == CodeModel::Kernel))
11891 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11893 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11895 // With PIC, the address is actually $g + Offset.
11896 if (isGlobalRelativeToPICBase(OpFlags)) {
11897 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11898 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11905 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11906 int64_t Offset, SelectionDAG &DAG) const {
11907 // Create the TargetGlobalAddress node, folding in the constant
11908 // offset if it is legal.
11909 unsigned char OpFlags =
11910 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11911 CodeModel::Model M = DAG.getTarget().getCodeModel();
11912 auto PtrVT = getPointerTy(DAG.getDataLayout());
11914 if (OpFlags == X86II::MO_NO_FLAG &&
11915 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11916 // A direct static reference to a global.
11917 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11920 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11923 if (Subtarget->isPICStyleRIPRel() &&
11924 (M == CodeModel::Small || M == CodeModel::Kernel))
11925 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11927 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11929 // With PIC, the address is actually $g + Offset.
11930 if (isGlobalRelativeToPICBase(OpFlags)) {
11931 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11932 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11935 // For globals that require a load from a stub to get the address, emit the
11937 if (isGlobalStubReference(OpFlags))
11938 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11939 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11940 false, false, false, 0);
11942 // If there was a non-zero offset that we didn't fold, create an explicit
11943 // addition for it.
11945 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11946 DAG.getConstant(Offset, dl, PtrVT));
11952 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11953 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11954 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11955 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11959 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11960 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11961 unsigned char OperandFlags, bool LocalDynamic = false) {
11962 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11963 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11965 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11966 GA->getValueType(0),
11970 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11974 SDValue Ops[] = { Chain, TGA, *InFlag };
11975 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11977 SDValue Ops[] = { Chain, TGA };
11978 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11981 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11982 MFI->setAdjustsStack(true);
11983 MFI->setHasCalls(true);
11985 SDValue Flag = Chain.getValue(1);
11986 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11989 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11991 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11994 SDLoc dl(GA); // ? function entry point might be better
11995 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11996 DAG.getNode(X86ISD::GlobalBaseReg,
11997 SDLoc(), PtrVT), InFlag);
11998 InFlag = Chain.getValue(1);
12000 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12003 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12005 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12007 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12008 X86::RAX, X86II::MO_TLSGD);
12011 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12017 // Get the start address of the TLS block for this module.
12018 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12019 .getInfo<X86MachineFunctionInfo>();
12020 MFI->incNumLocalDynamicTLSAccesses();
12024 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12025 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12028 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12029 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12030 InFlag = Chain.getValue(1);
12031 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12032 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12035 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12039 unsigned char OperandFlags = X86II::MO_DTPOFF;
12040 unsigned WrapperKind = X86ISD::Wrapper;
12041 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12042 GA->getValueType(0),
12043 GA->getOffset(), OperandFlags);
12044 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12046 // Add x@dtpoff with the base.
12047 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12050 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12051 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12052 const EVT PtrVT, TLSModel::Model model,
12053 bool is64Bit, bool isPIC) {
12056 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12057 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12058 is64Bit ? 257 : 256));
12060 SDValue ThreadPointer =
12061 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12062 MachinePointerInfo(Ptr), false, false, false, 0);
12064 unsigned char OperandFlags = 0;
12065 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12067 unsigned WrapperKind = X86ISD::Wrapper;
12068 if (model == TLSModel::LocalExec) {
12069 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12070 } else if (model == TLSModel::InitialExec) {
12072 OperandFlags = X86II::MO_GOTTPOFF;
12073 WrapperKind = X86ISD::WrapperRIP;
12075 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12078 llvm_unreachable("Unexpected model");
12081 // emit "addl x@ntpoff,%eax" (local exec)
12082 // or "addl x@indntpoff,%eax" (initial exec)
12083 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12085 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12086 GA->getOffset(), OperandFlags);
12087 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12089 if (model == TLSModel::InitialExec) {
12090 if (isPIC && !is64Bit) {
12091 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12092 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12096 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12097 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12098 false, false, false, 0);
12101 // The address of the thread local variable is the add of the thread
12102 // pointer with the offset of the variable.
12103 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12107 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12109 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12110 const GlobalValue *GV = GA->getGlobal();
12111 auto PtrVT = getPointerTy(DAG.getDataLayout());
12113 if (Subtarget->isTargetELF()) {
12114 if (DAG.getTarget().Options.EmulatedTLS)
12115 return LowerToTLSEmulatedModel(GA, DAG);
12116 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12118 case TLSModel::GeneralDynamic:
12119 if (Subtarget->is64Bit())
12120 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12121 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12122 case TLSModel::LocalDynamic:
12123 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12124 Subtarget->is64Bit());
12125 case TLSModel::InitialExec:
12126 case TLSModel::LocalExec:
12127 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12128 DAG.getTarget().getRelocationModel() ==
12131 llvm_unreachable("Unknown TLS model.");
12134 if (Subtarget->isTargetDarwin()) {
12135 // Darwin only has one model of TLS. Lower to that.
12136 unsigned char OpFlag = 0;
12137 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12138 X86ISD::WrapperRIP : X86ISD::Wrapper;
12140 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12141 // global base reg.
12142 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12143 !Subtarget->is64Bit();
12145 OpFlag = X86II::MO_TLVP_PIC_BASE;
12147 OpFlag = X86II::MO_TLVP;
12149 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12150 GA->getValueType(0),
12151 GA->getOffset(), OpFlag);
12152 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12154 // With PIC32, the address is actually $g + Offset.
12156 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12157 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12160 // Lowering the machine isd will make sure everything is in the right
12162 SDValue Chain = DAG.getEntryNode();
12163 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12164 SDValue Args[] = { Chain, Offset };
12165 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12167 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12168 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12169 MFI->setAdjustsStack(true);
12171 // And our return value (tls address) is in the standard call return value
12173 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12174 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12177 if (Subtarget->isTargetKnownWindowsMSVC() ||
12178 Subtarget->isTargetWindowsGNU()) {
12179 // Just use the implicit TLS architecture
12180 // Need to generate someting similar to:
12181 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12183 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12184 // mov rcx, qword [rdx+rcx*8]
12185 // mov eax, .tls$:tlsvar
12186 // [rax+rcx] contains the address
12187 // Windows 64bit: gs:0x58
12188 // Windows 32bit: fs:__tls_array
12191 SDValue Chain = DAG.getEntryNode();
12193 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12194 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12195 // use its literal value of 0x2C.
12196 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12197 ? Type::getInt8PtrTy(*DAG.getContext(),
12199 : Type::getInt32PtrTy(*DAG.getContext(),
12202 SDValue TlsArray = Subtarget->is64Bit()
12203 ? DAG.getIntPtrConstant(0x58, dl)
12204 : (Subtarget->isTargetWindowsGNU()
12205 ? DAG.getIntPtrConstant(0x2C, dl)
12206 : DAG.getExternalSymbol("_tls_array", PtrVT));
12208 SDValue ThreadPointer =
12209 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12213 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12214 res = ThreadPointer;
12216 // Load the _tls_index variable
12217 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12218 if (Subtarget->is64Bit())
12219 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12220 MachinePointerInfo(), MVT::i32, false, false,
12223 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12226 auto &DL = DAG.getDataLayout();
12228 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12229 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12231 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12234 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12237 // Get the offset of start of .tls section
12238 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12239 GA->getValueType(0),
12240 GA->getOffset(), X86II::MO_SECREL);
12241 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12243 // The address of the thread local variable is the add of the thread
12244 // pointer with the offset of the variable.
12245 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12248 llvm_unreachable("TLS not implemented for this target.");
12251 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12252 /// and take a 2 x i32 value to shift plus a shift amount.
12253 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12254 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12255 MVT VT = Op.getSimpleValueType();
12256 unsigned VTBits = VT.getSizeInBits();
12258 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12259 SDValue ShOpLo = Op.getOperand(0);
12260 SDValue ShOpHi = Op.getOperand(1);
12261 SDValue ShAmt = Op.getOperand(2);
12262 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12263 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12265 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12266 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12267 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12268 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12269 : DAG.getConstant(0, dl, VT);
12271 SDValue Tmp2, Tmp3;
12272 if (Op.getOpcode() == ISD::SHL_PARTS) {
12273 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12274 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12276 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12277 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12280 // If the shift amount is larger or equal than the width of a part we can't
12281 // rely on the results of shld/shrd. Insert a test and select the appropriate
12282 // values for large shift amounts.
12283 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12284 DAG.getConstant(VTBits, dl, MVT::i8));
12285 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12286 AndNode, DAG.getConstant(0, dl, MVT::i8));
12289 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12290 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12291 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12293 if (Op.getOpcode() == ISD::SHL_PARTS) {
12294 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12295 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12297 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12298 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12301 SDValue Ops[2] = { Lo, Hi };
12302 return DAG.getMergeValues(Ops, dl);
12305 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12306 SelectionDAG &DAG) const {
12307 SDValue Src = Op.getOperand(0);
12308 MVT SrcVT = Src.getSimpleValueType();
12309 MVT VT = Op.getSimpleValueType();
12312 if (SrcVT.isVector()) {
12313 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12314 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12315 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12316 DAG.getUNDEF(SrcVT)));
12318 if (SrcVT.getVectorElementType() == MVT::i1) {
12319 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12320 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12321 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12326 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12327 "Unknown SINT_TO_FP to lower!");
12329 // These are really Legal; return the operand so the caller accepts it as
12331 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12333 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12334 Subtarget->is64Bit()) {
12338 unsigned Size = SrcVT.getSizeInBits()/8;
12339 MachineFunction &MF = DAG.getMachineFunction();
12340 auto PtrVT = getPointerTy(MF.getDataLayout());
12341 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12342 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12343 SDValue Chain = DAG.getStore(
12344 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12345 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12347 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12350 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12352 SelectionDAG &DAG) const {
12356 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12358 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12360 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12362 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12364 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12365 MachineMemOperand *MMO;
12367 int SSFI = FI->getIndex();
12368 MMO = DAG.getMachineFunction().getMachineMemOperand(
12369 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12370 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12372 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12373 StackSlot = StackSlot.getOperand(1);
12375 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12376 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12378 Tys, Ops, SrcVT, MMO);
12381 Chain = Result.getValue(1);
12382 SDValue InFlag = Result.getValue(2);
12384 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12385 // shouldn't be necessary except that RFP cannot be live across
12386 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12387 MachineFunction &MF = DAG.getMachineFunction();
12388 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12389 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12390 auto PtrVT = getPointerTy(MF.getDataLayout());
12391 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12392 Tys = DAG.getVTList(MVT::Other);
12394 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12396 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12397 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12398 MachineMemOperand::MOStore, SSFISize, SSFISize);
12400 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12401 Ops, Op.getValueType(), MMO);
12402 Result = DAG.getLoad(
12403 Op.getValueType(), DL, Chain, StackSlot,
12404 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12405 false, false, false, 0);
12411 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12412 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12413 SelectionDAG &DAG) const {
12414 // This algorithm is not obvious. Here it is what we're trying to output:
12417 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12418 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12420 haddpd %xmm0, %xmm0
12422 pshufd $0x4e, %xmm0, %xmm1
12428 LLVMContext *Context = DAG.getContext();
12430 // Build some magic constants.
12431 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12432 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12433 auto PtrVT = getPointerTy(DAG.getDataLayout());
12434 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12436 SmallVector<Constant*,2> CV1;
12438 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12439 APInt(64, 0x4330000000000000ULL))));
12441 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12442 APInt(64, 0x4530000000000000ULL))));
12443 Constant *C1 = ConstantVector::get(CV1);
12444 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12446 // Load the 64-bit value into an XMM register.
12447 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12450 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12451 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12452 false, false, false, 16);
12454 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12457 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12458 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12459 false, false, false, 16);
12460 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12461 // TODO: Are there any fast-math-flags to propagate here?
12462 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12465 if (Subtarget->hasSSE3()) {
12466 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12467 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12469 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12470 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12472 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12473 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12476 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12477 DAG.getIntPtrConstant(0, dl));
12480 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12481 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12482 SelectionDAG &DAG) const {
12484 // FP constant to bias correct the final result.
12485 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12488 // Load the 32-bit value into an XMM register.
12489 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12492 // Zero out the upper parts of the register.
12493 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12495 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12496 DAG.getBitcast(MVT::v2f64, Load),
12497 DAG.getIntPtrConstant(0, dl));
12499 // Or the load with the bias.
12500 SDValue Or = DAG.getNode(
12501 ISD::OR, dl, MVT::v2i64,
12502 DAG.getBitcast(MVT::v2i64,
12503 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12504 DAG.getBitcast(MVT::v2i64,
12505 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12507 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12508 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12510 // Subtract the bias.
12511 // TODO: Are there any fast-math-flags to propagate here?
12512 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12514 // Handle final rounding.
12515 EVT DestVT = Op.getValueType();
12517 if (DestVT.bitsLT(MVT::f64))
12518 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12519 DAG.getIntPtrConstant(0, dl));
12520 if (DestVT.bitsGT(MVT::f64))
12521 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12523 // Handle final rounding.
12527 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12528 const X86Subtarget &Subtarget) {
12529 // The algorithm is the following:
12530 // #ifdef __SSE4_1__
12531 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12532 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12533 // (uint4) 0x53000000, 0xaa);
12535 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12536 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12538 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12539 // return (float4) lo + fhi;
12541 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12542 // reassociate the two FADDs, and if we do that, the algorithm fails
12543 // spectacularly (PR24512).
12544 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12545 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12546 // there's also the MachineCombiner reassociations happening on Machine IR.
12547 if (DAG.getTarget().Options.UnsafeFPMath)
12551 SDValue V = Op->getOperand(0);
12552 EVT VecIntVT = V.getValueType();
12553 bool Is128 = VecIntVT == MVT::v4i32;
12554 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12555 // If we convert to something else than the supported type, e.g., to v4f64,
12557 if (VecFloatVT != Op->getValueType(0))
12560 unsigned NumElts = VecIntVT.getVectorNumElements();
12561 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12562 "Unsupported custom type");
12563 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12565 // In the #idef/#else code, we have in common:
12566 // - The vector of constants:
12572 // Create the splat vector for 0x4b000000.
12573 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12574 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12575 CstLow, CstLow, CstLow, CstLow};
12576 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12577 makeArrayRef(&CstLowArray[0], NumElts));
12578 // Create the splat vector for 0x53000000.
12579 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12580 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12581 CstHigh, CstHigh, CstHigh, CstHigh};
12582 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12583 makeArrayRef(&CstHighArray[0], NumElts));
12585 // Create the right shift.
12586 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12587 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12588 CstShift, CstShift, CstShift, CstShift};
12589 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12590 makeArrayRef(&CstShiftArray[0], NumElts));
12591 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12594 if (Subtarget.hasSSE41()) {
12595 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12596 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12597 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12598 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12599 // Low will be bitcasted right away, so do not bother bitcasting back to its
12601 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12602 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12603 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12604 // (uint4) 0x53000000, 0xaa);
12605 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12606 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12607 // High will be bitcasted right away, so do not bother bitcasting back to
12608 // its original type.
12609 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12610 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12612 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12613 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12614 CstMask, CstMask, CstMask);
12615 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12616 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12617 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12619 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12620 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12623 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12624 SDValue CstFAdd = DAG.getConstantFP(
12625 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12626 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12627 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12628 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12629 makeArrayRef(&CstFAddArray[0], NumElts));
12631 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12632 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12633 // TODO: Are there any fast-math-flags to propagate here?
12635 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12636 // return (float4) lo + fhi;
12637 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12638 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12641 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12642 SelectionDAG &DAG) const {
12643 SDValue N0 = Op.getOperand(0);
12644 MVT SVT = N0.getSimpleValueType();
12647 switch (SVT.SimpleTy) {
12649 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12654 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12655 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12656 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12660 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12663 if (Subtarget->hasAVX512())
12664 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12665 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12667 llvm_unreachable(nullptr);
12670 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12671 SelectionDAG &DAG) const {
12672 SDValue N0 = Op.getOperand(0);
12674 auto PtrVT = getPointerTy(DAG.getDataLayout());
12676 if (Op.getValueType().isVector())
12677 return lowerUINT_TO_FP_vec(Op, DAG);
12679 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12680 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12681 // the optimization here.
12682 if (DAG.SignBitIsZero(N0))
12683 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12685 MVT SrcVT = N0.getSimpleValueType();
12686 MVT DstVT = Op.getSimpleValueType();
12688 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12689 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12690 // Conversions from unsigned i32 to f32/f64 are legal,
12691 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
12695 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12696 return LowerUINT_TO_FP_i64(Op, DAG);
12697 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12698 return LowerUINT_TO_FP_i32(Op, DAG);
12699 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12702 // Make a 64-bit buffer, and use it to build an FILD.
12703 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12704 if (SrcVT == MVT::i32) {
12705 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12706 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12707 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12708 StackSlot, MachinePointerInfo(),
12710 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12711 OffsetSlot, MachinePointerInfo(),
12713 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12717 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12718 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12719 StackSlot, MachinePointerInfo(),
12721 // For i64 source, we need to add the appropriate power of 2 if the input
12722 // was negative. This is the same as the optimization in
12723 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12724 // we must be careful to do the computation in x87 extended precision, not
12725 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12726 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12727 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12728 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12729 MachineMemOperand::MOLoad, 8, 8);
12731 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12732 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12733 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12736 APInt FF(32, 0x5F800000ULL);
12738 // Check whether the sign bit is set.
12739 SDValue SignSet = DAG.getSetCC(
12740 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12741 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12743 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12744 SDValue FudgePtr = DAG.getConstantPool(
12745 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12747 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12748 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12749 SDValue Four = DAG.getIntPtrConstant(4, dl);
12750 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12752 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12754 // Load the value out, extending it from f32 to f80.
12755 // FIXME: Avoid the extend by constructing the right constant pool?
12756 SDValue Fudge = DAG.getExtLoad(
12757 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12758 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12759 false, false, false, 4);
12760 // Extend everything to 80 bits to force it to be done on x87.
12761 // TODO: Are there any fast-math-flags to propagate here?
12762 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12763 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12764 DAG.getIntPtrConstant(0, dl));
12767 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12768 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12769 // just return an <SDValue(), SDValue()> pair.
12770 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12771 // to i16, i32 or i64, and we lower it to a legal sequence.
12772 // If lowered to the final integer result we return a <result, SDValue()> pair.
12773 // Otherwise we lower it to a sequence ending with a FIST, return a
12774 // <FIST, StackSlot> pair, and the caller is responsible for loading
12775 // the final integer result from StackSlot.
12776 std::pair<SDValue,SDValue>
12777 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12778 bool IsSigned, bool IsReplace) const {
12781 EVT DstTy = Op.getValueType();
12782 EVT TheVT = Op.getOperand(0).getValueType();
12783 auto PtrVT = getPointerTy(DAG.getDataLayout());
12785 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12786 // f16 must be promoted before using the lowering in this routine.
12787 // fp128 does not use this lowering.
12788 return std::make_pair(SDValue(), SDValue());
12791 // If using FIST to compute an unsigned i64, we'll need some fixup
12792 // to handle values above the maximum signed i64. A FIST is always
12793 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12794 bool UnsignedFixup = !IsSigned &&
12795 DstTy == MVT::i64 &&
12796 (!Subtarget->is64Bit() ||
12797 !isScalarFPTypeInSSEReg(TheVT));
12799 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12800 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12801 // The low 32 bits of the fist result will have the correct uint32 result.
12802 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12806 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12807 DstTy.getSimpleVT() >= MVT::i16 &&
12808 "Unknown FP_TO_INT to lower!");
12810 // These are really Legal.
12811 if (DstTy == MVT::i32 &&
12812 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12813 return std::make_pair(SDValue(), SDValue());
12814 if (Subtarget->is64Bit() &&
12815 DstTy == MVT::i64 &&
12816 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12817 return std::make_pair(SDValue(), SDValue());
12819 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12821 MachineFunction &MF = DAG.getMachineFunction();
12822 unsigned MemSize = DstTy.getSizeInBits()/8;
12823 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12824 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12827 switch (DstTy.getSimpleVT().SimpleTy) {
12828 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12829 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12830 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12831 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12834 SDValue Chain = DAG.getEntryNode();
12835 SDValue Value = Op.getOperand(0);
12836 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12838 if (UnsignedFixup) {
12840 // Conversion to unsigned i64 is implemented with a select,
12841 // depending on whether the source value fits in the range
12842 // of a signed i64. Let Thresh be the FP equivalent of
12843 // 0x8000000000000000ULL.
12845 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12846 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12847 // Fist-to-mem64 FistSrc
12848 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12849 // to XOR'ing the high 32 bits with Adjust.
12851 // Being a power of 2, Thresh is exactly representable in all FP formats.
12852 // For X87 we'd like to use the smallest FP type for this constant, but
12853 // for DAG type consistency we have to match the FP operand type.
12855 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12856 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12857 bool LosesInfo = false;
12858 if (TheVT == MVT::f64)
12859 // The rounding mode is irrelevant as the conversion should be exact.
12860 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12862 else if (TheVT == MVT::f80)
12863 Status = Thresh.convert(APFloat::x87DoubleExtended,
12864 APFloat::rmNearestTiesToEven, &LosesInfo);
12866 assert(Status == APFloat::opOK && !LosesInfo &&
12867 "FP conversion should have been exact");
12869 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12871 SDValue Cmp = DAG.getSetCC(DL,
12872 getSetCCResultType(DAG.getDataLayout(),
12873 *DAG.getContext(), TheVT),
12874 Value, ThreshVal, ISD::SETLT);
12875 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12876 DAG.getConstant(0, DL, MVT::i32),
12877 DAG.getConstant(0x80000000, DL, MVT::i32));
12878 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12879 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12880 *DAG.getContext(), TheVT),
12881 Value, ThreshVal, ISD::SETLT);
12882 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12885 // FIXME This causes a redundant load/store if the SSE-class value is already
12886 // in memory, such as if it is on the callstack.
12887 if (isScalarFPTypeInSSEReg(TheVT)) {
12888 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12889 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12890 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12892 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12894 Chain, StackSlot, DAG.getValueType(TheVT)
12897 MachineMemOperand *MMO =
12898 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12899 MachineMemOperand::MOLoad, MemSize, MemSize);
12900 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12901 Chain = Value.getValue(1);
12902 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12903 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12906 MachineMemOperand *MMO =
12907 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12908 MachineMemOperand::MOStore, MemSize, MemSize);
12910 if (UnsignedFixup) {
12912 // Insert the FIST, load its result as two i32's,
12913 // and XOR the high i32 with Adjust.
12915 SDValue FistOps[] = { Chain, Value, StackSlot };
12916 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12917 FistOps, DstTy, MMO);
12919 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12920 MachinePointerInfo(),
12921 false, false, false, 0);
12922 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12923 DAG.getConstant(4, DL, PtrVT));
12925 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12926 MachinePointerInfo(),
12927 false, false, false, 0);
12928 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12930 if (Subtarget->is64Bit()) {
12931 // Join High32 and Low32 into a 64-bit result.
12932 // (High32 << 32) | Low32
12933 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12934 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12935 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12936 DAG.getConstant(32, DL, MVT::i8));
12937 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12938 return std::make_pair(Result, SDValue());
12941 SDValue ResultOps[] = { Low32, High32 };
12943 SDValue pair = IsReplace
12944 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12945 : DAG.getMergeValues(ResultOps, DL);
12946 return std::make_pair(pair, SDValue());
12948 // Build the FP_TO_INT*_IN_MEM
12949 SDValue Ops[] = { Chain, Value, StackSlot };
12950 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12952 return std::make_pair(FIST, StackSlot);
12956 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12957 const X86Subtarget *Subtarget) {
12958 MVT VT = Op->getSimpleValueType(0);
12959 SDValue In = Op->getOperand(0);
12960 MVT InVT = In.getSimpleValueType();
12963 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12964 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12966 // Optimize vectors in AVX mode:
12969 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12970 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12971 // Concat upper and lower parts.
12974 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12975 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12976 // Concat upper and lower parts.
12979 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12980 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12981 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12984 if (Subtarget->hasInt256())
12985 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12987 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12988 SDValue Undef = DAG.getUNDEF(InVT);
12989 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12990 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12991 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12993 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12994 VT.getVectorNumElements()/2);
12996 OpLo = DAG.getBitcast(HVT, OpLo);
12997 OpHi = DAG.getBitcast(HVT, OpHi);
12999 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13002 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13003 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13004 MVT VT = Op->getSimpleValueType(0);
13005 SDValue In = Op->getOperand(0);
13006 MVT InVT = In.getSimpleValueType();
13008 unsigned int NumElts = VT.getVectorNumElements();
13009 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13012 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13013 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13015 assert(InVT.getVectorElementType() == MVT::i1);
13016 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13018 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13020 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13022 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13023 if (VT.is512BitVector())
13025 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13028 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13029 SelectionDAG &DAG) {
13030 if (Subtarget->hasFp256())
13031 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13037 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13038 SelectionDAG &DAG) {
13040 MVT VT = Op.getSimpleValueType();
13041 SDValue In = Op.getOperand(0);
13042 MVT SVT = In.getSimpleValueType();
13044 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13045 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13047 if (Subtarget->hasFp256())
13048 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13051 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13052 VT.getVectorNumElements() != SVT.getVectorNumElements());
13056 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13058 MVT VT = Op.getSimpleValueType();
13059 SDValue In = Op.getOperand(0);
13060 MVT InVT = In.getSimpleValueType();
13062 if (VT == MVT::i1) {
13063 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13064 "Invalid scalar TRUNCATE operation");
13065 if (InVT.getSizeInBits() >= 32)
13067 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13068 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13070 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13071 "Invalid TRUNCATE operation");
13073 // move vector to mask - truncate solution for SKX
13074 if (VT.getVectorElementType() == MVT::i1) {
13075 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13076 Subtarget->hasBWI())
13077 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13078 if ((InVT.is256BitVector() || InVT.is128BitVector())
13079 && InVT.getScalarSizeInBits() <= 16 &&
13080 Subtarget->hasBWI() && Subtarget->hasVLX())
13081 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13082 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13083 Subtarget->hasDQI())
13084 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13085 if ((InVT.is256BitVector() || InVT.is128BitVector())
13086 && InVT.getScalarSizeInBits() >= 32 &&
13087 Subtarget->hasDQI() && Subtarget->hasVLX())
13088 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13091 if (VT.getVectorElementType() == MVT::i1) {
13092 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13093 unsigned NumElts = InVT.getVectorNumElements();
13094 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13095 if (InVT.getSizeInBits() < 512) {
13096 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13097 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13102 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13103 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13104 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13107 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13108 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13109 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13110 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13112 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13113 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13114 if (Subtarget->hasInt256()) {
13115 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13116 In = DAG.getBitcast(MVT::v8i32, In);
13117 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13119 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13120 DAG.getIntPtrConstant(0, DL));
13123 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13124 DAG.getIntPtrConstant(0, DL));
13125 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13126 DAG.getIntPtrConstant(2, DL));
13127 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13128 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13129 static const int ShufMask[] = {0, 2, 4, 6};
13130 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13133 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13134 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13135 if (Subtarget->hasInt256()) {
13136 In = DAG.getBitcast(MVT::v32i8, In);
13138 SmallVector<SDValue,32> pshufbMask;
13139 for (unsigned i = 0; i < 2; ++i) {
13140 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13141 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13142 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13143 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13144 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13145 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13146 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13147 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13148 for (unsigned j = 0; j < 8; ++j)
13149 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13151 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13152 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13153 In = DAG.getBitcast(MVT::v4i64, In);
13155 static const int ShufMask[] = {0, 2, -1, -1};
13156 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13158 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13159 DAG.getIntPtrConstant(0, DL));
13160 return DAG.getBitcast(VT, In);
13163 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13164 DAG.getIntPtrConstant(0, DL));
13166 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13167 DAG.getIntPtrConstant(4, DL));
13169 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13170 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13172 // The PSHUFB mask:
13173 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13174 -1, -1, -1, -1, -1, -1, -1, -1};
13176 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13177 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13178 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13180 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13181 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13183 // The MOVLHPS Mask:
13184 static const int ShufMask2[] = {0, 1, 4, 5};
13185 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13186 return DAG.getBitcast(MVT::v8i16, res);
13189 // Handle truncation of V256 to V128 using shuffles.
13190 if (!VT.is128BitVector() || !InVT.is256BitVector())
13193 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13195 unsigned NumElems = VT.getVectorNumElements();
13196 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13198 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13199 // Prepare truncation shuffle mask
13200 for (unsigned i = 0; i != NumElems; ++i)
13201 MaskVec[i] = i * 2;
13202 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13203 DAG.getUNDEF(NVT), &MaskVec[0]);
13204 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13205 DAG.getIntPtrConstant(0, DL));
13208 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13209 SelectionDAG &DAG) const {
13210 assert(!Op.getSimpleValueType().isVector());
13212 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13213 /*IsSigned=*/ true, /*IsReplace=*/ false);
13214 SDValue FIST = Vals.first, StackSlot = Vals.second;
13215 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13216 if (!FIST.getNode())
13219 if (StackSlot.getNode())
13220 // Load the result.
13221 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13222 FIST, StackSlot, MachinePointerInfo(),
13223 false, false, false, 0);
13225 // The node is the result.
13229 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13230 SelectionDAG &DAG) const {
13231 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13232 /*IsSigned=*/ false, /*IsReplace=*/ false);
13233 SDValue FIST = Vals.first, StackSlot = Vals.second;
13234 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13235 if (!FIST.getNode())
13238 if (StackSlot.getNode())
13239 // Load the result.
13240 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13241 FIST, StackSlot, MachinePointerInfo(),
13242 false, false, false, 0);
13244 // The node is the result.
13248 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13250 MVT VT = Op.getSimpleValueType();
13251 SDValue In = Op.getOperand(0);
13252 MVT SVT = In.getSimpleValueType();
13254 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13256 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13257 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13258 In, DAG.getUNDEF(SVT)));
13261 /// The only differences between FABS and FNEG are the mask and the logic op.
13262 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13263 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13264 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13265 "Wrong opcode for lowering FABS or FNEG.");
13267 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13269 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13270 // into an FNABS. We'll lower the FABS after that if it is still in use.
13272 for (SDNode *User : Op->uses())
13273 if (User->getOpcode() == ISD::FNEG)
13277 MVT VT = Op.getSimpleValueType();
13279 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13280 // decide if we should generate a 16-byte constant mask when we only need 4 or
13281 // 8 bytes for the scalar case.
13287 if (VT.isVector()) {
13289 EltVT = VT.getVectorElementType();
13290 NumElts = VT.getVectorNumElements();
13292 // There are no scalar bitwise logical SSE/AVX instructions, so we
13293 // generate a 16-byte vector constant and logic op even for the scalar case.
13294 // Using a 16-byte mask allows folding the load of the mask with
13295 // the logic op, so it can save (~4 bytes) on code size.
13296 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13298 NumElts = (VT == MVT::f64) ? 2 : 4;
13301 unsigned EltBits = EltVT.getSizeInBits();
13302 LLVMContext *Context = DAG.getContext();
13303 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13305 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13306 Constant *C = ConstantInt::get(*Context, MaskElt);
13307 C = ConstantVector::getSplat(NumElts, C);
13308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13309 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13310 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13312 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13313 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13314 false, false, false, Alignment);
13316 SDValue Op0 = Op.getOperand(0);
13317 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13319 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13320 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13323 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13325 // For the scalar case extend to a 128-bit vector, perform the logic op,
13326 // and extract the scalar result back out.
13327 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13328 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13329 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13330 DAG.getIntPtrConstant(0, dl));
13333 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13335 LLVMContext *Context = DAG.getContext();
13336 SDValue Op0 = Op.getOperand(0);
13337 SDValue Op1 = Op.getOperand(1);
13339 MVT VT = Op.getSimpleValueType();
13340 MVT SrcVT = Op1.getSimpleValueType();
13342 // If second operand is smaller, extend it first.
13343 if (SrcVT.bitsLT(VT)) {
13344 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13347 // And if it is bigger, shrink it first.
13348 if (SrcVT.bitsGT(VT)) {
13349 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13353 // At this point the operands and the result should have the same
13354 // type, and that won't be f80 since that is not custom lowered.
13356 const fltSemantics &Sem =
13357 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13358 const unsigned SizeInBits = VT.getSizeInBits();
13360 SmallVector<Constant *, 4> CV(
13361 VT == MVT::f64 ? 2 : 4,
13362 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13364 // First, clear all bits but the sign bit from the second operand (sign).
13365 CV[0] = ConstantFP::get(*Context,
13366 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13367 Constant *C = ConstantVector::get(CV);
13368 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13369 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13371 // Perform all logic operations as 16-byte vectors because there are no
13372 // scalar FP logic instructions in SSE. This allows load folding of the
13373 // constants into the logic instructions.
13374 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13376 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13377 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13378 false, false, false, 16);
13379 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13380 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13382 // Next, clear the sign bit from the first operand (magnitude).
13383 // If it's a constant, we can clear it here.
13384 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13385 APFloat APF = Op0CN->getValueAPF();
13386 // If the magnitude is a positive zero, the sign bit alone is enough.
13387 if (APF.isPosZero())
13388 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13389 DAG.getIntPtrConstant(0, dl));
13391 CV[0] = ConstantFP::get(*Context, APF);
13393 CV[0] = ConstantFP::get(
13395 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13397 C = ConstantVector::get(CV);
13398 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13400 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13401 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13402 false, false, false, 16);
13403 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13404 if (!isa<ConstantFPSDNode>(Op0)) {
13405 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13406 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13408 // OR the magnitude value with the sign bit.
13409 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13410 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13411 DAG.getIntPtrConstant(0, dl));
13414 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13415 SDValue N0 = Op.getOperand(0);
13417 MVT VT = Op.getSimpleValueType();
13419 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13420 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13421 DAG.getConstant(1, dl, VT));
13422 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13425 // Check whether an OR'd tree is PTEST-able.
13426 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13427 SelectionDAG &DAG) {
13428 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13430 if (!Subtarget->hasSSE41())
13433 if (!Op->hasOneUse())
13436 SDNode *N = Op.getNode();
13439 SmallVector<SDValue, 8> Opnds;
13440 DenseMap<SDValue, unsigned> VecInMap;
13441 SmallVector<SDValue, 8> VecIns;
13442 EVT VT = MVT::Other;
13444 // Recognize a special case where a vector is casted into wide integer to
13446 Opnds.push_back(N->getOperand(0));
13447 Opnds.push_back(N->getOperand(1));
13449 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13450 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13451 // BFS traverse all OR'd operands.
13452 if (I->getOpcode() == ISD::OR) {
13453 Opnds.push_back(I->getOperand(0));
13454 Opnds.push_back(I->getOperand(1));
13455 // Re-evaluate the number of nodes to be traversed.
13456 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13460 // Quit if a non-EXTRACT_VECTOR_ELT
13461 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13464 // Quit if without a constant index.
13465 SDValue Idx = I->getOperand(1);
13466 if (!isa<ConstantSDNode>(Idx))
13469 SDValue ExtractedFromVec = I->getOperand(0);
13470 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13471 if (M == VecInMap.end()) {
13472 VT = ExtractedFromVec.getValueType();
13473 // Quit if not 128/256-bit vector.
13474 if (!VT.is128BitVector() && !VT.is256BitVector())
13476 // Quit if not the same type.
13477 if (VecInMap.begin() != VecInMap.end() &&
13478 VT != VecInMap.begin()->first.getValueType())
13480 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13481 VecIns.push_back(ExtractedFromVec);
13483 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13486 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13487 "Not extracted from 128-/256-bit vector.");
13489 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13491 for (DenseMap<SDValue, unsigned>::const_iterator
13492 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13493 // Quit if not all elements are used.
13494 if (I->second != FullMask)
13498 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13500 // Cast all vectors into TestVT for PTEST.
13501 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13502 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13504 // If more than one full vectors are evaluated, OR them first before PTEST.
13505 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13506 // Each iteration will OR 2 nodes and append the result until there is only
13507 // 1 node left, i.e. the final OR'd value of all vectors.
13508 SDValue LHS = VecIns[Slot];
13509 SDValue RHS = VecIns[Slot + 1];
13510 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13513 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13514 VecIns.back(), VecIns.back());
13517 /// \brief return true if \c Op has a use that doesn't just read flags.
13518 static bool hasNonFlagsUse(SDValue Op) {
13519 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13521 SDNode *User = *UI;
13522 unsigned UOpNo = UI.getOperandNo();
13523 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13524 // Look pass truncate.
13525 UOpNo = User->use_begin().getOperandNo();
13526 User = *User->use_begin();
13529 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13530 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13536 /// Emit nodes that will be selected as "test Op0,Op0", or something
13538 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13539 SelectionDAG &DAG) const {
13540 if (Op.getValueType() == MVT::i1) {
13541 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13542 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13543 DAG.getConstant(0, dl, MVT::i8));
13545 // CF and OF aren't always set the way we want. Determine which
13546 // of these we need.
13547 bool NeedCF = false;
13548 bool NeedOF = false;
13551 case X86::COND_A: case X86::COND_AE:
13552 case X86::COND_B: case X86::COND_BE:
13555 case X86::COND_G: case X86::COND_GE:
13556 case X86::COND_L: case X86::COND_LE:
13557 case X86::COND_O: case X86::COND_NO: {
13558 // Check if we really need to set the
13559 // Overflow flag. If NoSignedWrap is present
13560 // that is not actually needed.
13561 switch (Op->getOpcode()) {
13566 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13567 if (BinNode->Flags.hasNoSignedWrap())
13577 // See if we can use the EFLAGS value from the operand instead of
13578 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13579 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13580 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13581 // Emit a CMP with 0, which is the TEST pattern.
13582 //if (Op.getValueType() == MVT::i1)
13583 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13584 // DAG.getConstant(0, MVT::i1));
13585 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13586 DAG.getConstant(0, dl, Op.getValueType()));
13588 unsigned Opcode = 0;
13589 unsigned NumOperands = 0;
13591 // Truncate operations may prevent the merge of the SETCC instruction
13592 // and the arithmetic instruction before it. Attempt to truncate the operands
13593 // of the arithmetic instruction and use a reduced bit-width instruction.
13594 bool NeedTruncation = false;
13595 SDValue ArithOp = Op;
13596 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13597 SDValue Arith = Op->getOperand(0);
13598 // Both the trunc and the arithmetic op need to have one user each.
13599 if (Arith->hasOneUse())
13600 switch (Arith.getOpcode()) {
13607 NeedTruncation = true;
13613 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13614 // which may be the result of a CAST. We use the variable 'Op', which is the
13615 // non-casted variable when we check for possible users.
13616 switch (ArithOp.getOpcode()) {
13618 // Due to an isel shortcoming, be conservative if this add is likely to be
13619 // selected as part of a load-modify-store instruction. When the root node
13620 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13621 // uses of other nodes in the match, such as the ADD in this case. This
13622 // leads to the ADD being left around and reselected, with the result being
13623 // two adds in the output. Alas, even if none our users are stores, that
13624 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13625 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13626 // climbing the DAG back to the root, and it doesn't seem to be worth the
13628 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13629 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13630 if (UI->getOpcode() != ISD::CopyToReg &&
13631 UI->getOpcode() != ISD::SETCC &&
13632 UI->getOpcode() != ISD::STORE)
13635 if (ConstantSDNode *C =
13636 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13637 // An add of one will be selected as an INC.
13638 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13639 Opcode = X86ISD::INC;
13644 // An add of negative one (subtract of one) will be selected as a DEC.
13645 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13646 Opcode = X86ISD::DEC;
13652 // Otherwise use a regular EFLAGS-setting add.
13653 Opcode = X86ISD::ADD;
13658 // If we have a constant logical shift that's only used in a comparison
13659 // against zero turn it into an equivalent AND. This allows turning it into
13660 // a TEST instruction later.
13661 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13662 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13663 EVT VT = Op.getValueType();
13664 unsigned BitWidth = VT.getSizeInBits();
13665 unsigned ShAmt = Op->getConstantOperandVal(1);
13666 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13668 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13669 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13670 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13671 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13673 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13674 DAG.getConstant(Mask, dl, VT));
13675 DAG.ReplaceAllUsesWith(Op, New);
13681 // If the primary and result isn't used, don't bother using X86ISD::AND,
13682 // because a TEST instruction will be better.
13683 if (!hasNonFlagsUse(Op))
13689 // Due to the ISEL shortcoming noted above, be conservative if this op is
13690 // likely to be selected as part of a load-modify-store instruction.
13691 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13692 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13693 if (UI->getOpcode() == ISD::STORE)
13696 // Otherwise use a regular EFLAGS-setting instruction.
13697 switch (ArithOp.getOpcode()) {
13698 default: llvm_unreachable("unexpected operator!");
13699 case ISD::SUB: Opcode = X86ISD::SUB; break;
13700 case ISD::XOR: Opcode = X86ISD::XOR; break;
13701 case ISD::AND: Opcode = X86ISD::AND; break;
13703 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13704 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13705 if (EFLAGS.getNode())
13708 Opcode = X86ISD::OR;
13722 return SDValue(Op.getNode(), 1);
13728 // If we found that truncation is beneficial, perform the truncation and
13730 if (NeedTruncation) {
13731 EVT VT = Op.getValueType();
13732 SDValue WideVal = Op->getOperand(0);
13733 EVT WideVT = WideVal.getValueType();
13734 unsigned ConvertedOp = 0;
13735 // Use a target machine opcode to prevent further DAGCombine
13736 // optimizations that may separate the arithmetic operations
13737 // from the setcc node.
13738 switch (WideVal.getOpcode()) {
13740 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13741 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13742 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13743 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13744 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13749 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13750 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13751 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13752 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13758 // Emit a CMP with 0, which is the TEST pattern.
13759 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13760 DAG.getConstant(0, dl, Op.getValueType()));
13762 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13763 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13765 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13766 DAG.ReplaceAllUsesWith(Op, New);
13767 return SDValue(New.getNode(), 1);
13770 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13772 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13773 SDLoc dl, SelectionDAG &DAG) const {
13774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13775 if (C->getAPIntValue() == 0)
13776 return EmitTest(Op0, X86CC, dl, DAG);
13778 if (Op0.getValueType() == MVT::i1)
13779 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13782 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13783 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13784 // Do the comparison at i32 if it's smaller, besides the Atom case.
13785 // This avoids subregister aliasing issues. Keep the smaller reference
13786 // if we're optimizing for size, however, as that'll allow better folding
13787 // of memory operations.
13788 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13789 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13790 !Subtarget->isAtom()) {
13791 unsigned ExtendOp =
13792 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13793 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13794 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13796 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13797 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13798 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13800 return SDValue(Sub.getNode(), 1);
13802 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13805 /// Convert a comparison if required by the subtarget.
13806 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13807 SelectionDAG &DAG) const {
13808 // If the subtarget does not support the FUCOMI instruction, floating-point
13809 // comparisons have to be converted.
13810 if (Subtarget->hasCMov() ||
13811 Cmp.getOpcode() != X86ISD::CMP ||
13812 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13813 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13816 // The instruction selector will select an FUCOM instruction instead of
13817 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13818 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13819 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13821 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13822 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13823 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13824 DAG.getConstant(8, dl, MVT::i8));
13825 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13826 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13829 /// The minimum architected relative accuracy is 2^-12. We need one
13830 /// Newton-Raphson step to have a good float result (24 bits of precision).
13831 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13832 DAGCombinerInfo &DCI,
13833 unsigned &RefinementSteps,
13834 bool &UseOneConstNR) const {
13835 EVT VT = Op.getValueType();
13836 const char *RecipOp;
13838 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13839 // TODO: Add support for AVX512 (v16f32).
13840 // It is likely not profitable to do this for f64 because a double-precision
13841 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13842 // instructions: convert to single, rsqrtss, convert back to double, refine
13843 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13844 // along with FMA, this could be a throughput win.
13845 if (VT == MVT::f32 && Subtarget->hasSSE1())
13847 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13848 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13849 RecipOp = "vec-sqrtf";
13853 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13854 if (!Recips.isEnabled(RecipOp))
13857 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13858 UseOneConstNR = false;
13859 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13862 /// The minimum architected relative accuracy is 2^-12. We need one
13863 /// Newton-Raphson step to have a good float result (24 bits of precision).
13864 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13865 DAGCombinerInfo &DCI,
13866 unsigned &RefinementSteps) const {
13867 EVT VT = Op.getValueType();
13868 const char *RecipOp;
13870 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13871 // TODO: Add support for AVX512 (v16f32).
13872 // It is likely not profitable to do this for f64 because a double-precision
13873 // reciprocal estimate with refinement on x86 prior to FMA requires
13874 // 15 instructions: convert to single, rcpss, convert back to double, refine
13875 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13876 // along with FMA, this could be a throughput win.
13877 if (VT == MVT::f32 && Subtarget->hasSSE1())
13879 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13880 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13881 RecipOp = "vec-divf";
13885 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13886 if (!Recips.isEnabled(RecipOp))
13889 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13890 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13893 /// If we have at least two divisions that use the same divisor, convert to
13894 /// multplication by a reciprocal. This may need to be adjusted for a given
13895 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13896 /// This is because we still need one division to calculate the reciprocal and
13897 /// then we need two multiplies by that reciprocal as replacements for the
13898 /// original divisions.
13899 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13903 static bool isAllOnes(SDValue V) {
13904 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13905 return C && C->isAllOnesValue();
13908 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13909 /// if it's possible.
13910 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13911 SDLoc dl, SelectionDAG &DAG) const {
13912 SDValue Op0 = And.getOperand(0);
13913 SDValue Op1 = And.getOperand(1);
13914 if (Op0.getOpcode() == ISD::TRUNCATE)
13915 Op0 = Op0.getOperand(0);
13916 if (Op1.getOpcode() == ISD::TRUNCATE)
13917 Op1 = Op1.getOperand(0);
13920 if (Op1.getOpcode() == ISD::SHL)
13921 std::swap(Op0, Op1);
13922 if (Op0.getOpcode() == ISD::SHL) {
13923 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13924 if (And00C->getZExtValue() == 1) {
13925 // If we looked past a truncate, check that it's only truncating away
13927 unsigned BitWidth = Op0.getValueSizeInBits();
13928 unsigned AndBitWidth = And.getValueSizeInBits();
13929 if (BitWidth > AndBitWidth) {
13931 DAG.computeKnownBits(Op0, Zeros, Ones);
13932 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13936 RHS = Op0.getOperand(1);
13938 } else if (Op1.getOpcode() == ISD::Constant) {
13939 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13940 uint64_t AndRHSVal = AndRHS->getZExtValue();
13941 SDValue AndLHS = Op0;
13943 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13944 LHS = AndLHS.getOperand(0);
13945 RHS = AndLHS.getOperand(1);
13948 // Use BT if the immediate can't be encoded in a TEST instruction.
13949 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13951 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13955 if (LHS.getNode()) {
13956 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13957 // instruction. Since the shift amount is in-range-or-undefined, we know
13958 // that doing a bittest on the i32 value is ok. We extend to i32 because
13959 // the encoding for the i16 version is larger than the i32 version.
13960 // Also promote i16 to i32 for performance / code size reason.
13961 if (LHS.getValueType() == MVT::i8 ||
13962 LHS.getValueType() == MVT::i16)
13963 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13965 // If the operand types disagree, extend the shift amount to match. Since
13966 // BT ignores high bits (like shifts) we can use anyextend.
13967 if (LHS.getValueType() != RHS.getValueType())
13968 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13970 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13971 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13972 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13973 DAG.getConstant(Cond, dl, MVT::i8), BT);
13979 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13981 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13986 // SSE Condition code mapping:
13995 switch (SetCCOpcode) {
13996 default: llvm_unreachable("Unexpected SETCC condition");
13998 case ISD::SETEQ: SSECC = 0; break;
14000 case ISD::SETGT: Swap = true; // Fallthrough
14002 case ISD::SETOLT: SSECC = 1; break;
14004 case ISD::SETGE: Swap = true; // Fallthrough
14006 case ISD::SETOLE: SSECC = 2; break;
14007 case ISD::SETUO: SSECC = 3; break;
14009 case ISD::SETNE: SSECC = 4; break;
14010 case ISD::SETULE: Swap = true; // Fallthrough
14011 case ISD::SETUGE: SSECC = 5; break;
14012 case ISD::SETULT: Swap = true; // Fallthrough
14013 case ISD::SETUGT: SSECC = 6; break;
14014 case ISD::SETO: SSECC = 7; break;
14016 case ISD::SETONE: SSECC = 8; break;
14019 std::swap(Op0, Op1);
14024 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14025 // ones, and then concatenate the result back.
14026 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14027 MVT VT = Op.getSimpleValueType();
14029 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14030 "Unsupported value type for operation");
14032 unsigned NumElems = VT.getVectorNumElements();
14034 SDValue CC = Op.getOperand(2);
14036 // Extract the LHS vectors
14037 SDValue LHS = Op.getOperand(0);
14038 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14039 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14041 // Extract the RHS vectors
14042 SDValue RHS = Op.getOperand(1);
14043 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14044 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14046 // Issue the operation on the smaller types and concatenate the result back
14047 MVT EltVT = VT.getVectorElementType();
14048 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14049 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14050 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14051 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14054 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14055 SDValue Op0 = Op.getOperand(0);
14056 SDValue Op1 = Op.getOperand(1);
14057 SDValue CC = Op.getOperand(2);
14058 MVT VT = Op.getSimpleValueType();
14061 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
14062 "Unexpected type for boolean compare operation");
14063 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14064 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14065 DAG.getConstant(-1, dl, VT));
14066 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14067 DAG.getConstant(-1, dl, VT));
14068 switch (SetCCOpcode) {
14069 default: llvm_unreachable("Unexpected SETCC condition");
14071 // (x == y) -> ~(x ^ y)
14072 return DAG.getNode(ISD::XOR, dl, VT,
14073 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14074 DAG.getConstant(-1, dl, VT));
14076 // (x != y) -> (x ^ y)
14077 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14080 // (x > y) -> (x & ~y)
14081 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14084 // (x < y) -> (~x & y)
14085 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14088 // (x <= y) -> (~x | y)
14089 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14092 // (x >=y) -> (x | ~y)
14093 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14097 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14098 const X86Subtarget *Subtarget) {
14099 SDValue Op0 = Op.getOperand(0);
14100 SDValue Op1 = Op.getOperand(1);
14101 SDValue CC = Op.getOperand(2);
14102 MVT VT = Op.getSimpleValueType();
14105 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14106 Op.getValueType().getScalarType() == MVT::i1 &&
14107 "Cannot set masked compare for this operation");
14109 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14111 bool Unsigned = false;
14114 switch (SetCCOpcode) {
14115 default: llvm_unreachable("Unexpected SETCC condition");
14116 case ISD::SETNE: SSECC = 4; break;
14117 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14118 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14119 case ISD::SETLT: Swap = true; //fall-through
14120 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14121 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14122 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14123 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14124 case ISD::SETULE: Unsigned = true; //fall-through
14125 case ISD::SETLE: SSECC = 2; break;
14129 std::swap(Op0, Op1);
14131 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14132 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14133 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14134 DAG.getConstant(SSECC, dl, MVT::i8));
14137 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14138 /// operand \p Op1. If non-trivial (for example because it's not constant)
14139 /// return an empty value.
14140 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14142 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14146 MVT VT = Op1.getSimpleValueType();
14147 MVT EVT = VT.getVectorElementType();
14148 unsigned n = VT.getVectorNumElements();
14149 SmallVector<SDValue, 8> ULTOp1;
14151 for (unsigned i = 0; i < n; ++i) {
14152 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14153 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14156 // Avoid underflow.
14157 APInt Val = Elt->getAPIntValue();
14161 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14164 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14167 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14168 SelectionDAG &DAG) {
14169 SDValue Op0 = Op.getOperand(0);
14170 SDValue Op1 = Op.getOperand(1);
14171 SDValue CC = Op.getOperand(2);
14172 MVT VT = Op.getSimpleValueType();
14173 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14174 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14179 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14180 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14183 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14184 unsigned Opc = X86ISD::CMPP;
14185 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14186 assert(VT.getVectorNumElements() <= 16);
14187 Opc = X86ISD::CMPM;
14189 // In the two special cases we can't handle, emit two comparisons.
14192 unsigned CombineOpc;
14193 if (SetCCOpcode == ISD::SETUEQ) {
14194 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14196 assert(SetCCOpcode == ISD::SETONE);
14197 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14200 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14201 DAG.getConstant(CC0, dl, MVT::i8));
14202 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14203 DAG.getConstant(CC1, dl, MVT::i8));
14204 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14206 // Handle all other FP comparisons here.
14207 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14208 DAG.getConstant(SSECC, dl, MVT::i8));
14211 MVT VTOp0 = Op0.getSimpleValueType();
14212 assert(VTOp0 == Op1.getSimpleValueType() &&
14213 "Expected operands with same type!");
14214 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14215 "Invalid number of packed elements for source and destination!");
14217 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14218 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14219 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14220 // legalizer firstly checks if the first operand in input to the setcc has
14221 // a legal type. If so, then it promotes the return type to that same type.
14222 // Otherwise, the return type is promoted to the 'next legal type' which,
14223 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14225 // We reach this code only if the following two conditions are met:
14226 // 1. Both return type and operand type have been promoted to wider types
14227 // by the type legalizer.
14228 // 2. The original operand type has been promoted to a 256-bit vector.
14230 // Note that condition 2. only applies for AVX targets.
14231 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14232 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14235 // The non-AVX512 code below works under the assumption that source and
14236 // destination types are the same.
14237 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14238 "Value types for source and destination must be the same!");
14240 // Break 256-bit integer vector compare into smaller ones.
14241 if (VT.is256BitVector() && !Subtarget->hasInt256())
14242 return Lower256IntVSETCC(Op, DAG);
14244 EVT OpVT = Op1.getValueType();
14245 if (OpVT.getVectorElementType() == MVT::i1)
14246 return LowerBoolVSETCC_AVX512(Op, DAG);
14248 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14249 if (Subtarget->hasAVX512()) {
14250 if (Op1.getValueType().is512BitVector() ||
14251 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14252 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14253 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14255 // In AVX-512 architecture setcc returns mask with i1 elements,
14256 // But there is no compare instruction for i8 and i16 elements in KNL.
14257 // We are not talking about 512-bit operands in this case, these
14258 // types are illegal.
14260 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14261 OpVT.getVectorElementType().getSizeInBits() >= 8))
14262 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14263 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14266 // Lower using XOP integer comparisons.
14267 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14268 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14269 // Translate compare code to XOP PCOM compare mode.
14270 unsigned CmpMode = 0;
14271 switch (SetCCOpcode) {
14272 default: llvm_unreachable("Unexpected SETCC condition");
14274 case ISD::SETLT: CmpMode = 0x00; break;
14276 case ISD::SETLE: CmpMode = 0x01; break;
14278 case ISD::SETGT: CmpMode = 0x02; break;
14280 case ISD::SETGE: CmpMode = 0x03; break;
14281 case ISD::SETEQ: CmpMode = 0x04; break;
14282 case ISD::SETNE: CmpMode = 0x05; break;
14285 // Are we comparing unsigned or signed integers?
14286 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14287 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14289 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14290 DAG.getConstant(CmpMode, dl, MVT::i8));
14293 // We are handling one of the integer comparisons here. Since SSE only has
14294 // GT and EQ comparisons for integer, swapping operands and multiple
14295 // operations may be required for some comparisons.
14297 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14298 bool Subus = false;
14300 switch (SetCCOpcode) {
14301 default: llvm_unreachable("Unexpected SETCC condition");
14302 case ISD::SETNE: Invert = true;
14303 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14304 case ISD::SETLT: Swap = true;
14305 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14306 case ISD::SETGE: Swap = true;
14307 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14308 Invert = true; break;
14309 case ISD::SETULT: Swap = true;
14310 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14311 FlipSigns = true; break;
14312 case ISD::SETUGE: Swap = true;
14313 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14314 FlipSigns = true; Invert = true; break;
14317 // Special case: Use min/max operations for SETULE/SETUGE
14318 MVT VET = VT.getVectorElementType();
14320 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14321 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14324 switch (SetCCOpcode) {
14326 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14327 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14330 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14333 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14334 if (!MinMax && hasSubus) {
14335 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14337 // t = psubus Op0, Op1
14338 // pcmpeq t, <0..0>
14339 switch (SetCCOpcode) {
14341 case ISD::SETULT: {
14342 // If the comparison is against a constant we can turn this into a
14343 // setule. With psubus, setule does not require a swap. This is
14344 // beneficial because the constant in the register is no longer
14345 // destructed as the destination so it can be hoisted out of a loop.
14346 // Only do this pre-AVX since vpcmp* is no longer destructive.
14347 if (Subtarget->hasAVX())
14349 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14350 if (ULEOp1.getNode()) {
14352 Subus = true; Invert = false; Swap = false;
14356 // Psubus is better than flip-sign because it requires no inversion.
14357 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14358 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14362 Opc = X86ISD::SUBUS;
14368 std::swap(Op0, Op1);
14370 // Check that the operation in question is available (most are plain SSE2,
14371 // but PCMPGTQ and PCMPEQQ have different requirements).
14372 if (VT == MVT::v2i64) {
14373 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14374 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14376 // First cast everything to the right type.
14377 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14378 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14380 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14381 // bits of the inputs before performing those operations. The lower
14382 // compare is always unsigned.
14385 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14387 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14388 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14389 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14390 Sign, Zero, Sign, Zero);
14392 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14393 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14395 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14396 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14397 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14399 // Create masks for only the low parts/high parts of the 64 bit integers.
14400 static const int MaskHi[] = { 1, 1, 3, 3 };
14401 static const int MaskLo[] = { 0, 0, 2, 2 };
14402 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14403 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14404 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14406 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14407 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14410 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14412 return DAG.getBitcast(VT, Result);
14415 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14416 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14417 // pcmpeqd + pshufd + pand.
14418 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14420 // First cast everything to the right type.
14421 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14422 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14425 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14427 // Make sure the lower and upper halves are both all-ones.
14428 static const int Mask[] = { 1, 0, 3, 2 };
14429 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14430 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14433 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14435 return DAG.getBitcast(VT, Result);
14439 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14440 // bits of the inputs before performing those operations.
14442 EVT EltVT = VT.getVectorElementType();
14443 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14445 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14446 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14449 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14451 // If the logical-not of the result is required, perform that now.
14453 Result = DAG.getNOT(dl, Result, VT);
14456 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14459 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14460 getZeroVector(VT, Subtarget, DAG, dl));
14465 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14467 MVT VT = Op.getSimpleValueType();
14469 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14471 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14472 && "SetCC type must be 8-bit or 1-bit integer");
14473 SDValue Op0 = Op.getOperand(0);
14474 SDValue Op1 = Op.getOperand(1);
14476 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14478 // Optimize to BT if possible.
14479 // Lower (X & (1 << N)) == 0 to BT(X, N).
14480 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14481 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14482 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14483 Op1.getOpcode() == ISD::Constant &&
14484 cast<ConstantSDNode>(Op1)->isNullValue() &&
14485 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14486 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14487 if (NewSetCC.getNode()) {
14489 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14494 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14496 if (Op1.getOpcode() == ISD::Constant &&
14497 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14498 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14499 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14501 // If the input is a setcc, then reuse the input setcc or use a new one with
14502 // the inverted condition.
14503 if (Op0.getOpcode() == X86ISD::SETCC) {
14504 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14505 bool Invert = (CC == ISD::SETNE) ^
14506 cast<ConstantSDNode>(Op1)->isNullValue();
14510 CCode = X86::GetOppositeBranchCondition(CCode);
14511 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14512 DAG.getConstant(CCode, dl, MVT::i8),
14513 Op0.getOperand(1));
14515 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14519 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14520 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14521 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14523 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14524 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14527 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14528 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14529 if (X86CC == X86::COND_INVALID)
14532 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14533 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14534 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14535 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14537 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14541 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14542 static bool isX86LogicalCmp(SDValue Op) {
14543 unsigned Opc = Op.getNode()->getOpcode();
14544 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14545 Opc == X86ISD::SAHF)
14547 if (Op.getResNo() == 1 &&
14548 (Opc == X86ISD::ADD ||
14549 Opc == X86ISD::SUB ||
14550 Opc == X86ISD::ADC ||
14551 Opc == X86ISD::SBB ||
14552 Opc == X86ISD::SMUL ||
14553 Opc == X86ISD::UMUL ||
14554 Opc == X86ISD::INC ||
14555 Opc == X86ISD::DEC ||
14556 Opc == X86ISD::OR ||
14557 Opc == X86ISD::XOR ||
14558 Opc == X86ISD::AND))
14561 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14567 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14568 if (V.getOpcode() != ISD::TRUNCATE)
14571 SDValue VOp0 = V.getOperand(0);
14572 unsigned InBits = VOp0.getValueSizeInBits();
14573 unsigned Bits = V.getValueSizeInBits();
14574 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14577 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14578 bool addTest = true;
14579 SDValue Cond = Op.getOperand(0);
14580 SDValue Op1 = Op.getOperand(1);
14581 SDValue Op2 = Op.getOperand(2);
14583 EVT VT = Op1.getValueType();
14586 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14587 // are available or VBLENDV if AVX is available.
14588 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14589 if (Cond.getOpcode() == ISD::SETCC &&
14590 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14591 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14592 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14593 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14594 int SSECC = translateX86FSETCC(
14595 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14598 if (Subtarget->hasAVX512()) {
14599 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14600 DAG.getConstant(SSECC, DL, MVT::i8));
14601 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14604 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14605 DAG.getConstant(SSECC, DL, MVT::i8));
14607 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14608 // of 3 logic instructions for size savings and potentially speed.
14609 // Unfortunately, there is no scalar form of VBLENDV.
14611 // If either operand is a constant, don't try this. We can expect to
14612 // optimize away at least one of the logic instructions later in that
14613 // case, so that sequence would be faster than a variable blend.
14615 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14616 // uses XMM0 as the selection register. That may need just as many
14617 // instructions as the AND/ANDN/OR sequence due to register moves, so
14620 if (Subtarget->hasAVX() &&
14621 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14623 // Convert to vectors, do a VSELECT, and convert back to scalar.
14624 // All of the conversions should be optimized away.
14626 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14627 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14628 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14629 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14631 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14632 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14634 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14636 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14637 VSel, DAG.getIntPtrConstant(0, DL));
14639 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14640 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14641 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14645 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14647 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14648 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14649 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14650 Op1Scalar = Op1.getOperand(0);
14652 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14653 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14654 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14655 Op2Scalar = Op2.getOperand(0);
14656 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14657 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14658 Op1Scalar.getValueType(),
14659 Cond, Op1Scalar, Op2Scalar);
14660 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14661 return DAG.getBitcast(VT, newSelect);
14662 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14663 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14664 DAG.getIntPtrConstant(0, DL));
14668 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14669 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14670 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14671 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14672 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14673 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14674 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14676 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14679 if (Cond.getOpcode() == ISD::SETCC) {
14680 SDValue NewCond = LowerSETCC(Cond, DAG);
14681 if (NewCond.getNode())
14685 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14686 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14687 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14688 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14689 if (Cond.getOpcode() == X86ISD::SETCC &&
14690 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14691 isZero(Cond.getOperand(1).getOperand(1))) {
14692 SDValue Cmp = Cond.getOperand(1);
14694 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14696 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14697 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14698 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14700 SDValue CmpOp0 = Cmp.getOperand(0);
14701 // Apply further optimizations for special cases
14702 // (select (x != 0), -1, 0) -> neg & sbb
14703 // (select (x == 0), 0, -1) -> neg & sbb
14704 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14705 if (YC->isNullValue() &&
14706 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14707 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14708 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14709 DAG.getConstant(0, DL,
14710 CmpOp0.getValueType()),
14712 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14713 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14714 SDValue(Neg.getNode(), 1));
14718 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14719 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14720 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14722 SDValue Res = // Res = 0 or -1.
14723 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14724 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14726 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14727 Res = DAG.getNOT(DL, Res, Res.getValueType());
14729 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14730 if (!N2C || !N2C->isNullValue())
14731 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14736 // Look past (and (setcc_carry (cmp ...)), 1).
14737 if (Cond.getOpcode() == ISD::AND &&
14738 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14739 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14740 if (C && C->getAPIntValue() == 1)
14741 Cond = Cond.getOperand(0);
14744 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14745 // setting operand in place of the X86ISD::SETCC.
14746 unsigned CondOpcode = Cond.getOpcode();
14747 if (CondOpcode == X86ISD::SETCC ||
14748 CondOpcode == X86ISD::SETCC_CARRY) {
14749 CC = Cond.getOperand(0);
14751 SDValue Cmp = Cond.getOperand(1);
14752 unsigned Opc = Cmp.getOpcode();
14753 MVT VT = Op.getSimpleValueType();
14755 bool IllegalFPCMov = false;
14756 if (VT.isFloatingPoint() && !VT.isVector() &&
14757 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14758 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14760 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14761 Opc == X86ISD::BT) { // FIXME
14765 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14766 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14767 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14768 Cond.getOperand(0).getValueType() != MVT::i8)) {
14769 SDValue LHS = Cond.getOperand(0);
14770 SDValue RHS = Cond.getOperand(1);
14771 unsigned X86Opcode;
14774 switch (CondOpcode) {
14775 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14776 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14777 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14778 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14779 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14780 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14781 default: llvm_unreachable("unexpected overflowing operator");
14783 if (CondOpcode == ISD::UMULO)
14784 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14787 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14789 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14791 if (CondOpcode == ISD::UMULO)
14792 Cond = X86Op.getValue(2);
14794 Cond = X86Op.getValue(1);
14796 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14801 // Look past the truncate if the high bits are known zero.
14802 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14803 Cond = Cond.getOperand(0);
14805 // We know the result of AND is compared against zero. Try to match
14807 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14808 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14809 if (NewSetCC.getNode()) {
14810 CC = NewSetCC.getOperand(0);
14811 Cond = NewSetCC.getOperand(1);
14818 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14819 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14822 // a < b ? -1 : 0 -> RES = ~setcc_carry
14823 // a < b ? 0 : -1 -> RES = setcc_carry
14824 // a >= b ? -1 : 0 -> RES = setcc_carry
14825 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14826 if (Cond.getOpcode() == X86ISD::SUB) {
14827 Cond = ConvertCmpIfNecessary(Cond, DAG);
14828 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14830 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14831 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14832 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14833 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14835 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14836 return DAG.getNOT(DL, Res, Res.getValueType());
14841 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14842 // widen the cmov and push the truncate through. This avoids introducing a new
14843 // branch during isel and doesn't add any extensions.
14844 if (Op.getValueType() == MVT::i8 &&
14845 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14846 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14847 if (T1.getValueType() == T2.getValueType() &&
14848 // Blacklist CopyFromReg to avoid partial register stalls.
14849 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14850 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14851 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14852 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14856 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14857 // condition is true.
14858 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14859 SDValue Ops[] = { Op2, Op1, CC, Cond };
14860 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14863 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14864 const X86Subtarget *Subtarget,
14865 SelectionDAG &DAG) {
14866 MVT VT = Op->getSimpleValueType(0);
14867 SDValue In = Op->getOperand(0);
14868 MVT InVT = In.getSimpleValueType();
14869 MVT VTElt = VT.getVectorElementType();
14870 MVT InVTElt = InVT.getVectorElementType();
14874 if ((InVTElt == MVT::i1) &&
14875 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14876 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14878 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14879 VTElt.getSizeInBits() <= 16)) ||
14881 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14882 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14884 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14885 VTElt.getSizeInBits() >= 32))))
14886 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14888 unsigned int NumElts = VT.getVectorNumElements();
14890 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14893 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14894 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14895 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14896 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14899 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14900 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14902 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14905 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14907 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14908 if (VT.is512BitVector())
14910 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14913 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14914 const X86Subtarget *Subtarget,
14915 SelectionDAG &DAG) {
14916 SDValue In = Op->getOperand(0);
14917 MVT VT = Op->getSimpleValueType(0);
14918 MVT InVT = In.getSimpleValueType();
14919 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14921 MVT InSVT = InVT.getScalarType();
14922 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14924 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14926 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14931 // SSE41 targets can use the pmovsx* instructions directly.
14932 if (Subtarget->hasSSE41())
14933 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14935 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14939 // As SRAI is only available on i16/i32 types, we expand only up to i32
14940 // and handle i64 separately.
14941 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14942 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14943 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14944 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14945 Curr = DAG.getBitcast(CurrVT, Curr);
14948 SDValue SignExt = Curr;
14949 if (CurrVT != InVT) {
14950 unsigned SignExtShift =
14951 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14952 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14953 DAG.getConstant(SignExtShift, dl, MVT::i8));
14959 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14960 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14961 DAG.getConstant(31, dl, MVT::i8));
14962 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14963 return DAG.getBitcast(VT, Ext);
14969 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14970 SelectionDAG &DAG) {
14971 MVT VT = Op->getSimpleValueType(0);
14972 SDValue In = Op->getOperand(0);
14973 MVT InVT = In.getSimpleValueType();
14976 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14977 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14979 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14980 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14981 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14984 if (Subtarget->hasInt256())
14985 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14987 // Optimize vectors in AVX mode
14988 // Sign extend v8i16 to v8i32 and
14991 // Divide input vector into two parts
14992 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14993 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14994 // concat the vectors to original VT
14996 unsigned NumElems = InVT.getVectorNumElements();
14997 SDValue Undef = DAG.getUNDEF(InVT);
14999 SmallVector<int,8> ShufMask1(NumElems, -1);
15000 for (unsigned i = 0; i != NumElems/2; ++i)
15003 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15005 SmallVector<int,8> ShufMask2(NumElems, -1);
15006 for (unsigned i = 0; i != NumElems/2; ++i)
15007 ShufMask2[i] = i + NumElems/2;
15009 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15011 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15012 VT.getVectorNumElements()/2);
15014 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15015 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15017 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15020 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15021 // may emit an illegal shuffle but the expansion is still better than scalar
15022 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15023 // we'll emit a shuffle and a arithmetic shift.
15024 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15025 // TODO: It is possible to support ZExt by zeroing the undef values during
15026 // the shuffle phase or after the shuffle.
15027 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15028 SelectionDAG &DAG) {
15029 MVT RegVT = Op.getSimpleValueType();
15030 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15031 assert(RegVT.isInteger() &&
15032 "We only custom lower integer vector sext loads.");
15034 // Nothing useful we can do without SSE2 shuffles.
15035 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15037 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15039 EVT MemVT = Ld->getMemoryVT();
15040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15041 unsigned RegSz = RegVT.getSizeInBits();
15043 ISD::LoadExtType Ext = Ld->getExtensionType();
15045 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15046 && "Only anyext and sext are currently implemented.");
15047 assert(MemVT != RegVT && "Cannot extend to the same type");
15048 assert(MemVT.isVector() && "Must load a vector from memory");
15050 unsigned NumElems = RegVT.getVectorNumElements();
15051 unsigned MemSz = MemVT.getSizeInBits();
15052 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15054 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15055 // The only way in which we have a legal 256-bit vector result but not the
15056 // integer 256-bit operations needed to directly lower a sextload is if we
15057 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15058 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15059 // correctly legalized. We do this late to allow the canonical form of
15060 // sextload to persist throughout the rest of the DAG combiner -- it wants
15061 // to fold together any extensions it can, and so will fuse a sign_extend
15062 // of an sextload into a sextload targeting a wider value.
15064 if (MemSz == 128) {
15065 // Just switch this to a normal load.
15066 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15067 "it must be a legal 128-bit vector "
15069 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15070 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15071 Ld->isInvariant(), Ld->getAlignment());
15073 assert(MemSz < 128 &&
15074 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15075 // Do an sext load to a 128-bit vector type. We want to use the same
15076 // number of elements, but elements half as wide. This will end up being
15077 // recursively lowered by this routine, but will succeed as we definitely
15078 // have all the necessary features if we're using AVX1.
15080 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15081 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15083 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15084 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15085 Ld->isNonTemporal(), Ld->isInvariant(),
15086 Ld->getAlignment());
15089 // Replace chain users with the new chain.
15090 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15091 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15093 // Finally, do a normal sign-extend to the desired register.
15094 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15097 // All sizes must be a power of two.
15098 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15099 "Non-power-of-two elements are not custom lowered!");
15101 // Attempt to load the original value using scalar loads.
15102 // Find the largest scalar type that divides the total loaded size.
15103 MVT SclrLoadTy = MVT::i8;
15104 for (MVT Tp : MVT::integer_valuetypes()) {
15105 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15110 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15111 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15113 SclrLoadTy = MVT::f64;
15115 // Calculate the number of scalar loads that we need to perform
15116 // in order to load our vector from memory.
15117 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15119 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15120 "Can only lower sext loads with a single scalar load!");
15122 unsigned loadRegZize = RegSz;
15123 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15126 // Represent our vector as a sequence of elements which are the
15127 // largest scalar that we can load.
15128 EVT LoadUnitVecVT = EVT::getVectorVT(
15129 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15131 // Represent the data using the same element type that is stored in
15132 // memory. In practice, we ''widen'' MemVT.
15134 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15135 loadRegZize / MemVT.getScalarType().getSizeInBits());
15137 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15138 "Invalid vector type");
15140 // We can't shuffle using an illegal type.
15141 assert(TLI.isTypeLegal(WideVecVT) &&
15142 "We only lower types that form legal widened vector types");
15144 SmallVector<SDValue, 8> Chains;
15145 SDValue Ptr = Ld->getBasePtr();
15146 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15147 TLI.getPointerTy(DAG.getDataLayout()));
15148 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15150 for (unsigned i = 0; i < NumLoads; ++i) {
15151 // Perform a single load.
15152 SDValue ScalarLoad =
15153 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15154 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15155 Ld->getAlignment());
15156 Chains.push_back(ScalarLoad.getValue(1));
15157 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15158 // another round of DAGCombining.
15160 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15162 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15163 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15165 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15168 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15170 // Bitcast the loaded value to a vector of the original element type, in
15171 // the size of the target vector type.
15172 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15173 unsigned SizeRatio = RegSz / MemSz;
15175 if (Ext == ISD::SEXTLOAD) {
15176 // If we have SSE4.1, we can directly emit a VSEXT node.
15177 if (Subtarget->hasSSE41()) {
15178 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15179 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15183 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15185 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15186 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15188 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15189 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15193 // Redistribute the loaded elements into the different locations.
15194 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15195 for (unsigned i = 0; i != NumElems; ++i)
15196 ShuffleVec[i * SizeRatio] = i;
15198 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15199 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15201 // Bitcast to the requested type.
15202 Shuff = DAG.getBitcast(RegVT, Shuff);
15203 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15207 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15208 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15209 // from the AND / OR.
15210 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15211 Opc = Op.getOpcode();
15212 if (Opc != ISD::OR && Opc != ISD::AND)
15214 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15215 Op.getOperand(0).hasOneUse() &&
15216 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15217 Op.getOperand(1).hasOneUse());
15220 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15221 // 1 and that the SETCC node has a single use.
15222 static bool isXor1OfSetCC(SDValue Op) {
15223 if (Op.getOpcode() != ISD::XOR)
15225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15226 if (N1C && N1C->getAPIntValue() == 1) {
15227 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15228 Op.getOperand(0).hasOneUse();
15233 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15234 bool addTest = true;
15235 SDValue Chain = Op.getOperand(0);
15236 SDValue Cond = Op.getOperand(1);
15237 SDValue Dest = Op.getOperand(2);
15240 bool Inverted = false;
15242 if (Cond.getOpcode() == ISD::SETCC) {
15243 // Check for setcc([su]{add,sub,mul}o == 0).
15244 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15245 isa<ConstantSDNode>(Cond.getOperand(1)) &&
15246 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15247 Cond.getOperand(0).getResNo() == 1 &&
15248 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15249 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15250 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15251 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15252 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15253 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15255 Cond = Cond.getOperand(0);
15257 SDValue NewCond = LowerSETCC(Cond, DAG);
15258 if (NewCond.getNode())
15263 // FIXME: LowerXALUO doesn't handle these!!
15264 else if (Cond.getOpcode() == X86ISD::ADD ||
15265 Cond.getOpcode() == X86ISD::SUB ||
15266 Cond.getOpcode() == X86ISD::SMUL ||
15267 Cond.getOpcode() == X86ISD::UMUL)
15268 Cond = LowerXALUO(Cond, DAG);
15271 // Look pass (and (setcc_carry (cmp ...)), 1).
15272 if (Cond.getOpcode() == ISD::AND &&
15273 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15274 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15275 if (C && C->getAPIntValue() == 1)
15276 Cond = Cond.getOperand(0);
15279 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15280 // setting operand in place of the X86ISD::SETCC.
15281 unsigned CondOpcode = Cond.getOpcode();
15282 if (CondOpcode == X86ISD::SETCC ||
15283 CondOpcode == X86ISD::SETCC_CARRY) {
15284 CC = Cond.getOperand(0);
15286 SDValue Cmp = Cond.getOperand(1);
15287 unsigned Opc = Cmp.getOpcode();
15288 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15289 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15293 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15297 // These can only come from an arithmetic instruction with overflow,
15298 // e.g. SADDO, UADDO.
15299 Cond = Cond.getNode()->getOperand(1);
15305 CondOpcode = Cond.getOpcode();
15306 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15307 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15308 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15309 Cond.getOperand(0).getValueType() != MVT::i8)) {
15310 SDValue LHS = Cond.getOperand(0);
15311 SDValue RHS = Cond.getOperand(1);
15312 unsigned X86Opcode;
15315 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15316 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15318 switch (CondOpcode) {
15319 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15323 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15326 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15327 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15331 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15334 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15335 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15336 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15337 default: llvm_unreachable("unexpected overflowing operator");
15340 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15341 if (CondOpcode == ISD::UMULO)
15342 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15345 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15347 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15349 if (CondOpcode == ISD::UMULO)
15350 Cond = X86Op.getValue(2);
15352 Cond = X86Op.getValue(1);
15354 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15358 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15359 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15360 if (CondOpc == ISD::OR) {
15361 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15362 // two branches instead of an explicit OR instruction with a
15364 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15365 isX86LogicalCmp(Cmp)) {
15366 CC = Cond.getOperand(0).getOperand(0);
15367 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15368 Chain, Dest, CC, Cmp);
15369 CC = Cond.getOperand(1).getOperand(0);
15373 } else { // ISD::AND
15374 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15375 // two branches instead of an explicit AND instruction with a
15376 // separate test. However, we only do this if this block doesn't
15377 // have a fall-through edge, because this requires an explicit
15378 // jmp when the condition is false.
15379 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15380 isX86LogicalCmp(Cmp) &&
15381 Op.getNode()->hasOneUse()) {
15382 X86::CondCode CCode =
15383 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15384 CCode = X86::GetOppositeBranchCondition(CCode);
15385 CC = DAG.getConstant(CCode, dl, MVT::i8);
15386 SDNode *User = *Op.getNode()->use_begin();
15387 // Look for an unconditional branch following this conditional branch.
15388 // We need this because we need to reverse the successors in order
15389 // to implement FCMP_OEQ.
15390 if (User->getOpcode() == ISD::BR) {
15391 SDValue FalseBB = User->getOperand(1);
15393 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15394 assert(NewBR == User);
15398 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15399 Chain, Dest, CC, Cmp);
15400 X86::CondCode CCode =
15401 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15402 CCode = X86::GetOppositeBranchCondition(CCode);
15403 CC = DAG.getConstant(CCode, dl, MVT::i8);
15409 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15410 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15411 // It should be transformed during dag combiner except when the condition
15412 // is set by a arithmetics with overflow node.
15413 X86::CondCode CCode =
15414 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15415 CCode = X86::GetOppositeBranchCondition(CCode);
15416 CC = DAG.getConstant(CCode, dl, MVT::i8);
15417 Cond = Cond.getOperand(0).getOperand(1);
15419 } else if (Cond.getOpcode() == ISD::SETCC &&
15420 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15421 // For FCMP_OEQ, we can emit
15422 // two branches instead of an explicit AND instruction with a
15423 // separate test. However, we only do this if this block doesn't
15424 // have a fall-through edge, because this requires an explicit
15425 // jmp when the condition is false.
15426 if (Op.getNode()->hasOneUse()) {
15427 SDNode *User = *Op.getNode()->use_begin();
15428 // Look for an unconditional branch following this conditional branch.
15429 // We need this because we need to reverse the successors in order
15430 // to implement FCMP_OEQ.
15431 if (User->getOpcode() == ISD::BR) {
15432 SDValue FalseBB = User->getOperand(1);
15434 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15435 assert(NewBR == User);
15439 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15440 Cond.getOperand(0), Cond.getOperand(1));
15441 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15442 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15443 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15444 Chain, Dest, CC, Cmp);
15445 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15450 } else if (Cond.getOpcode() == ISD::SETCC &&
15451 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15452 // For FCMP_UNE, we can emit
15453 // two branches instead of an explicit AND instruction with a
15454 // separate test. However, we only do this if this block doesn't
15455 // have a fall-through edge, because this requires an explicit
15456 // jmp when the condition is false.
15457 if (Op.getNode()->hasOneUse()) {
15458 SDNode *User = *Op.getNode()->use_begin();
15459 // Look for an unconditional branch following this conditional branch.
15460 // We need this because we need to reverse the successors in order
15461 // to implement FCMP_UNE.
15462 if (User->getOpcode() == ISD::BR) {
15463 SDValue FalseBB = User->getOperand(1);
15465 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15466 assert(NewBR == User);
15469 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15470 Cond.getOperand(0), Cond.getOperand(1));
15471 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15472 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15473 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15474 Chain, Dest, CC, Cmp);
15475 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15485 // Look pass the truncate if the high bits are known zero.
15486 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15487 Cond = Cond.getOperand(0);
15489 // We know the result of AND is compared against zero. Try to match
15491 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15492 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15493 if (NewSetCC.getNode()) {
15494 CC = NewSetCC.getOperand(0);
15495 Cond = NewSetCC.getOperand(1);
15502 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15503 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15504 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15506 Cond = ConvertCmpIfNecessary(Cond, DAG);
15507 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15508 Chain, Dest, CC, Cond);
15511 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15512 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15513 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15514 // that the guard pages used by the OS virtual memory manager are allocated in
15515 // correct sequence.
15517 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15518 SelectionDAG &DAG) const {
15519 MachineFunction &MF = DAG.getMachineFunction();
15520 bool SplitStack = MF.shouldSplitStack();
15521 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15527 SDNode* Node = Op.getNode();
15529 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15530 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15531 " not tell us which reg is the stack pointer!");
15532 EVT VT = Node->getValueType(0);
15533 SDValue Tmp1 = SDValue(Node, 0);
15534 SDValue Tmp2 = SDValue(Node, 1);
15535 SDValue Tmp3 = Node->getOperand(2);
15536 SDValue Chain = Tmp1.getOperand(0);
15538 // Chain the dynamic stack allocation so that it doesn't modify the stack
15539 // pointer when other instructions are using the stack.
15540 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15543 SDValue Size = Tmp2.getOperand(1);
15544 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15545 Chain = SP.getValue(1);
15546 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15547 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15548 unsigned StackAlign = TFI.getStackAlignment();
15549 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15550 if (Align > StackAlign)
15551 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15552 DAG.getConstant(-(uint64_t)Align, dl, VT));
15553 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15555 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15556 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15559 SDValue Ops[2] = { Tmp1, Tmp2 };
15560 return DAG.getMergeValues(Ops, dl);
15564 SDValue Chain = Op.getOperand(0);
15565 SDValue Size = Op.getOperand(1);
15566 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15567 EVT VT = Op.getNode()->getValueType(0);
15569 bool Is64Bit = Subtarget->is64Bit();
15570 MVT SPTy = getPointerTy(DAG.getDataLayout());
15573 MachineRegisterInfo &MRI = MF.getRegInfo();
15576 // The 64 bit implementation of segmented stacks needs to clobber both r10
15577 // r11. This makes it impossible to use it along with nested parameters.
15578 const Function *F = MF.getFunction();
15580 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15582 if (I->hasNestAttr())
15583 report_fatal_error("Cannot use segmented stacks with functions that "
15584 "have nested arguments.");
15587 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15588 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15589 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15590 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15591 DAG.getRegister(Vreg, SPTy));
15592 SDValue Ops1[2] = { Value, Chain };
15593 return DAG.getMergeValues(Ops1, dl);
15596 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15598 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15599 Flag = Chain.getValue(1);
15600 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15602 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15604 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15605 unsigned SPReg = RegInfo->getStackRegister();
15606 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15607 Chain = SP.getValue(1);
15610 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15611 DAG.getConstant(-(uint64_t)Align, dl, VT));
15612 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15615 SDValue Ops1[2] = { SP, Chain };
15616 return DAG.getMergeValues(Ops1, dl);
15620 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15621 MachineFunction &MF = DAG.getMachineFunction();
15622 auto PtrVT = getPointerTy(MF.getDataLayout());
15623 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15625 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15628 if (!Subtarget->is64Bit() ||
15629 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15630 // vastart just stores the address of the VarArgsFrameIndex slot into the
15631 // memory location argument.
15632 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15633 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15634 MachinePointerInfo(SV), false, false, 0);
15638 // gp_offset (0 - 6 * 8)
15639 // fp_offset (48 - 48 + 8 * 16)
15640 // overflow_arg_area (point to parameters coming in memory).
15642 SmallVector<SDValue, 8> MemOps;
15643 SDValue FIN = Op.getOperand(1);
15645 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15646 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15648 FIN, MachinePointerInfo(SV), false, false, 0);
15649 MemOps.push_back(Store);
15652 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15653 Store = DAG.getStore(Op.getOperand(0), DL,
15654 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15656 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15657 MemOps.push_back(Store);
15659 // Store ptr to overflow_arg_area
15660 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15661 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15662 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15663 MachinePointerInfo(SV, 8),
15665 MemOps.push_back(Store);
15667 // Store ptr to reg_save_area.
15668 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15669 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15670 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15671 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15672 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15673 MemOps.push_back(Store);
15674 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15677 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15678 assert(Subtarget->is64Bit() &&
15679 "LowerVAARG only handles 64-bit va_arg!");
15680 assert(Op.getNode()->getNumOperands() == 4);
15682 MachineFunction &MF = DAG.getMachineFunction();
15683 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15684 // The Win64 ABI uses char* instead of a structure.
15685 return DAG.expandVAArg(Op.getNode());
15687 SDValue Chain = Op.getOperand(0);
15688 SDValue SrcPtr = Op.getOperand(1);
15689 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15690 unsigned Align = Op.getConstantOperandVal(3);
15693 EVT ArgVT = Op.getNode()->getValueType(0);
15694 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15695 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15698 // Decide which area this value should be read from.
15699 // TODO: Implement the AMD64 ABI in its entirety. This simple
15700 // selection mechanism works only for the basic types.
15701 if (ArgVT == MVT::f80) {
15702 llvm_unreachable("va_arg for f80 not yet implemented");
15703 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15704 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15705 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15706 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15708 llvm_unreachable("Unhandled argument type in LowerVAARG");
15711 if (ArgMode == 2) {
15712 // Sanity Check: Make sure using fp_offset makes sense.
15713 assert(!Subtarget->useSoftFloat() &&
15714 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15715 Subtarget->hasSSE1());
15718 // Insert VAARG_64 node into the DAG
15719 // VAARG_64 returns two values: Variable Argument Address, Chain
15720 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15721 DAG.getConstant(ArgMode, dl, MVT::i8),
15722 DAG.getConstant(Align, dl, MVT::i32)};
15723 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15724 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15725 VTs, InstOps, MVT::i64,
15726 MachinePointerInfo(SV),
15728 /*Volatile=*/false,
15730 /*WriteMem=*/true);
15731 Chain = VAARG.getValue(1);
15733 // Load the next argument and return it
15734 return DAG.getLoad(ArgVT, dl,
15737 MachinePointerInfo(),
15738 false, false, false, 0);
15741 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15742 SelectionDAG &DAG) {
15743 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15744 // where a va_list is still an i8*.
15745 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15746 if (Subtarget->isCallingConvWin64(
15747 DAG.getMachineFunction().getFunction()->getCallingConv()))
15748 // Probably a Win64 va_copy.
15749 return DAG.expandVACopy(Op.getNode());
15751 SDValue Chain = Op.getOperand(0);
15752 SDValue DstPtr = Op.getOperand(1);
15753 SDValue SrcPtr = Op.getOperand(2);
15754 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15755 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15758 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15759 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15761 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15764 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15765 // amount is a constant. Takes immediate version of shift as input.
15766 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15767 SDValue SrcOp, uint64_t ShiftAmt,
15768 SelectionDAG &DAG) {
15769 MVT ElementType = VT.getVectorElementType();
15771 // Fold this packed shift into its first operand if ShiftAmt is 0.
15775 // Check for ShiftAmt >= element width
15776 if (ShiftAmt >= ElementType.getSizeInBits()) {
15777 if (Opc == X86ISD::VSRAI)
15778 ShiftAmt = ElementType.getSizeInBits() - 1;
15780 return DAG.getConstant(0, dl, VT);
15783 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15784 && "Unknown target vector shift-by-constant node");
15786 // Fold this packed vector shift into a build vector if SrcOp is a
15787 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15788 if (VT == SrcOp.getSimpleValueType() &&
15789 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15790 SmallVector<SDValue, 8> Elts;
15791 unsigned NumElts = SrcOp->getNumOperands();
15792 ConstantSDNode *ND;
15795 default: llvm_unreachable(nullptr);
15796 case X86ISD::VSHLI:
15797 for (unsigned i=0; i!=NumElts; ++i) {
15798 SDValue CurrentOp = SrcOp->getOperand(i);
15799 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15800 Elts.push_back(CurrentOp);
15803 ND = cast<ConstantSDNode>(CurrentOp);
15804 const APInt &C = ND->getAPIntValue();
15805 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15808 case X86ISD::VSRLI:
15809 for (unsigned i=0; i!=NumElts; ++i) {
15810 SDValue CurrentOp = SrcOp->getOperand(i);
15811 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15812 Elts.push_back(CurrentOp);
15815 ND = cast<ConstantSDNode>(CurrentOp);
15816 const APInt &C = ND->getAPIntValue();
15817 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15820 case X86ISD::VSRAI:
15821 for (unsigned i=0; i!=NumElts; ++i) {
15822 SDValue CurrentOp = SrcOp->getOperand(i);
15823 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15824 Elts.push_back(CurrentOp);
15827 ND = cast<ConstantSDNode>(CurrentOp);
15828 const APInt &C = ND->getAPIntValue();
15829 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15834 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15837 return DAG.getNode(Opc, dl, VT, SrcOp,
15838 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15841 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15842 // may or may not be a constant. Takes immediate version of shift as input.
15843 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15844 SDValue SrcOp, SDValue ShAmt,
15845 SelectionDAG &DAG) {
15846 MVT SVT = ShAmt.getSimpleValueType();
15847 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15849 // Catch shift-by-constant.
15850 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15851 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15852 CShAmt->getZExtValue(), DAG);
15854 // Change opcode to non-immediate version
15856 default: llvm_unreachable("Unknown target vector shift node");
15857 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15858 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15859 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15862 const X86Subtarget &Subtarget =
15863 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15864 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15865 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15866 // Let the shuffle legalizer expand this shift amount node.
15867 SDValue Op0 = ShAmt.getOperand(0);
15868 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15869 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15871 // Need to build a vector containing shift amount.
15872 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15873 SmallVector<SDValue, 4> ShOps;
15874 ShOps.push_back(ShAmt);
15875 if (SVT == MVT::i32) {
15876 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15877 ShOps.push_back(DAG.getUNDEF(SVT));
15879 ShOps.push_back(DAG.getUNDEF(SVT));
15881 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15882 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15885 // The return type has to be a 128-bit type with the same element
15886 // type as the input type.
15887 MVT EltVT = VT.getVectorElementType();
15888 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15890 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15891 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15894 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15895 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15896 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15897 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15898 SDValue PreservedSrc,
15899 const X86Subtarget *Subtarget,
15900 SelectionDAG &DAG) {
15901 EVT VT = Op.getValueType();
15902 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15903 MVT::i1, VT.getVectorNumElements());
15904 SDValue VMask = SDValue();
15905 unsigned OpcodeSelect = ISD::VSELECT;
15908 assert(MaskVT.isSimple() && "invalid mask type");
15910 if (isAllOnes(Mask))
15913 if (MaskVT.bitsGT(Mask.getValueType())) {
15914 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15915 MaskVT.getSizeInBits());
15916 VMask = DAG.getBitcast(MaskVT,
15917 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15919 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15920 Mask.getValueType().getSizeInBits());
15921 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15922 // are extracted by EXTRACT_SUBVECTOR.
15923 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15924 DAG.getBitcast(BitcastVT, Mask),
15925 DAG.getIntPtrConstant(0, dl));
15928 switch (Op.getOpcode()) {
15930 case X86ISD::PCMPEQM:
15931 case X86ISD::PCMPGTM:
15933 case X86ISD::CMPMU:
15934 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15935 case X86ISD::VFPCLASS:
15936 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15937 case X86ISD::VTRUNC:
15938 case X86ISD::VTRUNCS:
15939 case X86ISD::VTRUNCUS:
15940 // We can't use ISD::VSELECT here because it is not always "Legal"
15941 // for the destination type. For example vpmovqb require only AVX512
15942 // and vselect that can operate on byte element type require BWI
15943 OpcodeSelect = X86ISD::SELECT;
15946 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15947 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15948 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15951 /// \brief Creates an SDNode for a predicated scalar operation.
15952 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15953 /// The mask is coming as MVT::i8 and it should be truncated
15954 /// to MVT::i1 while lowering masking intrinsics.
15955 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15956 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15957 /// for a scalar instruction.
15958 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15959 SDValue PreservedSrc,
15960 const X86Subtarget *Subtarget,
15961 SelectionDAG &DAG) {
15962 if (isAllOnes(Mask))
15965 EVT VT = Op.getValueType();
15967 // The mask should be of type MVT::i1
15968 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15970 if (Op.getOpcode() == X86ISD::FSETCC)
15971 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15972 if (Op.getOpcode() == X86ISD::VFPCLASS)
15973 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
15975 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15976 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15977 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15980 static int getSEHRegistrationNodeSize(const Function *Fn) {
15981 if (!Fn->hasPersonalityFn())
15982 report_fatal_error(
15983 "querying registration node size for function without personality");
15984 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15985 // WinEHStatePass for the full struct definition.
15986 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15987 case EHPersonality::MSVC_X86SEH: return 24;
15988 case EHPersonality::MSVC_CXX: return 16;
15991 report_fatal_error("can only recover FP for MSVC EH personality functions");
15994 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15995 /// function or when returning to a parent frame after catching an exception, we
15996 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15997 /// Here's the math:
15998 /// RegNodeBase = EntryEBP - RegNodeSize
15999 /// ParentFP = RegNodeBase - RegNodeFrameOffset
16000 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16001 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16002 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16003 SDValue EntryEBP) {
16004 MachineFunction &MF = DAG.getMachineFunction();
16007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16008 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16010 // It's possible that the parent function no longer has a personality function
16011 // if the exceptional code was optimized away, in which case we just return
16012 // the incoming EBP.
16013 if (!Fn->hasPersonalityFn())
16016 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16018 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16020 MCSymbol *OffsetSym =
16021 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16022 GlobalValue::getRealLinkageName(Fn->getName()));
16023 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16024 SDValue RegNodeFrameOffset =
16025 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16027 // RegNodeBase = EntryEBP - RegNodeSize
16028 // ParentFP = RegNodeBase - RegNodeFrameOffset
16029 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16030 DAG.getConstant(RegNodeSize, dl, PtrVT));
16031 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16034 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16035 SelectionDAG &DAG) {
16037 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16038 EVT VT = Op.getValueType();
16039 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16041 switch(IntrData->Type) {
16042 case INTR_TYPE_1OP:
16043 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16044 case INTR_TYPE_2OP:
16045 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16047 case INTR_TYPE_2OP_IMM8:
16048 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16049 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16050 case INTR_TYPE_3OP:
16051 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16052 Op.getOperand(2), Op.getOperand(3));
16053 case INTR_TYPE_4OP:
16054 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16055 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16056 case INTR_TYPE_1OP_MASK_RM: {
16057 SDValue Src = Op.getOperand(1);
16058 SDValue PassThru = Op.getOperand(2);
16059 SDValue Mask = Op.getOperand(3);
16060 SDValue RoundingMode;
16061 // We allways add rounding mode to the Node.
16062 // If the rounding mode is not specified, we add the
16063 // "current direction" mode.
16064 if (Op.getNumOperands() == 4)
16066 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16068 RoundingMode = Op.getOperand(4);
16069 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16070 if (IntrWithRoundingModeOpcode != 0)
16071 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16072 X86::STATIC_ROUNDING::CUR_DIRECTION)
16073 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16074 dl, Op.getValueType(), Src, RoundingMode),
16075 Mask, PassThru, Subtarget, DAG);
16076 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16078 Mask, PassThru, Subtarget, DAG);
16080 case INTR_TYPE_1OP_MASK: {
16081 SDValue Src = Op.getOperand(1);
16082 SDValue PassThru = Op.getOperand(2);
16083 SDValue Mask = Op.getOperand(3);
16084 // We add rounding mode to the Node when
16085 // - RM Opcode is specified and
16086 // - RM is not "current direction".
16087 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16088 if (IntrWithRoundingModeOpcode != 0) {
16089 SDValue Rnd = Op.getOperand(4);
16090 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16091 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16092 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16093 dl, Op.getValueType(),
16095 Mask, PassThru, Subtarget, DAG);
16098 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16099 Mask, PassThru, Subtarget, DAG);
16101 case INTR_TYPE_SCALAR_MASK: {
16102 SDValue Src1 = Op.getOperand(1);
16103 SDValue Src2 = Op.getOperand(2);
16104 SDValue passThru = Op.getOperand(3);
16105 SDValue Mask = Op.getOperand(4);
16106 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16107 Mask, passThru, Subtarget, DAG);
16109 case INTR_TYPE_SCALAR_MASK_RM: {
16110 SDValue Src1 = Op.getOperand(1);
16111 SDValue Src2 = Op.getOperand(2);
16112 SDValue Src0 = Op.getOperand(3);
16113 SDValue Mask = Op.getOperand(4);
16114 // There are 2 kinds of intrinsics in this group:
16115 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16116 // (2) With rounding mode and sae - 7 operands.
16117 if (Op.getNumOperands() == 6) {
16118 SDValue Sae = Op.getOperand(5);
16119 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16120 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16122 Mask, Src0, Subtarget, DAG);
16124 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16125 SDValue RoundingMode = Op.getOperand(5);
16126 SDValue Sae = Op.getOperand(6);
16127 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16128 RoundingMode, Sae),
16129 Mask, Src0, Subtarget, DAG);
16131 case INTR_TYPE_2OP_MASK:
16132 case INTR_TYPE_2OP_IMM8_MASK: {
16133 SDValue Src1 = Op.getOperand(1);
16134 SDValue Src2 = Op.getOperand(2);
16135 SDValue PassThru = Op.getOperand(3);
16136 SDValue Mask = Op.getOperand(4);
16138 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16139 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16141 // We specify 2 possible opcodes for intrinsics with rounding modes.
16142 // First, we check if the intrinsic may have non-default rounding mode,
16143 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16144 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16145 if (IntrWithRoundingModeOpcode != 0) {
16146 SDValue Rnd = Op.getOperand(5);
16147 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16148 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16149 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16150 dl, Op.getValueType(),
16152 Mask, PassThru, Subtarget, DAG);
16155 // TODO: Intrinsics should have fast-math-flags to propagate.
16156 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16157 Mask, PassThru, Subtarget, DAG);
16159 case INTR_TYPE_2OP_MASK_RM: {
16160 SDValue Src1 = Op.getOperand(1);
16161 SDValue Src2 = Op.getOperand(2);
16162 SDValue PassThru = Op.getOperand(3);
16163 SDValue Mask = Op.getOperand(4);
16164 // We specify 2 possible modes for intrinsics, with/without rounding
16166 // First, we check if the intrinsic have rounding mode (6 operands),
16167 // if not, we set rounding mode to "current".
16169 if (Op.getNumOperands() == 6)
16170 Rnd = Op.getOperand(5);
16172 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16173 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16175 Mask, PassThru, Subtarget, DAG);
16177 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16178 SDValue Src1 = Op.getOperand(1);
16179 SDValue Src2 = Op.getOperand(2);
16180 SDValue Src3 = Op.getOperand(3);
16181 SDValue PassThru = Op.getOperand(4);
16182 SDValue Mask = Op.getOperand(5);
16183 SDValue Sae = Op.getOperand(6);
16185 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16187 Mask, PassThru, Subtarget, DAG);
16189 case INTR_TYPE_3OP_MASK_RM: {
16190 SDValue Src1 = Op.getOperand(1);
16191 SDValue Src2 = Op.getOperand(2);
16192 SDValue Imm = Op.getOperand(3);
16193 SDValue PassThru = Op.getOperand(4);
16194 SDValue Mask = Op.getOperand(5);
16195 // We specify 2 possible modes for intrinsics, with/without rounding
16197 // First, we check if the intrinsic have rounding mode (7 operands),
16198 // if not, we set rounding mode to "current".
16200 if (Op.getNumOperands() == 7)
16201 Rnd = Op.getOperand(6);
16203 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16204 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16205 Src1, Src2, Imm, Rnd),
16206 Mask, PassThru, Subtarget, DAG);
16208 case INTR_TYPE_3OP_IMM8_MASK:
16209 case INTR_TYPE_3OP_MASK:
16210 case INSERT_SUBVEC: {
16211 SDValue Src1 = Op.getOperand(1);
16212 SDValue Src2 = Op.getOperand(2);
16213 SDValue Src3 = Op.getOperand(3);
16214 SDValue PassThru = Op.getOperand(4);
16215 SDValue Mask = Op.getOperand(5);
16217 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16218 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16219 else if (IntrData->Type == INSERT_SUBVEC) {
16220 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16221 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16222 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16223 Imm *= Src2.getValueType().getVectorNumElements();
16224 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16227 // We specify 2 possible opcodes for intrinsics with rounding modes.
16228 // First, we check if the intrinsic may have non-default rounding mode,
16229 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16230 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16231 if (IntrWithRoundingModeOpcode != 0) {
16232 SDValue Rnd = Op.getOperand(6);
16233 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16234 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16235 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16236 dl, Op.getValueType(),
16237 Src1, Src2, Src3, Rnd),
16238 Mask, PassThru, Subtarget, DAG);
16241 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16243 Mask, PassThru, Subtarget, DAG);
16245 case VPERM_3OP_MASKZ:
16246 case VPERM_3OP_MASK:
16249 case FMA_OP_MASK: {
16250 SDValue Src1 = Op.getOperand(1);
16251 SDValue Src2 = Op.getOperand(2);
16252 SDValue Src3 = Op.getOperand(3);
16253 SDValue Mask = Op.getOperand(4);
16254 EVT VT = Op.getValueType();
16255 SDValue PassThru = SDValue();
16257 // set PassThru element
16258 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16259 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16260 else if (IntrData->Type == FMA_OP_MASK3)
16265 // We specify 2 possible opcodes for intrinsics with rounding modes.
16266 // First, we check if the intrinsic may have non-default rounding mode,
16267 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16268 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16269 if (IntrWithRoundingModeOpcode != 0) {
16270 SDValue Rnd = Op.getOperand(5);
16271 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16272 X86::STATIC_ROUNDING::CUR_DIRECTION)
16273 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16274 dl, Op.getValueType(),
16275 Src1, Src2, Src3, Rnd),
16276 Mask, PassThru, Subtarget, DAG);
16278 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16279 dl, Op.getValueType(),
16281 Mask, PassThru, Subtarget, DAG);
16283 case TERLOG_OP_MASK:
16284 case TERLOG_OP_MASKZ: {
16285 SDValue Src1 = Op.getOperand(1);
16286 SDValue Src2 = Op.getOperand(2);
16287 SDValue Src3 = Op.getOperand(3);
16288 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16289 SDValue Mask = Op.getOperand(5);
16290 EVT VT = Op.getValueType();
16291 SDValue PassThru = Src1;
16292 // Set PassThru element.
16293 if (IntrData->Type == TERLOG_OP_MASKZ)
16294 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16296 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16297 Src1, Src2, Src3, Src4),
16298 Mask, PassThru, Subtarget, DAG);
16301 // FPclass intrinsics with mask
16302 SDValue Src1 = Op.getOperand(1);
16303 EVT VT = Src1.getValueType();
16304 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16305 VT.getVectorNumElements());
16306 SDValue Imm = Op.getOperand(2);
16307 SDValue Mask = Op.getOperand(3);
16308 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16309 Mask.getValueType().getSizeInBits());
16310 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16311 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16312 DAG.getTargetConstant(0, dl, MaskVT),
16314 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16315 DAG.getUNDEF(BitcastVT), FPclassMask,
16316 DAG.getIntPtrConstant(0, dl));
16317 return DAG.getBitcast(Op.getValueType(), Res);
16320 SDValue Src1 = Op.getOperand(1);
16321 SDValue Imm = Op.getOperand(2);
16322 SDValue Mask = Op.getOperand(3);
16323 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16324 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16325 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16326 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16329 case CMP_MASK_CC: {
16330 // Comparison intrinsics with masks.
16331 // Example of transformation:
16332 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16333 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16335 // (v8i1 (insert_subvector undef,
16336 // (v2i1 (and (PCMPEQM %a, %b),
16337 // (extract_subvector
16338 // (v8i1 (bitcast %mask)), 0))), 0))))
16339 EVT VT = Op.getOperand(1).getValueType();
16340 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16341 VT.getVectorNumElements());
16342 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16343 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16344 Mask.getValueType().getSizeInBits());
16346 if (IntrData->Type == CMP_MASK_CC) {
16347 SDValue CC = Op.getOperand(3);
16348 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16349 // We specify 2 possible opcodes for intrinsics with rounding modes.
16350 // First, we check if the intrinsic may have non-default rounding mode,
16351 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16352 if (IntrData->Opc1 != 0) {
16353 SDValue Rnd = Op.getOperand(5);
16354 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16355 X86::STATIC_ROUNDING::CUR_DIRECTION)
16356 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16357 Op.getOperand(2), CC, Rnd);
16359 //default rounding mode
16361 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16362 Op.getOperand(2), CC);
16365 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16366 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16369 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16370 DAG.getTargetConstant(0, dl,
16373 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16374 DAG.getUNDEF(BitcastVT), CmpMask,
16375 DAG.getIntPtrConstant(0, dl));
16376 return DAG.getBitcast(Op.getValueType(), Res);
16378 case CMP_MASK_SCALAR_CC: {
16379 SDValue Src1 = Op.getOperand(1);
16380 SDValue Src2 = Op.getOperand(2);
16381 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16382 SDValue Mask = Op.getOperand(4);
16385 if (IntrData->Opc1 != 0) {
16386 SDValue Rnd = Op.getOperand(5);
16387 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16388 X86::STATIC_ROUNDING::CUR_DIRECTION)
16389 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16391 //default rounding mode
16393 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16395 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16396 DAG.getTargetConstant(0, dl,
16400 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16401 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16402 DAG.getValueType(MVT::i1));
16404 case COMI: { // Comparison intrinsics
16405 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16406 SDValue LHS = Op.getOperand(1);
16407 SDValue RHS = Op.getOperand(2);
16408 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16409 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16410 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16411 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16412 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16413 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16416 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16417 Op.getOperand(1), Op.getOperand(2), DAG);
16419 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16420 Op.getSimpleValueType(),
16422 Op.getOperand(2), DAG),
16423 Op.getOperand(4), Op.getOperand(3), Subtarget,
16425 case COMPRESS_EXPAND_IN_REG: {
16426 SDValue Mask = Op.getOperand(3);
16427 SDValue DataToCompress = Op.getOperand(1);
16428 SDValue PassThru = Op.getOperand(2);
16429 if (isAllOnes(Mask)) // return data as is
16430 return Op.getOperand(1);
16432 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16434 Mask, PassThru, Subtarget, DAG);
16437 SDValue Mask = Op.getOperand(3);
16438 EVT VT = Op.getValueType();
16439 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16440 VT.getVectorNumElements());
16441 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16442 Mask.getValueType().getSizeInBits());
16444 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16445 DAG.getBitcast(BitcastVT, Mask),
16446 DAG.getIntPtrConstant(0, dl));
16447 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16456 default: return SDValue(); // Don't custom lower most intrinsics.
16458 case Intrinsic::x86_avx2_permd:
16459 case Intrinsic::x86_avx2_permps:
16460 // Operands intentionally swapped. Mask is last operand to intrinsic,
16461 // but second operand for node/instruction.
16462 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16463 Op.getOperand(2), Op.getOperand(1));
16465 // ptest and testp intrinsics. The intrinsic these come from are designed to
16466 // return an integer value, not just an instruction so lower it to the ptest
16467 // or testp pattern and a setcc for the result.
16468 case Intrinsic::x86_sse41_ptestz:
16469 case Intrinsic::x86_sse41_ptestc:
16470 case Intrinsic::x86_sse41_ptestnzc:
16471 case Intrinsic::x86_avx_ptestz_256:
16472 case Intrinsic::x86_avx_ptestc_256:
16473 case Intrinsic::x86_avx_ptestnzc_256:
16474 case Intrinsic::x86_avx_vtestz_ps:
16475 case Intrinsic::x86_avx_vtestc_ps:
16476 case Intrinsic::x86_avx_vtestnzc_ps:
16477 case Intrinsic::x86_avx_vtestz_pd:
16478 case Intrinsic::x86_avx_vtestc_pd:
16479 case Intrinsic::x86_avx_vtestnzc_pd:
16480 case Intrinsic::x86_avx_vtestz_ps_256:
16481 case Intrinsic::x86_avx_vtestc_ps_256:
16482 case Intrinsic::x86_avx_vtestnzc_ps_256:
16483 case Intrinsic::x86_avx_vtestz_pd_256:
16484 case Intrinsic::x86_avx_vtestc_pd_256:
16485 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16486 bool IsTestPacked = false;
16489 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16490 case Intrinsic::x86_avx_vtestz_ps:
16491 case Intrinsic::x86_avx_vtestz_pd:
16492 case Intrinsic::x86_avx_vtestz_ps_256:
16493 case Intrinsic::x86_avx_vtestz_pd_256:
16494 IsTestPacked = true; // Fallthrough
16495 case Intrinsic::x86_sse41_ptestz:
16496 case Intrinsic::x86_avx_ptestz_256:
16498 X86CC = X86::COND_E;
16500 case Intrinsic::x86_avx_vtestc_ps:
16501 case Intrinsic::x86_avx_vtestc_pd:
16502 case Intrinsic::x86_avx_vtestc_ps_256:
16503 case Intrinsic::x86_avx_vtestc_pd_256:
16504 IsTestPacked = true; // Fallthrough
16505 case Intrinsic::x86_sse41_ptestc:
16506 case Intrinsic::x86_avx_ptestc_256:
16508 X86CC = X86::COND_B;
16510 case Intrinsic::x86_avx_vtestnzc_ps:
16511 case Intrinsic::x86_avx_vtestnzc_pd:
16512 case Intrinsic::x86_avx_vtestnzc_ps_256:
16513 case Intrinsic::x86_avx_vtestnzc_pd_256:
16514 IsTestPacked = true; // Fallthrough
16515 case Intrinsic::x86_sse41_ptestnzc:
16516 case Intrinsic::x86_avx_ptestnzc_256:
16518 X86CC = X86::COND_A;
16522 SDValue LHS = Op.getOperand(1);
16523 SDValue RHS = Op.getOperand(2);
16524 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16525 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16526 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16527 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16528 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16530 case Intrinsic::x86_avx512_kortestz_w:
16531 case Intrinsic::x86_avx512_kortestc_w: {
16532 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16533 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16534 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16535 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16536 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16537 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16538 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16541 case Intrinsic::x86_sse42_pcmpistria128:
16542 case Intrinsic::x86_sse42_pcmpestria128:
16543 case Intrinsic::x86_sse42_pcmpistric128:
16544 case Intrinsic::x86_sse42_pcmpestric128:
16545 case Intrinsic::x86_sse42_pcmpistrio128:
16546 case Intrinsic::x86_sse42_pcmpestrio128:
16547 case Intrinsic::x86_sse42_pcmpistris128:
16548 case Intrinsic::x86_sse42_pcmpestris128:
16549 case Intrinsic::x86_sse42_pcmpistriz128:
16550 case Intrinsic::x86_sse42_pcmpestriz128: {
16554 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16555 case Intrinsic::x86_sse42_pcmpistria128:
16556 Opcode = X86ISD::PCMPISTRI;
16557 X86CC = X86::COND_A;
16559 case Intrinsic::x86_sse42_pcmpestria128:
16560 Opcode = X86ISD::PCMPESTRI;
16561 X86CC = X86::COND_A;
16563 case Intrinsic::x86_sse42_pcmpistric128:
16564 Opcode = X86ISD::PCMPISTRI;
16565 X86CC = X86::COND_B;
16567 case Intrinsic::x86_sse42_pcmpestric128:
16568 Opcode = X86ISD::PCMPESTRI;
16569 X86CC = X86::COND_B;
16571 case Intrinsic::x86_sse42_pcmpistrio128:
16572 Opcode = X86ISD::PCMPISTRI;
16573 X86CC = X86::COND_O;
16575 case Intrinsic::x86_sse42_pcmpestrio128:
16576 Opcode = X86ISD::PCMPESTRI;
16577 X86CC = X86::COND_O;
16579 case Intrinsic::x86_sse42_pcmpistris128:
16580 Opcode = X86ISD::PCMPISTRI;
16581 X86CC = X86::COND_S;
16583 case Intrinsic::x86_sse42_pcmpestris128:
16584 Opcode = X86ISD::PCMPESTRI;
16585 X86CC = X86::COND_S;
16587 case Intrinsic::x86_sse42_pcmpistriz128:
16588 Opcode = X86ISD::PCMPISTRI;
16589 X86CC = X86::COND_E;
16591 case Intrinsic::x86_sse42_pcmpestriz128:
16592 Opcode = X86ISD::PCMPESTRI;
16593 X86CC = X86::COND_E;
16596 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16597 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16598 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16599 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16600 DAG.getConstant(X86CC, dl, MVT::i8),
16601 SDValue(PCMP.getNode(), 1));
16602 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16605 case Intrinsic::x86_sse42_pcmpistri128:
16606 case Intrinsic::x86_sse42_pcmpestri128: {
16608 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16609 Opcode = X86ISD::PCMPISTRI;
16611 Opcode = X86ISD::PCMPESTRI;
16613 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16614 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16615 return DAG.getNode(Opcode, dl, VTs, NewOps);
16618 case Intrinsic::x86_seh_lsda: {
16619 // Compute the symbol for the LSDA. We know it'll get emitted later.
16620 MachineFunction &MF = DAG.getMachineFunction();
16621 SDValue Op1 = Op.getOperand(1);
16622 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16623 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16624 GlobalValue::getRealLinkageName(Fn->getName()));
16626 // Generate a simple absolute symbol reference. This intrinsic is only
16627 // supported on 32-bit Windows, which isn't PIC.
16628 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16629 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16632 case Intrinsic::x86_seh_recoverfp: {
16633 SDValue FnOp = Op.getOperand(1);
16634 SDValue IncomingFPOp = Op.getOperand(2);
16635 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16636 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16638 report_fatal_error(
16639 "llvm.x86.seh.recoverfp must take a function as the first argument");
16640 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16643 case Intrinsic::localaddress: {
16644 // Returns one of the stack, base, or frame pointer registers, depending on
16645 // which is used to reference local variables.
16646 MachineFunction &MF = DAG.getMachineFunction();
16647 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16649 if (RegInfo->hasBasePointer(MF))
16650 Reg = RegInfo->getBaseRegister();
16651 else // This function handles the SP or FP case.
16652 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16653 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16658 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16659 SDValue Src, SDValue Mask, SDValue Base,
16660 SDValue Index, SDValue ScaleOp, SDValue Chain,
16661 const X86Subtarget * Subtarget) {
16663 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16665 llvm_unreachable("Invalid scale type");
16666 unsigned ScaleVal = C->getZExtValue();
16667 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16668 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16670 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16671 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16672 Index.getSimpleValueType().getVectorNumElements());
16674 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16676 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16678 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16679 Mask.getValueType().getSizeInBits());
16681 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16682 // are extracted by EXTRACT_SUBVECTOR.
16683 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16684 DAG.getBitcast(BitcastVT, Mask),
16685 DAG.getIntPtrConstant(0, dl));
16687 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16688 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16689 SDValue Segment = DAG.getRegister(0, MVT::i32);
16690 if (Src.getOpcode() == ISD::UNDEF)
16691 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16692 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16693 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16694 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16695 return DAG.getMergeValues(RetOps, dl);
16698 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16699 SDValue Src, SDValue Mask, SDValue Base,
16700 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16702 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16704 llvm_unreachable("Invalid scale type");
16705 unsigned ScaleVal = C->getZExtValue();
16706 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16707 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16709 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16710 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16711 SDValue Segment = DAG.getRegister(0, MVT::i32);
16712 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16713 Index.getSimpleValueType().getVectorNumElements());
16715 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16717 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16719 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16720 Mask.getValueType().getSizeInBits());
16722 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16723 // are extracted by EXTRACT_SUBVECTOR.
16724 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16725 DAG.getBitcast(BitcastVT, Mask),
16726 DAG.getIntPtrConstant(0, dl));
16728 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16729 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16730 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16731 return SDValue(Res, 1);
16734 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16735 SDValue Mask, SDValue Base, SDValue Index,
16736 SDValue ScaleOp, SDValue Chain) {
16738 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16739 assert(C && "Invalid scale type");
16740 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16741 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16742 SDValue Segment = DAG.getRegister(0, MVT::i32);
16744 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16746 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16748 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16750 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16751 //SDVTList VTs = DAG.getVTList(MVT::Other);
16752 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16753 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16754 return SDValue(Res, 0);
16757 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16758 // read performance monitor counters (x86_rdpmc).
16759 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16760 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16761 SmallVectorImpl<SDValue> &Results) {
16762 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16763 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16766 // The ECX register is used to select the index of the performance counter
16768 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16770 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16772 // Reads the content of a 64-bit performance counter and returns it in the
16773 // registers EDX:EAX.
16774 if (Subtarget->is64Bit()) {
16775 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16776 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16779 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16780 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16783 Chain = HI.getValue(1);
16785 if (Subtarget->is64Bit()) {
16786 // The EAX register is loaded with the low-order 32 bits. The EDX register
16787 // is loaded with the supported high-order bits of the counter.
16788 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16789 DAG.getConstant(32, DL, MVT::i8));
16790 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16791 Results.push_back(Chain);
16795 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16796 SDValue Ops[] = { LO, HI };
16797 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16798 Results.push_back(Pair);
16799 Results.push_back(Chain);
16802 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16803 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16804 // also used to custom lower READCYCLECOUNTER nodes.
16805 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16806 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16807 SmallVectorImpl<SDValue> &Results) {
16808 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16809 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16812 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16813 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16814 // and the EAX register is loaded with the low-order 32 bits.
16815 if (Subtarget->is64Bit()) {
16816 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16817 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16820 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16821 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16824 SDValue Chain = HI.getValue(1);
16826 if (Opcode == X86ISD::RDTSCP_DAG) {
16827 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16829 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16830 // the ECX register. Add 'ecx' explicitly to the chain.
16831 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16833 // Explicitly store the content of ECX at the location passed in input
16834 // to the 'rdtscp' intrinsic.
16835 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16836 MachinePointerInfo(), false, false, 0);
16839 if (Subtarget->is64Bit()) {
16840 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16841 // the EAX register is loaded with the low-order 32 bits.
16842 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16843 DAG.getConstant(32, DL, MVT::i8));
16844 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16845 Results.push_back(Chain);
16849 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16850 SDValue Ops[] = { LO, HI };
16851 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16852 Results.push_back(Pair);
16853 Results.push_back(Chain);
16856 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16857 SelectionDAG &DAG) {
16858 SmallVector<SDValue, 2> Results;
16860 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16862 return DAG.getMergeValues(Results, DL);
16865 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16866 SelectionDAG &DAG) {
16867 MachineFunction &MF = DAG.getMachineFunction();
16868 const Function *Fn = MF.getFunction();
16870 SDValue Chain = Op.getOperand(0);
16872 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16873 "using llvm.x86.seh.restoreframe requires a frame pointer");
16875 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16876 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16878 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16879 unsigned FrameReg =
16880 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16881 unsigned SPReg = RegInfo->getStackRegister();
16882 unsigned SlotSize = RegInfo->getSlotSize();
16884 // Get incoming EBP.
16885 SDValue IncomingEBP =
16886 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16888 // SP is saved in the first field of every registration node, so load
16889 // [EBP-RegNodeSize] into SP.
16890 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16891 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16892 DAG.getConstant(-RegNodeSize, dl, VT));
16894 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16895 false, VT.getScalarSizeInBits() / 8);
16896 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16898 if (!RegInfo->needsStackRealignment(MF)) {
16899 // Adjust EBP to point back to the original frame position.
16900 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16901 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16903 assert(RegInfo->hasBasePointer(MF) &&
16904 "functions with Win32 EH must use frame or base pointer register");
16906 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16907 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16908 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16910 // Reload the spilled EBP value, now that the stack and base pointers are
16912 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16913 X86FI->setHasSEHFramePtrSave(true);
16914 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16915 X86FI->setSEHFramePtrSaveIndex(FI);
16916 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16917 MachinePointerInfo(), false, false, false,
16918 VT.getScalarSizeInBits() / 8);
16919 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16925 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16926 /// return truncate Store/MaskedStore Node
16927 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16931 SDValue Mask = Op.getOperand(4);
16932 SDValue DataToTruncate = Op.getOperand(3);
16933 SDValue Addr = Op.getOperand(2);
16934 SDValue Chain = Op.getOperand(0);
16936 EVT VT = DataToTruncate.getValueType();
16937 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16938 ElementType, VT.getVectorNumElements());
16940 if (isAllOnes(Mask)) // return just a truncate store
16941 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16942 MachinePointerInfo(), SVT, false, false,
16943 SVT.getScalarSizeInBits()/8);
16945 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16946 MVT::i1, VT.getVectorNumElements());
16947 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16948 Mask.getValueType().getSizeInBits());
16949 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16950 // are extracted by EXTRACT_SUBVECTOR.
16951 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16952 DAG.getBitcast(BitcastVT, Mask),
16953 DAG.getIntPtrConstant(0, dl));
16955 MachineMemOperand *MMO = DAG.getMachineFunction().
16956 getMachineMemOperand(MachinePointerInfo(),
16957 MachineMemOperand::MOStore, SVT.getStoreSize(),
16958 SVT.getScalarSizeInBits()/8);
16960 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16961 VMask, SVT, MMO, true);
16964 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16965 SelectionDAG &DAG) {
16966 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16968 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16970 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16971 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16976 switch(IntrData->Type) {
16978 llvm_unreachable("Unknown Intrinsic Type");
16982 // Emit the node with the right value type.
16983 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16984 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16986 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16987 // Otherwise return the value from Rand, which is always 0, casted to i32.
16988 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16989 DAG.getConstant(1, dl, Op->getValueType(1)),
16990 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16991 SDValue(Result.getNode(), 1) };
16992 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16993 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16996 // Return { result, isValid, chain }.
16997 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16998 SDValue(Result.getNode(), 2));
17001 //gather(v1, mask, index, base, scale);
17002 SDValue Chain = Op.getOperand(0);
17003 SDValue Src = Op.getOperand(2);
17004 SDValue Base = Op.getOperand(3);
17005 SDValue Index = Op.getOperand(4);
17006 SDValue Mask = Op.getOperand(5);
17007 SDValue Scale = Op.getOperand(6);
17008 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17012 //scatter(base, mask, index, v1, scale);
17013 SDValue Chain = Op.getOperand(0);
17014 SDValue Base = Op.getOperand(2);
17015 SDValue Mask = Op.getOperand(3);
17016 SDValue Index = Op.getOperand(4);
17017 SDValue Src = Op.getOperand(5);
17018 SDValue Scale = Op.getOperand(6);
17019 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17023 SDValue Hint = Op.getOperand(6);
17024 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17025 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17026 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17027 SDValue Chain = Op.getOperand(0);
17028 SDValue Mask = Op.getOperand(2);
17029 SDValue Index = Op.getOperand(3);
17030 SDValue Base = Op.getOperand(4);
17031 SDValue Scale = Op.getOperand(5);
17032 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17034 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17036 SmallVector<SDValue, 2> Results;
17037 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17039 return DAG.getMergeValues(Results, dl);
17041 // Read Performance Monitoring Counters.
17043 SmallVector<SDValue, 2> Results;
17044 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17045 return DAG.getMergeValues(Results, dl);
17047 // XTEST intrinsics.
17049 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17050 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17051 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17052 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17054 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17055 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17056 Ret, SDValue(InTrans.getNode(), 1));
17060 SmallVector<SDValue, 2> Results;
17061 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17062 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17063 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17064 DAG.getConstant(-1, dl, MVT::i8));
17065 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17066 Op.getOperand(4), GenCF.getValue(1));
17067 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17068 Op.getOperand(5), MachinePointerInfo(),
17070 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17071 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17073 Results.push_back(SetCC);
17074 Results.push_back(Store);
17075 return DAG.getMergeValues(Results, dl);
17077 case COMPRESS_TO_MEM: {
17079 SDValue Mask = Op.getOperand(4);
17080 SDValue DataToCompress = Op.getOperand(3);
17081 SDValue Addr = Op.getOperand(2);
17082 SDValue Chain = Op.getOperand(0);
17084 EVT VT = DataToCompress.getValueType();
17085 if (isAllOnes(Mask)) // return just a store
17086 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17087 MachinePointerInfo(), false, false,
17088 VT.getScalarSizeInBits()/8);
17090 SDValue Compressed =
17091 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17092 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17093 return DAG.getStore(Chain, dl, Compressed, Addr,
17094 MachinePointerInfo(), false, false,
17095 VT.getScalarSizeInBits()/8);
17097 case TRUNCATE_TO_MEM_VI8:
17098 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17099 case TRUNCATE_TO_MEM_VI16:
17100 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17101 case TRUNCATE_TO_MEM_VI32:
17102 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17103 case EXPAND_FROM_MEM: {
17105 SDValue Mask = Op.getOperand(4);
17106 SDValue PassThru = Op.getOperand(3);
17107 SDValue Addr = Op.getOperand(2);
17108 SDValue Chain = Op.getOperand(0);
17109 EVT VT = Op.getValueType();
17111 if (isAllOnes(Mask)) // return just a load
17112 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17113 false, VT.getScalarSizeInBits()/8);
17115 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17116 false, false, false,
17117 VT.getScalarSizeInBits()/8);
17119 SDValue Results[] = {
17120 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17121 Mask, PassThru, Subtarget, DAG), Chain};
17122 return DAG.getMergeValues(Results, dl);
17127 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17128 SelectionDAG &DAG) const {
17129 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17130 MFI->setReturnAddressIsTaken(true);
17132 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17135 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17137 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17140 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17141 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17142 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17143 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17144 DAG.getNode(ISD::ADD, dl, PtrVT,
17145 FrameAddr, Offset),
17146 MachinePointerInfo(), false, false, false, 0);
17149 // Just load the return address.
17150 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17151 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17152 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17155 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17156 MachineFunction &MF = DAG.getMachineFunction();
17157 MachineFrameInfo *MFI = MF.getFrameInfo();
17158 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17159 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17160 EVT VT = Op.getValueType();
17162 MFI->setFrameAddressIsTaken(true);
17164 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17165 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17166 // is not possible to crawl up the stack without looking at the unwind codes
17168 int FrameAddrIndex = FuncInfo->getFAIndex();
17169 if (!FrameAddrIndex) {
17170 // Set up a frame object for the return address.
17171 unsigned SlotSize = RegInfo->getSlotSize();
17172 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17173 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17174 FuncInfo->setFAIndex(FrameAddrIndex);
17176 return DAG.getFrameIndex(FrameAddrIndex, VT);
17179 unsigned FrameReg =
17180 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17181 SDLoc dl(Op); // FIXME probably not meaningful
17182 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17183 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17184 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17185 "Invalid Frame Register!");
17186 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17188 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17189 MachinePointerInfo(),
17190 false, false, false, 0);
17194 // FIXME? Maybe this could be a TableGen attribute on some registers and
17195 // this table could be generated automatically from RegInfo.
17196 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17197 SelectionDAG &DAG) const {
17198 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17199 const MachineFunction &MF = DAG.getMachineFunction();
17201 unsigned Reg = StringSwitch<unsigned>(RegName)
17202 .Case("esp", X86::ESP)
17203 .Case("rsp", X86::RSP)
17204 .Case("ebp", X86::EBP)
17205 .Case("rbp", X86::RBP)
17208 if (Reg == X86::EBP || Reg == X86::RBP) {
17209 if (!TFI.hasFP(MF))
17210 report_fatal_error("register " + StringRef(RegName) +
17211 " is allocatable: function has no frame pointer");
17214 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17215 unsigned FrameReg =
17216 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17217 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17218 "Invalid Frame Register!");
17226 report_fatal_error("Invalid register name global variable");
17229 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17230 SelectionDAG &DAG) const {
17231 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17232 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17235 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17236 SDValue Chain = Op.getOperand(0);
17237 SDValue Offset = Op.getOperand(1);
17238 SDValue Handler = Op.getOperand(2);
17241 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17242 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17243 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17244 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17245 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17246 "Invalid Frame Register!");
17247 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17248 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17250 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17251 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17253 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17254 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17256 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17258 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17259 DAG.getRegister(StoreAddrReg, PtrVT));
17262 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17263 SelectionDAG &DAG) const {
17265 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17266 DAG.getVTList(MVT::i32, MVT::Other),
17267 Op.getOperand(0), Op.getOperand(1));
17270 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17271 SelectionDAG &DAG) const {
17273 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17274 Op.getOperand(0), Op.getOperand(1));
17277 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17278 return Op.getOperand(0);
17281 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17282 SelectionDAG &DAG) const {
17283 SDValue Root = Op.getOperand(0);
17284 SDValue Trmp = Op.getOperand(1); // trampoline
17285 SDValue FPtr = Op.getOperand(2); // nested function
17286 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17289 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17290 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17292 if (Subtarget->is64Bit()) {
17293 SDValue OutChains[6];
17295 // Large code-model.
17296 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17297 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17299 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17300 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17302 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17304 // Load the pointer to the nested function into R11.
17305 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17306 SDValue Addr = Trmp;
17307 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17308 Addr, MachinePointerInfo(TrmpAddr),
17311 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17312 DAG.getConstant(2, dl, MVT::i64));
17313 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17314 MachinePointerInfo(TrmpAddr, 2),
17317 // Load the 'nest' parameter value into R10.
17318 // R10 is specified in X86CallingConv.td
17319 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17320 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17321 DAG.getConstant(10, dl, MVT::i64));
17322 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17323 Addr, MachinePointerInfo(TrmpAddr, 10),
17326 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17327 DAG.getConstant(12, dl, MVT::i64));
17328 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17329 MachinePointerInfo(TrmpAddr, 12),
17332 // Jump to the nested function.
17333 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17334 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17335 DAG.getConstant(20, dl, MVT::i64));
17336 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17337 Addr, MachinePointerInfo(TrmpAddr, 20),
17340 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17341 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17342 DAG.getConstant(22, dl, MVT::i64));
17343 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17344 Addr, MachinePointerInfo(TrmpAddr, 22),
17347 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17349 const Function *Func =
17350 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17351 CallingConv::ID CC = Func->getCallingConv();
17356 llvm_unreachable("Unsupported calling convention");
17357 case CallingConv::C:
17358 case CallingConv::X86_StdCall: {
17359 // Pass 'nest' parameter in ECX.
17360 // Must be kept in sync with X86CallingConv.td
17361 NestReg = X86::ECX;
17363 // Check that ECX wasn't needed by an 'inreg' parameter.
17364 FunctionType *FTy = Func->getFunctionType();
17365 const AttributeSet &Attrs = Func->getAttributes();
17367 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17368 unsigned InRegCount = 0;
17371 for (FunctionType::param_iterator I = FTy->param_begin(),
17372 E = FTy->param_end(); I != E; ++I, ++Idx)
17373 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17374 auto &DL = DAG.getDataLayout();
17375 // FIXME: should only count parameters that are lowered to integers.
17376 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17379 if (InRegCount > 2) {
17380 report_fatal_error("Nest register in use - reduce number of inreg"
17386 case CallingConv::X86_FastCall:
17387 case CallingConv::X86_ThisCall:
17388 case CallingConv::Fast:
17389 // Pass 'nest' parameter in EAX.
17390 // Must be kept in sync with X86CallingConv.td
17391 NestReg = X86::EAX;
17395 SDValue OutChains[4];
17396 SDValue Addr, Disp;
17398 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17399 DAG.getConstant(10, dl, MVT::i32));
17400 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17402 // This is storing the opcode for MOV32ri.
17403 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17404 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17405 OutChains[0] = DAG.getStore(Root, dl,
17406 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17407 Trmp, MachinePointerInfo(TrmpAddr),
17410 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17411 DAG.getConstant(1, dl, MVT::i32));
17412 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17413 MachinePointerInfo(TrmpAddr, 1),
17416 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17417 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17418 DAG.getConstant(5, dl, MVT::i32));
17419 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17420 Addr, MachinePointerInfo(TrmpAddr, 5),
17423 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17424 DAG.getConstant(6, dl, MVT::i32));
17425 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17426 MachinePointerInfo(TrmpAddr, 6),
17429 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17433 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17434 SelectionDAG &DAG) const {
17436 The rounding mode is in bits 11:10 of FPSR, and has the following
17438 00 Round to nearest
17443 FLT_ROUNDS, on the other hand, expects the following:
17450 To perform the conversion, we do:
17451 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17454 MachineFunction &MF = DAG.getMachineFunction();
17455 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17456 unsigned StackAlignment = TFI.getStackAlignment();
17457 MVT VT = Op.getSimpleValueType();
17460 // Save FP Control Word to stack slot
17461 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17462 SDValue StackSlot =
17463 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17465 MachineMemOperand *MMO =
17466 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17467 MachineMemOperand::MOStore, 2, 2);
17469 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17470 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17471 DAG.getVTList(MVT::Other),
17472 Ops, MVT::i16, MMO);
17474 // Load FP Control Word from stack slot
17475 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17476 MachinePointerInfo(), false, false, false, 0);
17478 // Transform as necessary
17480 DAG.getNode(ISD::SRL, DL, MVT::i16,
17481 DAG.getNode(ISD::AND, DL, MVT::i16,
17482 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17483 DAG.getConstant(11, DL, MVT::i8));
17485 DAG.getNode(ISD::SRL, DL, MVT::i16,
17486 DAG.getNode(ISD::AND, DL, MVT::i16,
17487 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17488 DAG.getConstant(9, DL, MVT::i8));
17491 DAG.getNode(ISD::AND, DL, MVT::i16,
17492 DAG.getNode(ISD::ADD, DL, MVT::i16,
17493 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17494 DAG.getConstant(1, DL, MVT::i16)),
17495 DAG.getConstant(3, DL, MVT::i16));
17497 return DAG.getNode((VT.getSizeInBits() < 16 ?
17498 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17501 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17503 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17504 // to 512-bit vector.
17505 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17506 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17507 // split the vector, perform operation on it's Lo a Hi part and
17508 // concatenate the results.
17509 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17511 MVT VT = Op.getSimpleValueType();
17512 MVT EltVT = VT.getVectorElementType();
17513 unsigned NumElems = VT.getVectorNumElements();
17515 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17516 // Extend to 512 bit vector.
17517 assert((VT.is256BitVector() || VT.is128BitVector()) &&
17518 "Unsupported value type for operation");
17520 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17521 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17522 DAG.getUNDEF(NewVT),
17524 DAG.getIntPtrConstant(0, dl));
17525 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17527 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17528 DAG.getIntPtrConstant(0, dl));
17531 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17532 "Unsupported element type");
17534 if (16 < NumElems) {
17535 // Split vector, it's Lo and Hi parts will be handled in next iteration.
17537 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17538 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17540 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17541 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17543 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17546 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17548 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17549 "Unsupported value type for operation");
17551 // Use native supported vector instruction vplzcntd.
17552 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17553 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17554 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17555 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17557 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17560 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17561 SelectionDAG &DAG) {
17562 MVT VT = Op.getSimpleValueType();
17564 unsigned NumBits = VT.getSizeInBits();
17567 if (VT.isVector() && Subtarget->hasAVX512())
17568 return LowerVectorCTLZ_AVX512(Op, DAG);
17570 Op = Op.getOperand(0);
17571 if (VT == MVT::i8) {
17572 // Zero extend to i32 since there is not an i8 bsr.
17574 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17577 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17578 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17579 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17581 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17584 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17585 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17588 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17590 // Finally xor with NumBits-1.
17591 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17592 DAG.getConstant(NumBits - 1, dl, OpVT));
17595 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17599 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17600 SelectionDAG &DAG) {
17601 MVT VT = Op.getSimpleValueType();
17603 unsigned NumBits = VT.getSizeInBits();
17606 if (VT.isVector() && Subtarget->hasAVX512())
17607 return LowerVectorCTLZ_AVX512(Op, DAG);
17609 Op = Op.getOperand(0);
17610 if (VT == MVT::i8) {
17611 // Zero extend to i32 since there is not an i8 bsr.
17613 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17616 // Issue a bsr (scan bits in reverse).
17617 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17618 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17620 // And xor with NumBits-1.
17621 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17622 DAG.getConstant(NumBits - 1, dl, OpVT));
17625 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17629 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17630 MVT VT = Op.getSimpleValueType();
17631 unsigned NumBits = VT.getScalarSizeInBits();
17634 if (VT.isVector()) {
17635 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17637 SDValue N0 = Op.getOperand(0);
17638 SDValue Zero = DAG.getConstant(0, dl, VT);
17640 // lsb(x) = (x & -x)
17641 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17642 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17644 // cttz_undef(x) = (width - 1) - ctlz(lsb)
17645 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17646 TLI.isOperationLegal(ISD::CTLZ, VT)) {
17647 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17648 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17649 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17652 // cttz(x) = ctpop(lsb - 1)
17653 SDValue One = DAG.getConstant(1, dl, VT);
17654 return DAG.getNode(ISD::CTPOP, dl, VT,
17655 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17658 assert(Op.getOpcode() == ISD::CTTZ &&
17659 "Only scalar CTTZ requires custom lowering");
17661 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17662 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17663 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17665 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17668 DAG.getConstant(NumBits, dl, VT),
17669 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17672 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17675 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17676 // ones, and then concatenate the result back.
17677 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17678 MVT VT = Op.getSimpleValueType();
17680 assert(VT.is256BitVector() && VT.isInteger() &&
17681 "Unsupported value type for operation");
17683 unsigned NumElems = VT.getVectorNumElements();
17686 // Extract the LHS vectors
17687 SDValue LHS = Op.getOperand(0);
17688 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17689 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17691 // Extract the RHS vectors
17692 SDValue RHS = Op.getOperand(1);
17693 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17694 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17696 MVT EltVT = VT.getVectorElementType();
17697 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17699 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17700 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17701 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17704 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17705 if (Op.getValueType() == MVT::i1)
17706 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17707 Op.getOperand(0), Op.getOperand(1));
17708 assert(Op.getSimpleValueType().is256BitVector() &&
17709 Op.getSimpleValueType().isInteger() &&
17710 "Only handle AVX 256-bit vector integer operation");
17711 return Lower256IntArith(Op, DAG);
17714 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17715 if (Op.getValueType() == MVT::i1)
17716 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17717 Op.getOperand(0), Op.getOperand(1));
17718 assert(Op.getSimpleValueType().is256BitVector() &&
17719 Op.getSimpleValueType().isInteger() &&
17720 "Only handle AVX 256-bit vector integer operation");
17721 return Lower256IntArith(Op, DAG);
17724 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17725 assert(Op.getSimpleValueType().is256BitVector() &&
17726 Op.getSimpleValueType().isInteger() &&
17727 "Only handle AVX 256-bit vector integer operation");
17728 return Lower256IntArith(Op, DAG);
17731 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17732 SelectionDAG &DAG) {
17734 MVT VT = Op.getSimpleValueType();
17737 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17739 // Decompose 256-bit ops into smaller 128-bit ops.
17740 if (VT.is256BitVector() && !Subtarget->hasInt256())
17741 return Lower256IntArith(Op, DAG);
17743 SDValue A = Op.getOperand(0);
17744 SDValue B = Op.getOperand(1);
17746 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17747 // pairs, multiply and truncate.
17748 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17749 if (Subtarget->hasInt256()) {
17750 if (VT == MVT::v32i8) {
17751 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17752 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17753 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17754 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17755 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17756 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17757 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17758 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17759 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17760 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17763 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17764 return DAG.getNode(
17765 ISD::TRUNCATE, dl, VT,
17766 DAG.getNode(ISD::MUL, dl, ExVT,
17767 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17768 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17771 assert(VT == MVT::v16i8 &&
17772 "Pre-AVX2 support only supports v16i8 multiplication");
17773 MVT ExVT = MVT::v8i16;
17775 // Extract the lo parts and sign extend to i16
17777 if (Subtarget->hasSSE41()) {
17778 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17779 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17781 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17782 -1, 4, -1, 5, -1, 6, -1, 7};
17783 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17784 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17785 ALo = DAG.getBitcast(ExVT, ALo);
17786 BLo = DAG.getBitcast(ExVT, BLo);
17787 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17788 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17791 // Extract the hi parts and sign extend to i16
17793 if (Subtarget->hasSSE41()) {
17794 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17795 -1, -1, -1, -1, -1, -1, -1, -1};
17796 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17797 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17798 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17799 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17801 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17802 -1, 12, -1, 13, -1, 14, -1, 15};
17803 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17804 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17805 AHi = DAG.getBitcast(ExVT, AHi);
17806 BHi = DAG.getBitcast(ExVT, BHi);
17807 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17808 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17811 // Multiply, mask the lower 8bits of the lo/hi results and pack
17812 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17813 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17814 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17815 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17816 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17819 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17820 if (VT == MVT::v4i32) {
17821 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17822 "Should not custom lower when pmuldq is available!");
17824 // Extract the odd parts.
17825 static const int UnpackMask[] = { 1, -1, 3, -1 };
17826 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17827 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17829 // Multiply the even parts.
17830 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17831 // Now multiply odd parts.
17832 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17834 Evens = DAG.getBitcast(VT, Evens);
17835 Odds = DAG.getBitcast(VT, Odds);
17837 // Merge the two vectors back together with a shuffle. This expands into 2
17839 static const int ShufMask[] = { 0, 4, 2, 6 };
17840 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17843 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17844 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17846 // Ahi = psrlqi(a, 32);
17847 // Bhi = psrlqi(b, 32);
17849 // AloBlo = pmuludq(a, b);
17850 // AloBhi = pmuludq(a, Bhi);
17851 // AhiBlo = pmuludq(Ahi, b);
17853 // AloBhi = psllqi(AloBhi, 32);
17854 // AhiBlo = psllqi(AhiBlo, 32);
17855 // return AloBlo + AloBhi + AhiBlo;
17857 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17858 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17860 SDValue AhiBlo = Ahi;
17861 SDValue AloBhi = Bhi;
17862 // Bit cast to 32-bit vectors for MULUDQ
17863 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17864 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17865 A = DAG.getBitcast(MulVT, A);
17866 B = DAG.getBitcast(MulVT, B);
17867 Ahi = DAG.getBitcast(MulVT, Ahi);
17868 Bhi = DAG.getBitcast(MulVT, Bhi);
17870 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17871 // After shifting right const values the result may be all-zero.
17872 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17873 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17874 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17876 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17877 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17878 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17881 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17882 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17885 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17886 assert(Subtarget->isTargetWin64() && "Unexpected target");
17887 EVT VT = Op.getValueType();
17888 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17889 "Unexpected return type for lowering");
17893 switch (Op->getOpcode()) {
17894 default: llvm_unreachable("Unexpected request for libcall!");
17895 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17896 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17897 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17898 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17899 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17900 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17904 SDValue InChain = DAG.getEntryNode();
17906 TargetLowering::ArgListTy Args;
17907 TargetLowering::ArgListEntry Entry;
17908 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17909 EVT ArgVT = Op->getOperand(i).getValueType();
17910 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17911 "Unexpected argument type for lowering");
17912 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17913 Entry.Node = StackPtr;
17914 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17916 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17917 Entry.Ty = PointerType::get(ArgTy,0);
17918 Entry.isSExt = false;
17919 Entry.isZExt = false;
17920 Args.push_back(Entry);
17923 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17924 getPointerTy(DAG.getDataLayout()));
17926 TargetLowering::CallLoweringInfo CLI(DAG);
17927 CLI.setDebugLoc(dl).setChain(InChain)
17928 .setCallee(getLibcallCallingConv(LC),
17929 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17930 Callee, std::move(Args), 0)
17931 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17933 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17934 return DAG.getBitcast(VT, CallInfo.first);
17937 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17938 SelectionDAG &DAG) {
17939 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17940 EVT VT = Op0.getValueType();
17943 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17944 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17946 // PMULxD operations multiply each even value (starting at 0) of LHS with
17947 // the related value of RHS and produce a widen result.
17948 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17949 // => <2 x i64> <ae|cg>
17951 // In other word, to have all the results, we need to perform two PMULxD:
17952 // 1. one with the even values.
17953 // 2. one with the odd values.
17954 // To achieve #2, with need to place the odd values at an even position.
17956 // Place the odd value at an even position (basically, shift all values 1
17957 // step to the left):
17958 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17959 // <a|b|c|d> => <b|undef|d|undef>
17960 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17961 // <e|f|g|h> => <f|undef|h|undef>
17962 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17964 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17966 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17967 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17969 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17970 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17971 // => <2 x i64> <ae|cg>
17972 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17973 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17974 // => <2 x i64> <bf|dh>
17975 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17977 // Shuffle it back into the right order.
17978 SDValue Highs, Lows;
17979 if (VT == MVT::v8i32) {
17980 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17981 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17982 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17983 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17985 const int HighMask[] = {1, 5, 3, 7};
17986 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17987 const int LowMask[] = {0, 4, 2, 6};
17988 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17991 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17992 // unsigned multiply.
17993 if (IsSigned && !Subtarget->hasSSE41()) {
17994 SDValue ShAmt = DAG.getConstant(
17996 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17997 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17998 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17999 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18000 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18002 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18003 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18006 // The first result of MUL_LOHI is actually the low value, followed by the
18008 SDValue Ops[] = {Lows, Highs};
18009 return DAG.getMergeValues(Ops, dl);
18012 // Return true if the required (according to Opcode) shift-imm form is natively
18013 // supported by the Subtarget
18014 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18016 if (VT.getScalarSizeInBits() < 16)
18019 if (VT.is512BitVector() &&
18020 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18023 bool LShift = VT.is128BitVector() ||
18024 (VT.is256BitVector() && Subtarget->hasInt256());
18026 bool AShift = LShift && (Subtarget->hasVLX() ||
18027 (VT != MVT::v2i64 && VT != MVT::v4i64));
18028 return (Opcode == ISD::SRA) ? AShift : LShift;
18031 // The shift amount is a variable, but it is the same for all vector lanes.
18032 // These instructions are defined together with shift-immediate.
18034 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18036 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18039 // Return true if the required (according to Opcode) variable-shift form is
18040 // natively supported by the Subtarget
18041 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18044 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18047 // vXi16 supported only on AVX-512, BWI
18048 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18051 if (VT.is512BitVector() || Subtarget->hasVLX())
18054 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18055 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18056 return (Opcode == ISD::SRA) ? AShift : LShift;
18059 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18060 const X86Subtarget *Subtarget) {
18061 MVT VT = Op.getSimpleValueType();
18063 SDValue R = Op.getOperand(0);
18064 SDValue Amt = Op.getOperand(1);
18066 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18067 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18069 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18070 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18071 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18072 SDValue Ex = DAG.getBitcast(ExVT, R);
18074 if (ShiftAmt >= 32) {
18075 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18077 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18078 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18079 ShiftAmt - 32, DAG);
18080 if (VT == MVT::v2i64)
18081 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18082 if (VT == MVT::v4i64)
18083 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18084 {9, 1, 11, 3, 13, 5, 15, 7});
18086 // SRA upper i32, SHL whole i64 and select lower i32.
18087 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18090 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18091 Lower = DAG.getBitcast(ExVT, Lower);
18092 if (VT == MVT::v2i64)
18093 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18094 if (VT == MVT::v4i64)
18095 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18096 {8, 1, 10, 3, 12, 5, 14, 7});
18098 return DAG.getBitcast(VT, Ex);
18101 // Optimize shl/srl/sra with constant shift amount.
18102 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18103 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18104 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18106 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18107 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18109 // i64 SRA needs to be performed as partial shifts.
18110 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18111 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18112 return ArithmeticShiftRight64(ShiftAmt);
18114 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18115 unsigned NumElts = VT.getVectorNumElements();
18116 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18118 // Simple i8 add case
18119 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18120 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18122 // ashr(R, 7) === cmp_slt(R, 0)
18123 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18124 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18125 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18128 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18129 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18132 if (Op.getOpcode() == ISD::SHL) {
18133 // Make a large shift.
18134 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18136 SHL = DAG.getBitcast(VT, SHL);
18137 // Zero out the rightmost bits.
18138 SmallVector<SDValue, 32> V(
18139 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18140 return DAG.getNode(ISD::AND, dl, VT, SHL,
18141 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18143 if (Op.getOpcode() == ISD::SRL) {
18144 // Make a large shift.
18145 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18147 SRL = DAG.getBitcast(VT, SRL);
18148 // Zero out the leftmost bits.
18149 SmallVector<SDValue, 32> V(
18150 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18151 return DAG.getNode(ISD::AND, dl, VT, SRL,
18152 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18154 if (Op.getOpcode() == ISD::SRA) {
18155 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18156 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18157 SmallVector<SDValue, 32> V(NumElts,
18158 DAG.getConstant(128 >> ShiftAmt, dl,
18160 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18161 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18162 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18165 llvm_unreachable("Unknown shift opcode.");
18170 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18171 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18172 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18174 // Peek through any splat that was introduced for i64 shift vectorization.
18175 int SplatIndex = -1;
18176 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18177 if (SVN->isSplat()) {
18178 SplatIndex = SVN->getSplatIndex();
18179 Amt = Amt.getOperand(0);
18180 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18181 "Splat shuffle referencing second operand");
18184 if (Amt.getOpcode() != ISD::BITCAST ||
18185 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18188 Amt = Amt.getOperand(0);
18189 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18190 VT.getVectorNumElements();
18191 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18192 uint64_t ShiftAmt = 0;
18193 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18194 for (unsigned i = 0; i != Ratio; ++i) {
18195 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18199 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18202 // Check remaining shift amounts (if not a splat).
18203 if (SplatIndex < 0) {
18204 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18205 uint64_t ShAmt = 0;
18206 for (unsigned j = 0; j != Ratio; ++j) {
18207 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18211 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18213 if (ShAmt != ShiftAmt)
18218 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18219 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18221 if (Op.getOpcode() == ISD::SRA)
18222 return ArithmeticShiftRight64(ShiftAmt);
18228 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18229 const X86Subtarget* Subtarget) {
18230 MVT VT = Op.getSimpleValueType();
18232 SDValue R = Op.getOperand(0);
18233 SDValue Amt = Op.getOperand(1);
18235 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18236 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18238 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18239 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18241 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18243 EVT EltVT = VT.getVectorElementType();
18245 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18246 // Check if this build_vector node is doing a splat.
18247 // If so, then set BaseShAmt equal to the splat value.
18248 BaseShAmt = BV->getSplatValue();
18249 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18250 BaseShAmt = SDValue();
18252 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18253 Amt = Amt.getOperand(0);
18255 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18256 if (SVN && SVN->isSplat()) {
18257 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18258 SDValue InVec = Amt.getOperand(0);
18259 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18260 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18261 "Unexpected shuffle index found!");
18262 BaseShAmt = InVec.getOperand(SplatIdx);
18263 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18264 if (ConstantSDNode *C =
18265 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18266 if (C->getZExtValue() == SplatIdx)
18267 BaseShAmt = InVec.getOperand(1);
18272 // Avoid introducing an extract element from a shuffle.
18273 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18274 DAG.getIntPtrConstant(SplatIdx, dl));
18278 if (BaseShAmt.getNode()) {
18279 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18280 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18281 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18282 else if (EltVT.bitsLT(MVT::i32))
18283 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18285 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18289 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18290 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18291 Amt.getOpcode() == ISD::BITCAST &&
18292 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18293 Amt = Amt.getOperand(0);
18294 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18295 VT.getVectorNumElements();
18296 std::vector<SDValue> Vals(Ratio);
18297 for (unsigned i = 0; i != Ratio; ++i)
18298 Vals[i] = Amt.getOperand(i);
18299 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18300 for (unsigned j = 0; j != Ratio; ++j)
18301 if (Vals[j] != Amt.getOperand(i + j))
18305 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18306 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18311 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18312 SelectionDAG &DAG) {
18313 MVT VT = Op.getSimpleValueType();
18315 SDValue R = Op.getOperand(0);
18316 SDValue Amt = Op.getOperand(1);
18318 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18319 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18321 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18324 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18327 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18330 // XOP has 128-bit variable logical/arithmetic shifts.
18331 // +ve/-ve Amt = shift left/right.
18332 if (Subtarget->hasXOP() &&
18333 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18334 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18335 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18336 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18337 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18339 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18340 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18341 if (Op.getOpcode() == ISD::SRA)
18342 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18345 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18346 // shifts per-lane and then shuffle the partial results back together.
18347 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18348 // Splat the shift amounts so the scalar shifts above will catch it.
18349 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18350 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18351 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18352 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18353 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18356 // i64 vector arithmetic shift can be emulated with the transform:
18357 // M = lshr(SIGN_BIT, Amt)
18358 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18359 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18360 Op.getOpcode() == ISD::SRA) {
18361 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18362 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18363 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18364 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18365 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18369 // If possible, lower this packed shift into a vector multiply instead of
18370 // expanding it into a sequence of scalar shifts.
18371 // Do this only if the vector shift count is a constant build_vector.
18372 if (Op.getOpcode() == ISD::SHL &&
18373 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18374 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18375 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18376 SmallVector<SDValue, 8> Elts;
18377 EVT SVT = VT.getScalarType();
18378 unsigned SVTBits = SVT.getSizeInBits();
18379 const APInt &One = APInt(SVTBits, 1);
18380 unsigned NumElems = VT.getVectorNumElements();
18382 for (unsigned i=0; i !=NumElems; ++i) {
18383 SDValue Op = Amt->getOperand(i);
18384 if (Op->getOpcode() == ISD::UNDEF) {
18385 Elts.push_back(Op);
18389 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18390 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18391 uint64_t ShAmt = C.getZExtValue();
18392 if (ShAmt >= SVTBits) {
18393 Elts.push_back(DAG.getUNDEF(SVT));
18396 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18398 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18399 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18402 // Lower SHL with variable shift amount.
18403 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18404 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18406 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18407 DAG.getConstant(0x3f800000U, dl, VT));
18408 Op = DAG.getBitcast(MVT::v4f32, Op);
18409 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18410 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18413 // If possible, lower this shift as a sequence of two shifts by
18414 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18416 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18418 // Could be rewritten as:
18419 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18421 // The advantage is that the two shifts from the example would be
18422 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18423 // the vector shift into four scalar shifts plus four pairs of vector
18425 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18426 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18427 unsigned TargetOpcode = X86ISD::MOVSS;
18428 bool CanBeSimplified;
18429 // The splat value for the first packed shift (the 'X' from the example).
18430 SDValue Amt1 = Amt->getOperand(0);
18431 // The splat value for the second packed shift (the 'Y' from the example).
18432 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18433 Amt->getOperand(2);
18435 // See if it is possible to replace this node with a sequence of
18436 // two shifts followed by a MOVSS/MOVSD
18437 if (VT == MVT::v4i32) {
18438 // Check if it is legal to use a MOVSS.
18439 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18440 Amt2 == Amt->getOperand(3);
18441 if (!CanBeSimplified) {
18442 // Otherwise, check if we can still simplify this node using a MOVSD.
18443 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18444 Amt->getOperand(2) == Amt->getOperand(3);
18445 TargetOpcode = X86ISD::MOVSD;
18446 Amt2 = Amt->getOperand(2);
18449 // Do similar checks for the case where the machine value type
18451 CanBeSimplified = Amt1 == Amt->getOperand(1);
18452 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18453 CanBeSimplified = Amt2 == Amt->getOperand(i);
18455 if (!CanBeSimplified) {
18456 TargetOpcode = X86ISD::MOVSD;
18457 CanBeSimplified = true;
18458 Amt2 = Amt->getOperand(4);
18459 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18460 CanBeSimplified = Amt1 == Amt->getOperand(i);
18461 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18462 CanBeSimplified = Amt2 == Amt->getOperand(j);
18466 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18467 isa<ConstantSDNode>(Amt2)) {
18468 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18469 EVT CastVT = MVT::v4i32;
18471 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18472 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18474 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18475 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18476 if (TargetOpcode == X86ISD::MOVSD)
18477 CastVT = MVT::v2i64;
18478 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18479 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18480 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18482 return DAG.getBitcast(VT, Result);
18486 // v4i32 Non Uniform Shifts.
18487 // If the shift amount is constant we can shift each lane using the SSE2
18488 // immediate shifts, else we need to zero-extend each lane to the lower i64
18489 // and shift using the SSE2 variable shifts.
18490 // The separate results can then be blended together.
18491 if (VT == MVT::v4i32) {
18492 unsigned Opc = Op.getOpcode();
18493 SDValue Amt0, Amt1, Amt2, Amt3;
18494 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18495 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18496 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18497 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18498 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18500 // ISD::SHL is handled above but we include it here for completeness.
18503 llvm_unreachable("Unknown target vector shift node");
18505 Opc = X86ISD::VSHL;
18508 Opc = X86ISD::VSRL;
18511 Opc = X86ISD::VSRA;
18514 // The SSE2 shifts use the lower i64 as the same shift amount for
18515 // all lanes and the upper i64 is ignored. These shuffle masks
18516 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18517 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18518 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18519 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18520 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18521 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18524 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18525 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18526 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18527 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18528 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18529 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18530 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18533 if (VT == MVT::v16i8 ||
18534 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18535 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18536 unsigned ShiftOpcode = Op->getOpcode();
18538 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18539 // On SSE41 targets we make use of the fact that VSELECT lowers
18540 // to PBLENDVB which selects bytes based just on the sign bit.
18541 if (Subtarget->hasSSE41()) {
18542 V0 = DAG.getBitcast(VT, V0);
18543 V1 = DAG.getBitcast(VT, V1);
18544 Sel = DAG.getBitcast(VT, Sel);
18545 return DAG.getBitcast(SelVT,
18546 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18548 // On pre-SSE41 targets we test for the sign bit by comparing to
18549 // zero - a negative value will set all bits of the lanes to true
18550 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18551 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18552 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18553 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18556 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18557 // We can safely do this using i16 shifts as we're only interested in
18558 // the 3 lower bits of each byte.
18559 Amt = DAG.getBitcast(ExtVT, Amt);
18560 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18561 Amt = DAG.getBitcast(VT, Amt);
18563 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18564 // r = VSELECT(r, shift(r, 4), a);
18566 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18567 R = SignBitSelect(VT, Amt, M, R);
18570 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18572 // r = VSELECT(r, shift(r, 2), a);
18573 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18574 R = SignBitSelect(VT, Amt, M, R);
18577 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18579 // return VSELECT(r, shift(r, 1), a);
18580 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18581 R = SignBitSelect(VT, Amt, M, R);
18585 if (Op->getOpcode() == ISD::SRA) {
18586 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18587 // so we can correctly sign extend. We don't care what happens to the
18589 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18590 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18591 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18592 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18593 ALo = DAG.getBitcast(ExtVT, ALo);
18594 AHi = DAG.getBitcast(ExtVT, AHi);
18595 RLo = DAG.getBitcast(ExtVT, RLo);
18596 RHi = DAG.getBitcast(ExtVT, RHi);
18598 // r = VSELECT(r, shift(r, 4), a);
18599 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18600 DAG.getConstant(4, dl, ExtVT));
18601 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18602 DAG.getConstant(4, dl, ExtVT));
18603 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18604 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18607 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18608 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18610 // r = VSELECT(r, shift(r, 2), a);
18611 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18612 DAG.getConstant(2, dl, ExtVT));
18613 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18614 DAG.getConstant(2, dl, ExtVT));
18615 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18616 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18619 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18620 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18622 // r = VSELECT(r, shift(r, 1), a);
18623 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18624 DAG.getConstant(1, dl, ExtVT));
18625 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18626 DAG.getConstant(1, dl, ExtVT));
18627 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18628 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18630 // Logical shift the result back to the lower byte, leaving a zero upper
18632 // meaning that we can safely pack with PACKUSWB.
18634 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18636 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18637 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18641 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18642 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18643 // solution better.
18644 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18645 MVT ExtVT = MVT::v8i32;
18647 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18648 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18649 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18650 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18651 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18654 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18655 MVT ExtVT = MVT::v8i32;
18656 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18657 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18658 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18659 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18660 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18661 ALo = DAG.getBitcast(ExtVT, ALo);
18662 AHi = DAG.getBitcast(ExtVT, AHi);
18663 RLo = DAG.getBitcast(ExtVT, RLo);
18664 RHi = DAG.getBitcast(ExtVT, RHi);
18665 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18666 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18667 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18668 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18669 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18672 if (VT == MVT::v8i16) {
18673 unsigned ShiftOpcode = Op->getOpcode();
18675 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18676 // On SSE41 targets we make use of the fact that VSELECT lowers
18677 // to PBLENDVB which selects bytes based just on the sign bit.
18678 if (Subtarget->hasSSE41()) {
18679 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18680 V0 = DAG.getBitcast(ExtVT, V0);
18681 V1 = DAG.getBitcast(ExtVT, V1);
18682 Sel = DAG.getBitcast(ExtVT, Sel);
18683 return DAG.getBitcast(
18684 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18686 // On pre-SSE41 targets we splat the sign bit - a negative value will
18687 // set all bits of the lanes to true and VSELECT uses that in
18688 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18690 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18691 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18694 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18695 if (Subtarget->hasSSE41()) {
18696 // On SSE41 targets we need to replicate the shift mask in both
18697 // bytes for PBLENDVB.
18700 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18701 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18703 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18706 // r = VSELECT(r, shift(r, 8), a);
18707 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18708 R = SignBitSelect(Amt, M, R);
18711 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18713 // r = VSELECT(r, shift(r, 4), a);
18714 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18715 R = SignBitSelect(Amt, M, R);
18718 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18720 // r = VSELECT(r, shift(r, 2), a);
18721 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18722 R = SignBitSelect(Amt, M, R);
18725 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18727 // return VSELECT(r, shift(r, 1), a);
18728 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18729 R = SignBitSelect(Amt, M, R);
18733 // Decompose 256-bit shifts into smaller 128-bit shifts.
18734 if (VT.is256BitVector()) {
18735 unsigned NumElems = VT.getVectorNumElements();
18736 MVT EltVT = VT.getVectorElementType();
18737 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18739 // Extract the two vectors
18740 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18741 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18743 // Recreate the shift amount vectors
18744 SDValue Amt1, Amt2;
18745 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18746 // Constant shift amount
18747 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18748 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18749 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18751 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18752 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18754 // Variable shift amount
18755 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18756 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18759 // Issue new vector shifts for the smaller types
18760 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18761 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18763 // Concatenate the result back
18764 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18770 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18771 SelectionDAG &DAG) {
18772 MVT VT = Op.getSimpleValueType();
18774 SDValue R = Op.getOperand(0);
18775 SDValue Amt = Op.getOperand(1);
18777 assert(VT.isVector() && "Custom lowering only for vector rotates!");
18778 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18779 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18781 // XOP has 128-bit vector variable + immediate rotates.
18782 // +ve/-ve Amt = rotate left/right.
18784 // Split 256-bit integers.
18785 if (VT.getSizeInBits() == 256)
18786 return Lower256IntArith(Op, DAG);
18788 assert(VT.getSizeInBits() == 128 && "Only rotate 128-bit vectors!");
18790 // Attempt to rotate by immediate.
18791 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18792 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18793 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18794 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18795 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18796 DAG.getConstant(RotateAmt, DL, MVT::i8));
18800 // Use general rotate by variable (per-element).
18801 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18804 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18805 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18806 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18807 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18808 // has only one use.
18809 SDNode *N = Op.getNode();
18810 SDValue LHS = N->getOperand(0);
18811 SDValue RHS = N->getOperand(1);
18812 unsigned BaseOp = 0;
18815 switch (Op.getOpcode()) {
18816 default: llvm_unreachable("Unknown ovf instruction!");
18818 // A subtract of one will be selected as a INC. Note that INC doesn't
18819 // set CF, so we can't do this for UADDO.
18820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18822 BaseOp = X86ISD::INC;
18823 Cond = X86::COND_O;
18826 BaseOp = X86ISD::ADD;
18827 Cond = X86::COND_O;
18830 BaseOp = X86ISD::ADD;
18831 Cond = X86::COND_B;
18834 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18835 // set CF, so we can't do this for USUBO.
18836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18838 BaseOp = X86ISD::DEC;
18839 Cond = X86::COND_O;
18842 BaseOp = X86ISD::SUB;
18843 Cond = X86::COND_O;
18846 BaseOp = X86ISD::SUB;
18847 Cond = X86::COND_B;
18850 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18851 Cond = X86::COND_O;
18853 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18854 if (N->getValueType(0) == MVT::i8) {
18855 BaseOp = X86ISD::UMUL8;
18856 Cond = X86::COND_O;
18859 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18861 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18864 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18865 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18866 SDValue(Sum.getNode(), 2));
18868 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18872 // Also sets EFLAGS.
18873 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18874 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18877 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18878 DAG.getConstant(Cond, DL, MVT::i32),
18879 SDValue(Sum.getNode(), 1));
18881 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18884 /// Returns true if the operand type is exactly twice the native width, and
18885 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18886 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18887 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18888 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18889 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18892 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18893 else if (OpWidth == 128)
18894 return Subtarget->hasCmpxchg16b();
18899 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18900 return needsCmpXchgNb(SI->getValueOperand()->getType());
18903 // Note: this turns large loads into lock cmpxchg8b/16b.
18904 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18905 TargetLowering::AtomicExpansionKind
18906 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18907 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18908 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18909 : AtomicExpansionKind::None;
18912 TargetLowering::AtomicExpansionKind
18913 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18914 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18915 Type *MemType = AI->getType();
18917 // If the operand is too big, we must see if cmpxchg8/16b is available
18918 // and default to library calls otherwise.
18919 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18920 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18921 : AtomicExpansionKind::None;
18924 AtomicRMWInst::BinOp Op = AI->getOperation();
18927 llvm_unreachable("Unknown atomic operation");
18928 case AtomicRMWInst::Xchg:
18929 case AtomicRMWInst::Add:
18930 case AtomicRMWInst::Sub:
18931 // It's better to use xadd, xsub or xchg for these in all cases.
18932 return AtomicExpansionKind::None;
18933 case AtomicRMWInst::Or:
18934 case AtomicRMWInst::And:
18935 case AtomicRMWInst::Xor:
18936 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18937 // prefix to a normal instruction for these operations.
18938 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18939 : AtomicExpansionKind::None;
18940 case AtomicRMWInst::Nand:
18941 case AtomicRMWInst::Max:
18942 case AtomicRMWInst::Min:
18943 case AtomicRMWInst::UMax:
18944 case AtomicRMWInst::UMin:
18945 // These always require a non-trivial set of data operations on x86. We must
18946 // use a cmpxchg loop.
18947 return AtomicExpansionKind::CmpXChg;
18951 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18952 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18953 // no-sse2). There isn't any reason to disable it if the target processor
18955 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18959 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18960 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18961 Type *MemType = AI->getType();
18962 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18963 // there is no benefit in turning such RMWs into loads, and it is actually
18964 // harmful as it introduces a mfence.
18965 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18968 auto Builder = IRBuilder<>(AI);
18969 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18970 auto SynchScope = AI->getSynchScope();
18971 // We must restrict the ordering to avoid generating loads with Release or
18972 // ReleaseAcquire orderings.
18973 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18974 auto Ptr = AI->getPointerOperand();
18976 // Before the load we need a fence. Here is an example lifted from
18977 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18980 // x.store(1, relaxed);
18981 // r1 = y.fetch_add(0, release);
18983 // y.fetch_add(42, acquire);
18984 // r2 = x.load(relaxed);
18985 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18986 // lowered to just a load without a fence. A mfence flushes the store buffer,
18987 // making the optimization clearly correct.
18988 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18989 // otherwise, we might be able to be more aggressive on relaxed idempotent
18990 // rmw. In practice, they do not look useful, so we don't try to be
18991 // especially clever.
18992 if (SynchScope == SingleThread)
18993 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18994 // the IR level, so we must wrap it in an intrinsic.
18997 if (!hasMFENCE(*Subtarget))
18998 // FIXME: it might make sense to use a locked operation here but on a
18999 // different cache-line to prevent cache-line bouncing. In practice it
19000 // is probably a small win, and x86 processors without mfence are rare
19001 // enough that we do not bother.
19005 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19006 Builder.CreateCall(MFence, {});
19008 // Finally we can emit the atomic load.
19009 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19010 AI->getType()->getPrimitiveSizeInBits());
19011 Loaded->setAtomic(Order, SynchScope);
19012 AI->replaceAllUsesWith(Loaded);
19013 AI->eraseFromParent();
19017 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19018 SelectionDAG &DAG) {
19020 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19021 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19022 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19023 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19025 // The only fence that needs an instruction is a sequentially-consistent
19026 // cross-thread fence.
19027 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19028 if (hasMFENCE(*Subtarget))
19029 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19031 SDValue Chain = Op.getOperand(0);
19032 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19034 DAG.getRegister(X86::ESP, MVT::i32), // Base
19035 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19036 DAG.getRegister(0, MVT::i32), // Index
19037 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19038 DAG.getRegister(0, MVT::i32), // Segment.
19042 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19043 return SDValue(Res, 0);
19046 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19047 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19050 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19051 SelectionDAG &DAG) {
19052 MVT T = Op.getSimpleValueType();
19056 switch(T.SimpleTy) {
19057 default: llvm_unreachable("Invalid value type!");
19058 case MVT::i8: Reg = X86::AL; size = 1; break;
19059 case MVT::i16: Reg = X86::AX; size = 2; break;
19060 case MVT::i32: Reg = X86::EAX; size = 4; break;
19062 assert(Subtarget->is64Bit() && "Node not type legal!");
19063 Reg = X86::RAX; size = 8;
19066 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19067 Op.getOperand(2), SDValue());
19068 SDValue Ops[] = { cpIn.getValue(0),
19071 DAG.getTargetConstant(size, DL, MVT::i8),
19072 cpIn.getValue(1) };
19073 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19074 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19075 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19079 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19080 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19081 MVT::i32, cpOut.getValue(2));
19082 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19083 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19086 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19087 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19088 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19092 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19093 SelectionDAG &DAG) {
19094 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19095 MVT DstVT = Op.getSimpleValueType();
19097 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19098 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19099 if (DstVT != MVT::f64)
19100 // This conversion needs to be expanded.
19103 SDValue InVec = Op->getOperand(0);
19105 unsigned NumElts = SrcVT.getVectorNumElements();
19106 EVT SVT = SrcVT.getVectorElementType();
19108 // Widen the vector in input in the case of MVT::v2i32.
19109 // Example: from MVT::v2i32 to MVT::v4i32.
19110 SmallVector<SDValue, 16> Elts;
19111 for (unsigned i = 0, e = NumElts; i != e; ++i)
19112 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19113 DAG.getIntPtrConstant(i, dl)));
19115 // Explicitly mark the extra elements as Undef.
19116 Elts.append(NumElts, DAG.getUNDEF(SVT));
19118 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19119 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19120 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19121 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19122 DAG.getIntPtrConstant(0, dl));
19125 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19126 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19127 assert((DstVT == MVT::i64 ||
19128 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19129 "Unexpected custom BITCAST");
19130 // i64 <=> MMX conversions are Legal.
19131 if (SrcVT==MVT::i64 && DstVT.isVector())
19133 if (DstVT==MVT::i64 && SrcVT.isVector())
19135 // MMX <=> MMX conversions are Legal.
19136 if (SrcVT.isVector() && DstVT.isVector())
19138 // All other conversions need to be expanded.
19142 /// Compute the horizontal sum of bytes in V for the elements of VT.
19144 /// Requires V to be a byte vector and VT to be an integer vector type with
19145 /// wider elements than V's type. The width of the elements of VT determines
19146 /// how many bytes of V are summed horizontally to produce each element of the
19148 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19149 const X86Subtarget *Subtarget,
19150 SelectionDAG &DAG) {
19152 MVT ByteVecVT = V.getSimpleValueType();
19153 MVT EltVT = VT.getVectorElementType();
19154 int NumElts = VT.getVectorNumElements();
19155 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19156 "Expected value to have byte element type.");
19157 assert(EltVT != MVT::i8 &&
19158 "Horizontal byte sum only makes sense for wider elements!");
19159 unsigned VecSize = VT.getSizeInBits();
19160 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19162 // PSADBW instruction horizontally add all bytes and leave the result in i64
19163 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19164 if (EltVT == MVT::i64) {
19165 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19166 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19167 return DAG.getBitcast(VT, V);
19170 if (EltVT == MVT::i32) {
19171 // We unpack the low half and high half into i32s interleaved with zeros so
19172 // that we can use PSADBW to horizontally sum them. The most useful part of
19173 // this is that it lines up the results of two PSADBW instructions to be
19174 // two v2i64 vectors which concatenated are the 4 population counts. We can
19175 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19176 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19177 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19178 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19180 // Do the horizontal sums into two v2i64s.
19181 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19182 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19183 DAG.getBitcast(ByteVecVT, Low), Zeros);
19184 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19185 DAG.getBitcast(ByteVecVT, High), Zeros);
19187 // Merge them together.
19188 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19189 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19190 DAG.getBitcast(ShortVecVT, Low),
19191 DAG.getBitcast(ShortVecVT, High));
19193 return DAG.getBitcast(VT, V);
19196 // The only element type left is i16.
19197 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19199 // To obtain pop count for each i16 element starting from the pop count for
19200 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19201 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19202 // directly supported.
19203 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19204 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19205 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19206 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19207 DAG.getBitcast(ByteVecVT, V));
19208 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19211 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19212 const X86Subtarget *Subtarget,
19213 SelectionDAG &DAG) {
19214 MVT VT = Op.getSimpleValueType();
19215 MVT EltVT = VT.getVectorElementType();
19216 unsigned VecSize = VT.getSizeInBits();
19218 // Implement a lookup table in register by using an algorithm based on:
19219 // http://wm.ite.pl/articles/sse-popcount.html
19221 // The general idea is that every lower byte nibble in the input vector is an
19222 // index into a in-register pre-computed pop count table. We then split up the
19223 // input vector in two new ones: (1) a vector with only the shifted-right
19224 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19225 // masked out higher ones) for each byte. PSHUB is used separately with both
19226 // to index the in-register table. Next, both are added and the result is a
19227 // i8 vector where each element contains the pop count for input byte.
19229 // To obtain the pop count for elements != i8, we follow up with the same
19230 // approach and use additional tricks as described below.
19232 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19233 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19234 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19235 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19237 int NumByteElts = VecSize / 8;
19238 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19239 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19240 SmallVector<SDValue, 16> LUTVec;
19241 for (int i = 0; i < NumByteElts; ++i)
19242 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19243 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19244 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19245 DAG.getConstant(0x0F, DL, MVT::i8));
19246 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19249 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19250 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19251 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19254 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19256 // The input vector is used as the shuffle mask that index elements into the
19257 // LUT. After counting low and high nibbles, add the vector to obtain the
19258 // final pop count per i8 element.
19259 SDValue HighPopCnt =
19260 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19261 SDValue LowPopCnt =
19262 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19263 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19265 if (EltVT == MVT::i8)
19268 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19271 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19272 const X86Subtarget *Subtarget,
19273 SelectionDAG &DAG) {
19274 MVT VT = Op.getSimpleValueType();
19275 assert(VT.is128BitVector() &&
19276 "Only 128-bit vector bitmath lowering supported.");
19278 int VecSize = VT.getSizeInBits();
19279 MVT EltVT = VT.getVectorElementType();
19280 int Len = EltVT.getSizeInBits();
19282 // This is the vectorized version of the "best" algorithm from
19283 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19284 // with a minor tweak to use a series of adds + shifts instead of vector
19285 // multiplications. Implemented for all integer vector types. We only use
19286 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19287 // much faster, even faster than using native popcnt instructions.
19289 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19290 MVT VT = V.getSimpleValueType();
19291 SmallVector<SDValue, 32> Shifters(
19292 VT.getVectorNumElements(),
19293 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19294 return DAG.getNode(OpCode, DL, VT, V,
19295 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19297 auto GetMask = [&](SDValue V, APInt Mask) {
19298 MVT VT = V.getSimpleValueType();
19299 SmallVector<SDValue, 32> Masks(
19300 VT.getVectorNumElements(),
19301 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19302 return DAG.getNode(ISD::AND, DL, VT, V,
19303 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19306 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19307 // x86, so set the SRL type to have elements at least i16 wide. This is
19308 // correct because all of our SRLs are followed immediately by a mask anyways
19309 // that handles any bits that sneak into the high bits of the byte elements.
19310 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19314 // v = v - ((v >> 1) & 0x55555555...)
19316 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19317 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19318 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19320 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19321 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19322 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19323 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19324 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19326 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19327 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19328 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19329 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19331 // At this point, V contains the byte-wise population count, and we are
19332 // merely doing a horizontal sum if necessary to get the wider element
19334 if (EltVT == MVT::i8)
19337 return LowerHorizontalByteSum(
19338 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19342 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19343 SelectionDAG &DAG) {
19344 MVT VT = Op.getSimpleValueType();
19345 // FIXME: Need to add AVX-512 support here!
19346 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19347 "Unknown CTPOP type to handle");
19348 SDLoc DL(Op.getNode());
19349 SDValue Op0 = Op.getOperand(0);
19351 if (!Subtarget->hasSSSE3()) {
19352 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19353 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19354 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19357 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19358 unsigned NumElems = VT.getVectorNumElements();
19360 // Extract each 128-bit vector, compute pop count and concat the result.
19361 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19362 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19364 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19365 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19366 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19369 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19372 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19373 SelectionDAG &DAG) {
19374 assert(Op.getValueType().isVector() &&
19375 "We only do custom lowering for vector population count.");
19376 return LowerVectorCTPOP(Op, Subtarget, DAG);
19379 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19380 SDNode *Node = Op.getNode();
19382 EVT T = Node->getValueType(0);
19383 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19384 DAG.getConstant(0, dl, T), Node->getOperand(2));
19385 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19386 cast<AtomicSDNode>(Node)->getMemoryVT(),
19387 Node->getOperand(0),
19388 Node->getOperand(1), negOp,
19389 cast<AtomicSDNode>(Node)->getMemOperand(),
19390 cast<AtomicSDNode>(Node)->getOrdering(),
19391 cast<AtomicSDNode>(Node)->getSynchScope());
19394 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19395 SDNode *Node = Op.getNode();
19397 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19399 // Convert seq_cst store -> xchg
19400 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19401 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19402 // (The only way to get a 16-byte store is cmpxchg16b)
19403 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19404 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19405 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19406 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19407 cast<AtomicSDNode>(Node)->getMemoryVT(),
19408 Node->getOperand(0),
19409 Node->getOperand(1), Node->getOperand(2),
19410 cast<AtomicSDNode>(Node)->getMemOperand(),
19411 cast<AtomicSDNode>(Node)->getOrdering(),
19412 cast<AtomicSDNode>(Node)->getSynchScope());
19413 return Swap.getValue(1);
19415 // Other atomic stores have a simple pattern.
19419 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19420 EVT VT = Op.getNode()->getSimpleValueType(0);
19422 // Let legalize expand this if it isn't a legal type yet.
19423 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19426 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19429 bool ExtraOp = false;
19430 switch (Op.getOpcode()) {
19431 default: llvm_unreachable("Invalid code");
19432 case ISD::ADDC: Opc = X86ISD::ADD; break;
19433 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19434 case ISD::SUBC: Opc = X86ISD::SUB; break;
19435 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19439 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19441 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19442 Op.getOperand(1), Op.getOperand(2));
19445 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19446 SelectionDAG &DAG) {
19447 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19449 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19450 // which returns the values as { float, float } (in XMM0) or
19451 // { double, double } (which is returned in XMM0, XMM1).
19453 SDValue Arg = Op.getOperand(0);
19454 EVT ArgVT = Arg.getValueType();
19455 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19457 TargetLowering::ArgListTy Args;
19458 TargetLowering::ArgListEntry Entry;
19462 Entry.isSExt = false;
19463 Entry.isZExt = false;
19464 Args.push_back(Entry);
19466 bool isF64 = ArgVT == MVT::f64;
19467 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19468 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19469 // the results are returned via SRet in memory.
19470 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19471 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19473 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19475 Type *RetTy = isF64
19476 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19477 : (Type*)VectorType::get(ArgTy, 4);
19479 TargetLowering::CallLoweringInfo CLI(DAG);
19480 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19481 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19483 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19486 // Returned in xmm0 and xmm1.
19487 return CallResult.first;
19489 // Returned in bits 0:31 and 32:64 xmm0.
19490 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19491 CallResult.first, DAG.getIntPtrConstant(0, dl));
19492 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19493 CallResult.first, DAG.getIntPtrConstant(1, dl));
19494 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19495 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19498 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19499 SelectionDAG &DAG) {
19500 assert(Subtarget->hasAVX512() &&
19501 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19503 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19504 EVT VT = N->getValue().getValueType();
19505 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19508 // X86 scatter kills mask register, so its type should be added to
19509 // the list of return values
19510 if (N->getNumValues() == 1) {
19511 SDValue Index = N->getIndex();
19512 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19513 !Index.getValueType().is512BitVector())
19514 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19516 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19517 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19518 N->getOperand(3), Index };
19520 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19521 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19522 return SDValue(NewScatter.getNode(), 0);
19527 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19528 SelectionDAG &DAG) {
19529 assert(Subtarget->hasAVX512() &&
19530 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19532 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19533 EVT VT = Op.getValueType();
19534 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19537 SDValue Index = N->getIndex();
19538 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19539 !Index.getValueType().is512BitVector()) {
19540 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19541 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19542 N->getOperand(3), Index };
19543 DAG.UpdateNodeOperands(N, Ops);
19548 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19549 SelectionDAG &DAG) const {
19550 // TODO: Eventually, the lowering of these nodes should be informed by or
19551 // deferred to the GC strategy for the function in which they appear. For
19552 // now, however, they must be lowered to something. Since they are logically
19553 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19554 // require special handling for these nodes), lower them as literal NOOPs for
19556 SmallVector<SDValue, 2> Ops;
19558 Ops.push_back(Op.getOperand(0));
19559 if (Op->getGluedNode())
19560 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19563 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19564 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19569 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19570 SelectionDAG &DAG) const {
19571 // TODO: Eventually, the lowering of these nodes should be informed by or
19572 // deferred to the GC strategy for the function in which they appear. For
19573 // now, however, they must be lowered to something. Since they are logically
19574 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19575 // require special handling for these nodes), lower them as literal NOOPs for
19577 SmallVector<SDValue, 2> Ops;
19579 Ops.push_back(Op.getOperand(0));
19580 if (Op->getGluedNode())
19581 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19584 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19585 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19590 /// LowerOperation - Provide custom lowering hooks for some operations.
19592 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19593 switch (Op.getOpcode()) {
19594 default: llvm_unreachable("Should not custom lower this!");
19595 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19596 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19597 return LowerCMP_SWAP(Op, Subtarget, DAG);
19598 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19599 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19600 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19601 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19602 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19603 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19604 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19605 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19606 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19607 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19608 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19609 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19610 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19611 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19612 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19613 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19614 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19615 case ISD::SHL_PARTS:
19616 case ISD::SRA_PARTS:
19617 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19618 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19619 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19620 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19621 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19622 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19623 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19624 case ISD::SIGN_EXTEND_VECTOR_INREG:
19625 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19626 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19627 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19628 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19629 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19631 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19632 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19633 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19634 case ISD::SETCC: return LowerSETCC(Op, DAG);
19635 case ISD::SELECT: return LowerSELECT(Op, DAG);
19636 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19637 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19638 case ISD::VASTART: return LowerVASTART(Op, DAG);
19639 case ISD::VAARG: return LowerVAARG(Op, DAG);
19640 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19641 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19642 case ISD::INTRINSIC_VOID:
19643 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19644 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19645 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19646 case ISD::FRAME_TO_ARGS_OFFSET:
19647 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19648 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19649 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19650 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19651 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19652 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19653 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19654 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19655 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
19656 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19658 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
19659 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19660 case ISD::UMUL_LOHI:
19661 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19662 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
19665 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19671 case ISD::UMULO: return LowerXALUO(Op, DAG);
19672 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19673 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19677 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19678 case ISD::ADD: return LowerADD(Op, DAG);
19679 case ISD::SUB: return LowerSUB(Op, DAG);
19683 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19684 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19685 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19686 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19687 case ISD::GC_TRANSITION_START:
19688 return LowerGC_TRANSITION_START(Op, DAG);
19689 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19693 /// ReplaceNodeResults - Replace a node with an illegal result type
19694 /// with a new node built out of custom code.
19695 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19696 SmallVectorImpl<SDValue>&Results,
19697 SelectionDAG &DAG) const {
19699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19700 switch (N->getOpcode()) {
19702 llvm_unreachable("Do not know how to custom type legalize this operation!");
19703 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19704 case X86ISD::FMINC:
19706 case X86ISD::FMAXC:
19707 case X86ISD::FMAX: {
19708 EVT VT = N->getValueType(0);
19709 if (VT != MVT::v2f32)
19710 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19711 SDValue UNDEF = DAG.getUNDEF(VT);
19712 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19713 N->getOperand(0), UNDEF);
19714 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19715 N->getOperand(1), UNDEF);
19716 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19719 case ISD::SIGN_EXTEND_INREG:
19724 // We don't want to expand or promote these.
19731 case ISD::UDIVREM: {
19732 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19733 Results.push_back(V);
19736 case ISD::FP_TO_SINT:
19737 case ISD::FP_TO_UINT: {
19738 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19740 std::pair<SDValue,SDValue> Vals =
19741 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19742 SDValue FIST = Vals.first, StackSlot = Vals.second;
19743 if (FIST.getNode()) {
19744 EVT VT = N->getValueType(0);
19745 // Return a load from the stack slot.
19746 if (StackSlot.getNode())
19747 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19748 MachinePointerInfo(),
19749 false, false, false, 0));
19751 Results.push_back(FIST);
19755 case ISD::UINT_TO_FP: {
19756 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19757 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19758 N->getValueType(0) != MVT::v2f32)
19760 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19762 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19764 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19765 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19766 DAG.getBitcast(MVT::v2i64, VBias));
19767 Or = DAG.getBitcast(MVT::v2f64, Or);
19768 // TODO: Are there any fast-math-flags to propagate here?
19769 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19770 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19773 case ISD::FP_ROUND: {
19774 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19776 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19777 Results.push_back(V);
19780 case ISD::FP_EXTEND: {
19781 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19782 // No other ValueType for FP_EXTEND should reach this point.
19783 assert(N->getValueType(0) == MVT::v2f32 &&
19784 "Do not know how to legalize this Node");
19787 case ISD::INTRINSIC_W_CHAIN: {
19788 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19790 default : llvm_unreachable("Do not know how to custom type "
19791 "legalize this intrinsic operation!");
19792 case Intrinsic::x86_rdtsc:
19793 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19795 case Intrinsic::x86_rdtscp:
19796 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19798 case Intrinsic::x86_rdpmc:
19799 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19802 case ISD::READCYCLECOUNTER: {
19803 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19806 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19807 EVT T = N->getValueType(0);
19808 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19809 bool Regs64bit = T == MVT::i128;
19810 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19811 SDValue cpInL, cpInH;
19812 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19813 DAG.getConstant(0, dl, HalfT));
19814 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19815 DAG.getConstant(1, dl, HalfT));
19816 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19817 Regs64bit ? X86::RAX : X86::EAX,
19819 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19820 Regs64bit ? X86::RDX : X86::EDX,
19821 cpInH, cpInL.getValue(1));
19822 SDValue swapInL, swapInH;
19823 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19824 DAG.getConstant(0, dl, HalfT));
19825 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19826 DAG.getConstant(1, dl, HalfT));
19827 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19828 Regs64bit ? X86::RBX : X86::EBX,
19829 swapInL, cpInH.getValue(1));
19830 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19831 Regs64bit ? X86::RCX : X86::ECX,
19832 swapInH, swapInL.getValue(1));
19833 SDValue Ops[] = { swapInH.getValue(0),
19835 swapInH.getValue(1) };
19836 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19837 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19838 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19839 X86ISD::LCMPXCHG8_DAG;
19840 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19841 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19842 Regs64bit ? X86::RAX : X86::EAX,
19843 HalfT, Result.getValue(1));
19844 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19845 Regs64bit ? X86::RDX : X86::EDX,
19846 HalfT, cpOutL.getValue(2));
19847 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19849 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19850 MVT::i32, cpOutH.getValue(2));
19852 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19853 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19854 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19856 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19857 Results.push_back(Success);
19858 Results.push_back(EFLAGS.getValue(1));
19861 case ISD::ATOMIC_SWAP:
19862 case ISD::ATOMIC_LOAD_ADD:
19863 case ISD::ATOMIC_LOAD_SUB:
19864 case ISD::ATOMIC_LOAD_AND:
19865 case ISD::ATOMIC_LOAD_OR:
19866 case ISD::ATOMIC_LOAD_XOR:
19867 case ISD::ATOMIC_LOAD_NAND:
19868 case ISD::ATOMIC_LOAD_MIN:
19869 case ISD::ATOMIC_LOAD_MAX:
19870 case ISD::ATOMIC_LOAD_UMIN:
19871 case ISD::ATOMIC_LOAD_UMAX:
19872 case ISD::ATOMIC_LOAD: {
19873 // Delegate to generic TypeLegalization. Situations we can really handle
19874 // should have already been dealt with by AtomicExpandPass.cpp.
19877 case ISD::BITCAST: {
19878 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19879 EVT DstVT = N->getValueType(0);
19880 EVT SrcVT = N->getOperand(0)->getValueType(0);
19882 if (SrcVT != MVT::f64 ||
19883 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19886 unsigned NumElts = DstVT.getVectorNumElements();
19887 EVT SVT = DstVT.getVectorElementType();
19888 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19889 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19890 MVT::v2f64, N->getOperand(0));
19891 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19893 if (ExperimentalVectorWideningLegalization) {
19894 // If we are legalizing vectors by widening, we already have the desired
19895 // legal vector type, just return it.
19896 Results.push_back(ToVecInt);
19900 SmallVector<SDValue, 8> Elts;
19901 for (unsigned i = 0, e = NumElts; i != e; ++i)
19902 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19903 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19905 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19910 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19911 switch ((X86ISD::NodeType)Opcode) {
19912 case X86ISD::FIRST_NUMBER: break;
19913 case X86ISD::BSF: return "X86ISD::BSF";
19914 case X86ISD::BSR: return "X86ISD::BSR";
19915 case X86ISD::SHLD: return "X86ISD::SHLD";
19916 case X86ISD::SHRD: return "X86ISD::SHRD";
19917 case X86ISD::FAND: return "X86ISD::FAND";
19918 case X86ISD::FANDN: return "X86ISD::FANDN";
19919 case X86ISD::FOR: return "X86ISD::FOR";
19920 case X86ISD::FXOR: return "X86ISD::FXOR";
19921 case X86ISD::FILD: return "X86ISD::FILD";
19922 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19923 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19924 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19925 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19926 case X86ISD::FLD: return "X86ISD::FLD";
19927 case X86ISD::FST: return "X86ISD::FST";
19928 case X86ISD::CALL: return "X86ISD::CALL";
19929 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19930 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19931 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19932 case X86ISD::BT: return "X86ISD::BT";
19933 case X86ISD::CMP: return "X86ISD::CMP";
19934 case X86ISD::COMI: return "X86ISD::COMI";
19935 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19936 case X86ISD::CMPM: return "X86ISD::CMPM";
19937 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19938 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19939 case X86ISD::SETCC: return "X86ISD::SETCC";
19940 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19941 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19942 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19943 case X86ISD::CMOV: return "X86ISD::CMOV";
19944 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19945 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19946 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19947 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19948 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19949 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19950 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19951 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19952 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19953 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19954 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19955 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19956 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19957 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19958 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19959 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19960 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19961 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19962 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19963 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19964 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19965 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19966 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19967 case X86ISD::HADD: return "X86ISD::HADD";
19968 case X86ISD::HSUB: return "X86ISD::HSUB";
19969 case X86ISD::FHADD: return "X86ISD::FHADD";
19970 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19971 case X86ISD::ABS: return "X86ISD::ABS";
19972 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19973 case X86ISD::FMAX: return "X86ISD::FMAX";
19974 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19975 case X86ISD::FMIN: return "X86ISD::FMIN";
19976 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19977 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19978 case X86ISD::FMINC: return "X86ISD::FMINC";
19979 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19980 case X86ISD::FRCP: return "X86ISD::FRCP";
19981 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19982 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19983 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19984 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19985 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19986 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19987 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19988 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19989 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19990 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19991 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19992 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19993 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19994 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19995 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19996 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19997 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19998 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19999 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20000 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20001 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20002 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20003 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20004 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20005 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20006 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20007 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20008 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20009 case X86ISD::VSHL: return "X86ISD::VSHL";
20010 case X86ISD::VSRL: return "X86ISD::VSRL";
20011 case X86ISD::VSRA: return "X86ISD::VSRA";
20012 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20013 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20014 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20015 case X86ISD::CMPP: return "X86ISD::CMPP";
20016 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20017 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20018 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20019 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20020 case X86ISD::ADD: return "X86ISD::ADD";
20021 case X86ISD::SUB: return "X86ISD::SUB";
20022 case X86ISD::ADC: return "X86ISD::ADC";
20023 case X86ISD::SBB: return "X86ISD::SBB";
20024 case X86ISD::SMUL: return "X86ISD::SMUL";
20025 case X86ISD::UMUL: return "X86ISD::UMUL";
20026 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20027 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20028 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20029 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20030 case X86ISD::INC: return "X86ISD::INC";
20031 case X86ISD::DEC: return "X86ISD::DEC";
20032 case X86ISD::OR: return "X86ISD::OR";
20033 case X86ISD::XOR: return "X86ISD::XOR";
20034 case X86ISD::AND: return "X86ISD::AND";
20035 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20036 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20037 case X86ISD::PTEST: return "X86ISD::PTEST";
20038 case X86ISD::TESTP: return "X86ISD::TESTP";
20039 case X86ISD::TESTM: return "X86ISD::TESTM";
20040 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20041 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20042 case X86ISD::KTEST: return "X86ISD::KTEST";
20043 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20044 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20045 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20046 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20047 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20048 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20049 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20050 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20051 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20052 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20053 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20054 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20055 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20056 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20057 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20058 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20059 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20060 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20061 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20062 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20063 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20064 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20065 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20066 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20067 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20068 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20069 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20070 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20071 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20072 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20073 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20074 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20075 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20076 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20077 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20078 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20079 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20080 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20081 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20082 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20083 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20084 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20085 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20086 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20087 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20088 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20089 case X86ISD::SAHF: return "X86ISD::SAHF";
20090 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20091 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20092 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20093 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20094 case X86ISD::VPROT: return "X86ISD::VPROT";
20095 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20096 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20097 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20098 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20099 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20100 case X86ISD::FMADD: return "X86ISD::FMADD";
20101 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20102 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20103 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20104 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20105 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20106 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20107 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20108 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20109 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20110 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20111 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20112 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20113 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20114 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20115 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20116 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20117 case X86ISD::XTEST: return "X86ISD::XTEST";
20118 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20119 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20120 case X86ISD::SELECT: return "X86ISD::SELECT";
20121 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20122 case X86ISD::RCP28: return "X86ISD::RCP28";
20123 case X86ISD::EXP2: return "X86ISD::EXP2";
20124 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20125 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20126 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20127 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20128 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20129 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20130 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20131 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20132 case X86ISD::ADDS: return "X86ISD::ADDS";
20133 case X86ISD::SUBS: return "X86ISD::SUBS";
20134 case X86ISD::AVG: return "X86ISD::AVG";
20135 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20136 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20137 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20138 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20139 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20140 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20145 // isLegalAddressingMode - Return true if the addressing mode represented
20146 // by AM is legal for this target, for a load/store of the specified type.
20147 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20148 const AddrMode &AM, Type *Ty,
20149 unsigned AS) const {
20150 // X86 supports extremely general addressing modes.
20151 CodeModel::Model M = getTargetMachine().getCodeModel();
20152 Reloc::Model R = getTargetMachine().getRelocationModel();
20154 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20155 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20160 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20162 // If a reference to this global requires an extra load, we can't fold it.
20163 if (isGlobalStubReference(GVFlags))
20166 // If BaseGV requires a register for the PIC base, we cannot also have a
20167 // BaseReg specified.
20168 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20171 // If lower 4G is not available, then we must use rip-relative addressing.
20172 if ((M != CodeModel::Small || R != Reloc::Static) &&
20173 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20177 switch (AM.Scale) {
20183 // These scales always work.
20188 // These scales are formed with basereg+scalereg. Only accept if there is
20193 default: // Other stuff never works.
20200 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20201 unsigned Bits = Ty->getScalarSizeInBits();
20203 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20204 // particularly cheaper than those without.
20208 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20209 // variable shifts just as cheap as scalar ones.
20210 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20213 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20214 // fully general vector.
20218 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20219 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20221 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20222 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20223 return NumBits1 > NumBits2;
20226 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20227 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20230 if (!isTypeLegal(EVT::getEVT(Ty1)))
20233 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20235 // Assuming the caller doesn't have a zeroext or signext return parameter,
20236 // truncation all the way down to i1 is valid.
20240 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20241 return isInt<32>(Imm);
20244 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20245 // Can also use sub to handle negated immediates.
20246 return isInt<32>(Imm);
20249 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20250 if (!VT1.isInteger() || !VT2.isInteger())
20252 unsigned NumBits1 = VT1.getSizeInBits();
20253 unsigned NumBits2 = VT2.getSizeInBits();
20254 return NumBits1 > NumBits2;
20257 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20258 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20259 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20262 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20263 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20264 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20267 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20268 EVT VT1 = Val.getValueType();
20269 if (isZExtFree(VT1, VT2))
20272 if (Val.getOpcode() != ISD::LOAD)
20275 if (!VT1.isSimple() || !VT1.isInteger() ||
20276 !VT2.isSimple() || !VT2.isInteger())
20279 switch (VT1.getSimpleVT().SimpleTy) {
20284 // X86 has 8, 16, and 32-bit zero-extending loads.
20291 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20294 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20295 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20298 VT = VT.getScalarType();
20300 if (!VT.isSimple())
20303 switch (VT.getSimpleVT().SimpleTy) {
20314 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20315 // i16 instructions are longer (0x66 prefix) and potentially slower.
20316 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20319 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20320 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20321 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20322 /// are assumed to be legal.
20324 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20326 if (!VT.isSimple())
20329 // Not for i1 vectors
20330 if (VT.getScalarType() == MVT::i1)
20333 // Very little shuffling can be done for 64-bit vectors right now.
20334 if (VT.getSizeInBits() == 64)
20337 // We only care that the types being shuffled are legal. The lowering can
20338 // handle any possible shuffle mask that results.
20339 return isTypeLegal(VT.getSimpleVT());
20343 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20345 // Just delegate to the generic legality, clear masks aren't special.
20346 return isShuffleMaskLegal(Mask, VT);
20349 //===----------------------------------------------------------------------===//
20350 // X86 Scheduler Hooks
20351 //===----------------------------------------------------------------------===//
20353 /// Utility function to emit xbegin specifying the start of an RTM region.
20354 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20355 const TargetInstrInfo *TII) {
20356 DebugLoc DL = MI->getDebugLoc();
20358 const BasicBlock *BB = MBB->getBasicBlock();
20359 MachineFunction::iterator I = ++MBB->getIterator();
20361 // For the v = xbegin(), we generate
20372 MachineBasicBlock *thisMBB = MBB;
20373 MachineFunction *MF = MBB->getParent();
20374 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20375 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20376 MF->insert(I, mainMBB);
20377 MF->insert(I, sinkMBB);
20379 // Transfer the remainder of BB and its successor edges to sinkMBB.
20380 sinkMBB->splice(sinkMBB->begin(), MBB,
20381 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20382 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20386 // # fallthrough to mainMBB
20387 // # abortion to sinkMBB
20388 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20389 thisMBB->addSuccessor(mainMBB);
20390 thisMBB->addSuccessor(sinkMBB);
20394 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20395 mainMBB->addSuccessor(sinkMBB);
20398 // EAX is live into the sinkMBB
20399 sinkMBB->addLiveIn(X86::EAX);
20400 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20401 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20404 MI->eraseFromParent();
20408 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20409 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20410 // in the .td file.
20411 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20412 const TargetInstrInfo *TII) {
20414 switch (MI->getOpcode()) {
20415 default: llvm_unreachable("illegal opcode!");
20416 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20417 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20418 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20419 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20420 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20421 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20422 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20423 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20426 DebugLoc dl = MI->getDebugLoc();
20427 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20429 unsigned NumArgs = MI->getNumOperands();
20430 for (unsigned i = 1; i < NumArgs; ++i) {
20431 MachineOperand &Op = MI->getOperand(i);
20432 if (!(Op.isReg() && Op.isImplicit()))
20433 MIB.addOperand(Op);
20435 if (MI->hasOneMemOperand())
20436 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20438 BuildMI(*BB, MI, dl,
20439 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20440 .addReg(X86::XMM0);
20442 MI->eraseFromParent();
20446 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20447 // defs in an instruction pattern
20448 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20449 const TargetInstrInfo *TII) {
20451 switch (MI->getOpcode()) {
20452 default: llvm_unreachable("illegal opcode!");
20453 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20454 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20455 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20456 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20457 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20458 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20459 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20460 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20463 DebugLoc dl = MI->getDebugLoc();
20464 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20466 unsigned NumArgs = MI->getNumOperands(); // remove the results
20467 for (unsigned i = 1; i < NumArgs; ++i) {
20468 MachineOperand &Op = MI->getOperand(i);
20469 if (!(Op.isReg() && Op.isImplicit()))
20470 MIB.addOperand(Op);
20472 if (MI->hasOneMemOperand())
20473 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20475 BuildMI(*BB, MI, dl,
20476 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20479 MI->eraseFromParent();
20483 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20484 const X86Subtarget *Subtarget) {
20485 DebugLoc dl = MI->getDebugLoc();
20486 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20487 // Address into RAX/EAX, other two args into ECX, EDX.
20488 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20489 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20490 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20491 for (int i = 0; i < X86::AddrNumOperands; ++i)
20492 MIB.addOperand(MI->getOperand(i));
20494 unsigned ValOps = X86::AddrNumOperands;
20495 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20496 .addReg(MI->getOperand(ValOps).getReg());
20497 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20498 .addReg(MI->getOperand(ValOps+1).getReg());
20500 // The instruction doesn't actually take any operands though.
20501 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20503 MI->eraseFromParent(); // The pseudo is gone now.
20507 MachineBasicBlock *
20508 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20509 MachineBasicBlock *MBB) const {
20510 // Emit va_arg instruction on X86-64.
20512 // Operands to this pseudo-instruction:
20513 // 0 ) Output : destination address (reg)
20514 // 1-5) Input : va_list address (addr, i64mem)
20515 // 6 ) ArgSize : Size (in bytes) of vararg type
20516 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20517 // 8 ) Align : Alignment of type
20518 // 9 ) EFLAGS (implicit-def)
20520 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20521 static_assert(X86::AddrNumOperands == 5,
20522 "VAARG_64 assumes 5 address operands");
20524 unsigned DestReg = MI->getOperand(0).getReg();
20525 MachineOperand &Base = MI->getOperand(1);
20526 MachineOperand &Scale = MI->getOperand(2);
20527 MachineOperand &Index = MI->getOperand(3);
20528 MachineOperand &Disp = MI->getOperand(4);
20529 MachineOperand &Segment = MI->getOperand(5);
20530 unsigned ArgSize = MI->getOperand(6).getImm();
20531 unsigned ArgMode = MI->getOperand(7).getImm();
20532 unsigned Align = MI->getOperand(8).getImm();
20534 // Memory Reference
20535 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20536 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20537 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20539 // Machine Information
20540 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20541 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20542 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20543 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20544 DebugLoc DL = MI->getDebugLoc();
20546 // struct va_list {
20549 // i64 overflow_area (address)
20550 // i64 reg_save_area (address)
20552 // sizeof(va_list) = 24
20553 // alignment(va_list) = 8
20555 unsigned TotalNumIntRegs = 6;
20556 unsigned TotalNumXMMRegs = 8;
20557 bool UseGPOffset = (ArgMode == 1);
20558 bool UseFPOffset = (ArgMode == 2);
20559 unsigned MaxOffset = TotalNumIntRegs * 8 +
20560 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20562 /* Align ArgSize to a multiple of 8 */
20563 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20564 bool NeedsAlign = (Align > 8);
20566 MachineBasicBlock *thisMBB = MBB;
20567 MachineBasicBlock *overflowMBB;
20568 MachineBasicBlock *offsetMBB;
20569 MachineBasicBlock *endMBB;
20571 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20572 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20573 unsigned OffsetReg = 0;
20575 if (!UseGPOffset && !UseFPOffset) {
20576 // If we only pull from the overflow region, we don't create a branch.
20577 // We don't need to alter control flow.
20578 OffsetDestReg = 0; // unused
20579 OverflowDestReg = DestReg;
20581 offsetMBB = nullptr;
20582 overflowMBB = thisMBB;
20585 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20586 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20587 // If not, pull from overflow_area. (branch to overflowMBB)
20592 // offsetMBB overflowMBB
20597 // Registers for the PHI in endMBB
20598 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20599 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20601 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20602 MachineFunction *MF = MBB->getParent();
20603 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20604 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20605 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20607 MachineFunction::iterator MBBIter = ++MBB->getIterator();
20609 // Insert the new basic blocks
20610 MF->insert(MBBIter, offsetMBB);
20611 MF->insert(MBBIter, overflowMBB);
20612 MF->insert(MBBIter, endMBB);
20614 // Transfer the remainder of MBB and its successor edges to endMBB.
20615 endMBB->splice(endMBB->begin(), thisMBB,
20616 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20617 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20619 // Make offsetMBB and overflowMBB successors of thisMBB
20620 thisMBB->addSuccessor(offsetMBB);
20621 thisMBB->addSuccessor(overflowMBB);
20623 // endMBB is a successor of both offsetMBB and overflowMBB
20624 offsetMBB->addSuccessor(endMBB);
20625 overflowMBB->addSuccessor(endMBB);
20627 // Load the offset value into a register
20628 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20629 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20633 .addDisp(Disp, UseFPOffset ? 4 : 0)
20634 .addOperand(Segment)
20635 .setMemRefs(MMOBegin, MMOEnd);
20637 // Check if there is enough room left to pull this argument.
20638 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20640 .addImm(MaxOffset + 8 - ArgSizeA8);
20642 // Branch to "overflowMBB" if offset >= max
20643 // Fall through to "offsetMBB" otherwise
20644 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20645 .addMBB(overflowMBB);
20648 // In offsetMBB, emit code to use the reg_save_area.
20650 assert(OffsetReg != 0);
20652 // Read the reg_save_area address.
20653 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20654 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20659 .addOperand(Segment)
20660 .setMemRefs(MMOBegin, MMOEnd);
20662 // Zero-extend the offset
20663 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20664 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20667 .addImm(X86::sub_32bit);
20669 // Add the offset to the reg_save_area to get the final address.
20670 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20671 .addReg(OffsetReg64)
20672 .addReg(RegSaveReg);
20674 // Compute the offset for the next argument
20675 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20676 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20678 .addImm(UseFPOffset ? 16 : 8);
20680 // Store it back into the va_list.
20681 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20685 .addDisp(Disp, UseFPOffset ? 4 : 0)
20686 .addOperand(Segment)
20687 .addReg(NextOffsetReg)
20688 .setMemRefs(MMOBegin, MMOEnd);
20691 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20696 // Emit code to use overflow area
20699 // Load the overflow_area address into a register.
20700 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20701 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20706 .addOperand(Segment)
20707 .setMemRefs(MMOBegin, MMOEnd);
20709 // If we need to align it, do so. Otherwise, just copy the address
20710 // to OverflowDestReg.
20712 // Align the overflow address
20713 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20714 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20716 // aligned_addr = (addr + (align-1)) & ~(align-1)
20717 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20718 .addReg(OverflowAddrReg)
20721 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20723 .addImm(~(uint64_t)(Align-1));
20725 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20726 .addReg(OverflowAddrReg);
20729 // Compute the next overflow address after this argument.
20730 // (the overflow address should be kept 8-byte aligned)
20731 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20732 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20733 .addReg(OverflowDestReg)
20734 .addImm(ArgSizeA8);
20736 // Store the new overflow address.
20737 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20742 .addOperand(Segment)
20743 .addReg(NextAddrReg)
20744 .setMemRefs(MMOBegin, MMOEnd);
20746 // If we branched, emit the PHI to the front of endMBB.
20748 BuildMI(*endMBB, endMBB->begin(), DL,
20749 TII->get(X86::PHI), DestReg)
20750 .addReg(OffsetDestReg).addMBB(offsetMBB)
20751 .addReg(OverflowDestReg).addMBB(overflowMBB);
20754 // Erase the pseudo instruction
20755 MI->eraseFromParent();
20760 MachineBasicBlock *
20761 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20763 MachineBasicBlock *MBB) const {
20764 // Emit code to save XMM registers to the stack. The ABI says that the
20765 // number of registers to save is given in %al, so it's theoretically
20766 // possible to do an indirect jump trick to avoid saving all of them,
20767 // however this code takes a simpler approach and just executes all
20768 // of the stores if %al is non-zero. It's less code, and it's probably
20769 // easier on the hardware branch predictor, and stores aren't all that
20770 // expensive anyway.
20772 // Create the new basic blocks. One block contains all the XMM stores,
20773 // and one block is the final destination regardless of whether any
20774 // stores were performed.
20775 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20776 MachineFunction *F = MBB->getParent();
20777 MachineFunction::iterator MBBIter = ++MBB->getIterator();
20778 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20779 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20780 F->insert(MBBIter, XMMSaveMBB);
20781 F->insert(MBBIter, EndMBB);
20783 // Transfer the remainder of MBB and its successor edges to EndMBB.
20784 EndMBB->splice(EndMBB->begin(), MBB,
20785 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20786 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20788 // The original block will now fall through to the XMM save block.
20789 MBB->addSuccessor(XMMSaveMBB);
20790 // The XMMSaveMBB will fall through to the end block.
20791 XMMSaveMBB->addSuccessor(EndMBB);
20793 // Now add the instructions.
20794 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20795 DebugLoc DL = MI->getDebugLoc();
20797 unsigned CountReg = MI->getOperand(0).getReg();
20798 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20799 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20801 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20802 // If %al is 0, branch around the XMM save block.
20803 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20804 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20805 MBB->addSuccessor(EndMBB);
20808 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20809 // that was just emitted, but clearly shouldn't be "saved".
20810 assert((MI->getNumOperands() <= 3 ||
20811 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20812 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20813 && "Expected last argument to be EFLAGS");
20814 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20815 // In the XMM save block, save all the XMM argument registers.
20816 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20817 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20818 MachineMemOperand *MMO = F->getMachineMemOperand(
20819 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20820 MachineMemOperand::MOStore,
20821 /*Size=*/16, /*Align=*/16);
20822 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20823 .addFrameIndex(RegSaveFrameIndex)
20824 .addImm(/*Scale=*/1)
20825 .addReg(/*IndexReg=*/0)
20826 .addImm(/*Disp=*/Offset)
20827 .addReg(/*Segment=*/0)
20828 .addReg(MI->getOperand(i).getReg())
20829 .addMemOperand(MMO);
20832 MI->eraseFromParent(); // The pseudo instruction is gone now.
20837 // The EFLAGS operand of SelectItr might be missing a kill marker
20838 // because there were multiple uses of EFLAGS, and ISel didn't know
20839 // which to mark. Figure out whether SelectItr should have had a
20840 // kill marker, and set it if it should. Returns the correct kill
20842 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20843 MachineBasicBlock* BB,
20844 const TargetRegisterInfo* TRI) {
20845 // Scan forward through BB for a use/def of EFLAGS.
20846 MachineBasicBlock::iterator miI(std::next(SelectItr));
20847 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20848 const MachineInstr& mi = *miI;
20849 if (mi.readsRegister(X86::EFLAGS))
20851 if (mi.definesRegister(X86::EFLAGS))
20852 break; // Should have kill-flag - update below.
20855 // If we hit the end of the block, check whether EFLAGS is live into a
20857 if (miI == BB->end()) {
20858 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20859 sEnd = BB->succ_end();
20860 sItr != sEnd; ++sItr) {
20861 MachineBasicBlock* succ = *sItr;
20862 if (succ->isLiveIn(X86::EFLAGS))
20867 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20868 // out. SelectMI should have a kill flag on EFLAGS.
20869 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20873 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20874 // together with other CMOV pseudo-opcodes into a single basic-block with
20875 // conditional jump around it.
20876 static bool isCMOVPseudo(MachineInstr *MI) {
20877 switch (MI->getOpcode()) {
20878 case X86::CMOV_FR32:
20879 case X86::CMOV_FR64:
20880 case X86::CMOV_GR8:
20881 case X86::CMOV_GR16:
20882 case X86::CMOV_GR32:
20883 case X86::CMOV_RFP32:
20884 case X86::CMOV_RFP64:
20885 case X86::CMOV_RFP80:
20886 case X86::CMOV_V2F64:
20887 case X86::CMOV_V2I64:
20888 case X86::CMOV_V4F32:
20889 case X86::CMOV_V4F64:
20890 case X86::CMOV_V4I64:
20891 case X86::CMOV_V16F32:
20892 case X86::CMOV_V8F32:
20893 case X86::CMOV_V8F64:
20894 case X86::CMOV_V8I64:
20895 case X86::CMOV_V8I1:
20896 case X86::CMOV_V16I1:
20897 case X86::CMOV_V32I1:
20898 case X86::CMOV_V64I1:
20906 MachineBasicBlock *
20907 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20908 MachineBasicBlock *BB) const {
20909 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20910 DebugLoc DL = MI->getDebugLoc();
20912 // To "insert" a SELECT_CC instruction, we actually have to insert the
20913 // diamond control-flow pattern. The incoming instruction knows the
20914 // destination vreg to set, the condition code register to branch on, the
20915 // true/false values to select between, and a branch opcode to use.
20916 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20917 MachineFunction::iterator It = ++BB->getIterator();
20922 // cmpTY ccX, r1, r2
20924 // fallthrough --> copy0MBB
20925 MachineBasicBlock *thisMBB = BB;
20926 MachineFunction *F = BB->getParent();
20928 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20929 // as described above, by inserting a BB, and then making a PHI at the join
20930 // point to select the true and false operands of the CMOV in the PHI.
20932 // The code also handles two different cases of multiple CMOV opcodes
20936 // In this case, there are multiple CMOVs in a row, all which are based on
20937 // the same condition setting (or the exact opposite condition setting).
20938 // In this case we can lower all the CMOVs using a single inserted BB, and
20939 // then make a number of PHIs at the join point to model the CMOVs. The only
20940 // trickiness here, is that in a case like:
20942 // t2 = CMOV cond1 t1, f1
20943 // t3 = CMOV cond1 t2, f2
20945 // when rewriting this into PHIs, we have to perform some renaming on the
20946 // temps since you cannot have a PHI operand refer to a PHI result earlier
20947 // in the same block. The "simple" but wrong lowering would be:
20949 // t2 = PHI t1(BB1), f1(BB2)
20950 // t3 = PHI t2(BB1), f2(BB2)
20952 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20953 // renaming is to note that on the path through BB1, t2 is really just a
20954 // copy of t1, and do that renaming, properly generating:
20956 // t2 = PHI t1(BB1), f1(BB2)
20957 // t3 = PHI t1(BB1), f2(BB2)
20959 // Case 2, we lower cascaded CMOVs such as
20961 // (CMOV (CMOV F, T, cc1), T, cc2)
20963 // to two successives branches. For that, we look for another CMOV as the
20964 // following instruction.
20966 // Without this, we would add a PHI between the two jumps, which ends up
20967 // creating a few copies all around. For instance, for
20969 // (sitofp (zext (fcmp une)))
20971 // we would generate:
20973 // ucomiss %xmm1, %xmm0
20974 // movss <1.0f>, %xmm0
20975 // movaps %xmm0, %xmm1
20977 // xorps %xmm1, %xmm1
20980 // movaps %xmm1, %xmm0
20984 // because this custom-inserter would have generated:
20996 // A: X = ...; Y = ...
20998 // C: Z = PHI [X, A], [Y, B]
21000 // E: PHI [X, C], [Z, D]
21002 // If we lower both CMOVs in a single step, we can instead generate:
21014 // A: X = ...; Y = ...
21016 // E: PHI [X, A], [X, C], [Y, D]
21018 // Which, in our sitofp/fcmp example, gives us something like:
21020 // ucomiss %xmm1, %xmm0
21021 // movss <1.0f>, %xmm0
21024 // xorps %xmm0, %xmm0
21028 MachineInstr *CascadedCMOV = nullptr;
21029 MachineInstr *LastCMOV = MI;
21030 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21031 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21032 MachineBasicBlock::iterator NextMIIt =
21033 std::next(MachineBasicBlock::iterator(MI));
21035 // Check for case 1, where there are multiple CMOVs with the same condition
21036 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21037 // number of jumps the most.
21039 if (isCMOVPseudo(MI)) {
21040 // See if we have a string of CMOVS with the same condition.
21041 while (NextMIIt != BB->end() &&
21042 isCMOVPseudo(NextMIIt) &&
21043 (NextMIIt->getOperand(3).getImm() == CC ||
21044 NextMIIt->getOperand(3).getImm() == OppCC)) {
21045 LastCMOV = &*NextMIIt;
21050 // This checks for case 2, but only do this if we didn't already find
21051 // case 1, as indicated by LastCMOV == MI.
21052 if (LastCMOV == MI &&
21053 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21054 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21055 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21056 CascadedCMOV = &*NextMIIt;
21059 MachineBasicBlock *jcc1MBB = nullptr;
21061 // If we have a cascaded CMOV, we lower it to two successive branches to
21062 // the same block. EFLAGS is used by both, so mark it as live in the second.
21063 if (CascadedCMOV) {
21064 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21065 F->insert(It, jcc1MBB);
21066 jcc1MBB->addLiveIn(X86::EFLAGS);
21069 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21070 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21071 F->insert(It, copy0MBB);
21072 F->insert(It, sinkMBB);
21074 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21075 // live into the sink and copy blocks.
21076 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21078 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21079 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21080 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21081 copy0MBB->addLiveIn(X86::EFLAGS);
21082 sinkMBB->addLiveIn(X86::EFLAGS);
21085 // Transfer the remainder of BB and its successor edges to sinkMBB.
21086 sinkMBB->splice(sinkMBB->begin(), BB,
21087 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21088 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21090 // Add the true and fallthrough blocks as its successors.
21091 if (CascadedCMOV) {
21092 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21093 BB->addSuccessor(jcc1MBB);
21095 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21096 // jump to the sinkMBB.
21097 jcc1MBB->addSuccessor(copy0MBB);
21098 jcc1MBB->addSuccessor(sinkMBB);
21100 BB->addSuccessor(copy0MBB);
21103 // The true block target of the first (or only) branch is always sinkMBB.
21104 BB->addSuccessor(sinkMBB);
21106 // Create the conditional branch instruction.
21107 unsigned Opc = X86::GetCondBranchFromCond(CC);
21108 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21110 if (CascadedCMOV) {
21111 unsigned Opc2 = X86::GetCondBranchFromCond(
21112 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21113 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21117 // %FalseValue = ...
21118 // # fallthrough to sinkMBB
21119 copy0MBB->addSuccessor(sinkMBB);
21122 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21124 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21125 MachineBasicBlock::iterator MIItEnd =
21126 std::next(MachineBasicBlock::iterator(LastCMOV));
21127 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21128 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21129 MachineInstrBuilder MIB;
21131 // As we are creating the PHIs, we have to be careful if there is more than
21132 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21133 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21134 // That also means that PHI construction must work forward from earlier to
21135 // later, and that the code must maintain a mapping from earlier PHI's
21136 // destination registers, and the registers that went into the PHI.
21138 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21139 unsigned DestReg = MIIt->getOperand(0).getReg();
21140 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21141 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21143 // If this CMOV we are generating is the opposite condition from
21144 // the jump we generated, then we have to swap the operands for the
21145 // PHI that is going to be generated.
21146 if (MIIt->getOperand(3).getImm() == OppCC)
21147 std::swap(Op1Reg, Op2Reg);
21149 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21150 Op1Reg = RegRewriteTable[Op1Reg].first;
21152 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21153 Op2Reg = RegRewriteTable[Op2Reg].second;
21155 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21156 TII->get(X86::PHI), DestReg)
21157 .addReg(Op1Reg).addMBB(copy0MBB)
21158 .addReg(Op2Reg).addMBB(thisMBB);
21160 // Add this PHI to the rewrite table.
21161 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21164 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21165 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21166 if (CascadedCMOV) {
21167 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21168 // Copy the PHI result to the register defined by the second CMOV.
21169 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21170 DL, TII->get(TargetOpcode::COPY),
21171 CascadedCMOV->getOperand(0).getReg())
21172 .addReg(MI->getOperand(0).getReg());
21173 CascadedCMOV->eraseFromParent();
21176 // Now remove the CMOV(s).
21177 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21178 (MIIt++)->eraseFromParent();
21183 MachineBasicBlock *
21184 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21185 MachineBasicBlock *BB) const {
21186 // Combine the following atomic floating-point modification pattern:
21187 // a.store(reg OP a.load(acquire), release)
21188 // Transform them into:
21189 // OPss (%gpr), %xmm
21190 // movss %xmm, (%gpr)
21191 // Or sd equivalent for 64-bit operations.
21193 switch (MI->getOpcode()) {
21194 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21195 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21196 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21198 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21199 DebugLoc DL = MI->getDebugLoc();
21200 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21201 MachineOperand MSrc = MI->getOperand(0);
21202 unsigned VSrc = MI->getOperand(5).getReg();
21203 const MachineOperand &Disp = MI->getOperand(3);
21204 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21205 bool hasDisp = Disp.isGlobal() || Disp.isImm();
21206 if (hasDisp && MSrc.isReg())
21207 MSrc.setIsKill(false);
21208 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21209 .addOperand(/*Base=*/MSrc)
21210 .addImm(/*Scale=*/1)
21211 .addReg(/*Index=*/0)
21212 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21214 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21215 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21217 .addOperand(/*Base=*/MSrc)
21218 .addImm(/*Scale=*/1)
21219 .addReg(/*Index=*/0)
21220 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21221 .addReg(/*Segment=*/0);
21222 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21223 MI->eraseFromParent(); // The pseudo instruction is gone now.
21227 MachineBasicBlock *
21228 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21229 MachineBasicBlock *BB) const {
21230 MachineFunction *MF = BB->getParent();
21231 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21232 DebugLoc DL = MI->getDebugLoc();
21233 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21235 assert(MF->shouldSplitStack());
21237 const bool Is64Bit = Subtarget->is64Bit();
21238 const bool IsLP64 = Subtarget->isTarget64BitLP64();
21240 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21241 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21244 // ... [Till the alloca]
21245 // If stacklet is not large enough, jump to mallocMBB
21248 // Allocate by subtracting from RSP
21249 // Jump to continueMBB
21252 // Allocate by call to runtime
21256 // [rest of original BB]
21259 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21260 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21261 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21263 MachineRegisterInfo &MRI = MF->getRegInfo();
21264 const TargetRegisterClass *AddrRegClass =
21265 getRegClassFor(getPointerTy(MF->getDataLayout()));
21267 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21268 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21269 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21270 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21271 sizeVReg = MI->getOperand(1).getReg(),
21272 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21274 MachineFunction::iterator MBBIter = ++BB->getIterator();
21276 MF->insert(MBBIter, bumpMBB);
21277 MF->insert(MBBIter, mallocMBB);
21278 MF->insert(MBBIter, continueMBB);
21280 continueMBB->splice(continueMBB->begin(), BB,
21281 std::next(MachineBasicBlock::iterator(MI)), BB->end());
21282 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21284 // Add code to the main basic block to check if the stack limit has been hit,
21285 // and if so, jump to mallocMBB otherwise to bumpMBB.
21286 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21287 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21288 .addReg(tmpSPVReg).addReg(sizeVReg);
21289 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21290 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21291 .addReg(SPLimitVReg);
21292 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21294 // bumpMBB simply decreases the stack pointer, since we know the current
21295 // stacklet has enough space.
21296 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21297 .addReg(SPLimitVReg);
21298 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21299 .addReg(SPLimitVReg);
21300 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21302 // Calls into a routine in libgcc to allocate more space from the heap.
21303 const uint32_t *RegMask =
21304 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21306 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21308 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21309 .addExternalSymbol("__morestack_allocate_stack_space")
21310 .addRegMask(RegMask)
21311 .addReg(X86::RDI, RegState::Implicit)
21312 .addReg(X86::RAX, RegState::ImplicitDefine);
21313 } else if (Is64Bit) {
21314 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21316 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21317 .addExternalSymbol("__morestack_allocate_stack_space")
21318 .addRegMask(RegMask)
21319 .addReg(X86::EDI, RegState::Implicit)
21320 .addReg(X86::EAX, RegState::ImplicitDefine);
21322 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21324 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21325 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21326 .addExternalSymbol("__morestack_allocate_stack_space")
21327 .addRegMask(RegMask)
21328 .addReg(X86::EAX, RegState::ImplicitDefine);
21332 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21335 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21336 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21337 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21339 // Set up the CFG correctly.
21340 BB->addSuccessor(bumpMBB);
21341 BB->addSuccessor(mallocMBB);
21342 mallocMBB->addSuccessor(continueMBB);
21343 bumpMBB->addSuccessor(continueMBB);
21345 // Take care of the PHI nodes.
21346 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21347 MI->getOperand(0).getReg())
21348 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21349 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21351 // Delete the original pseudo instruction.
21352 MI->eraseFromParent();
21355 return continueMBB;
21358 MachineBasicBlock *
21359 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21360 MachineBasicBlock *BB) const {
21361 DebugLoc DL = MI->getDebugLoc();
21363 assert(!Subtarget->isTargetMachO());
21365 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21368 MI->eraseFromParent(); // The pseudo instruction is gone now.
21372 MachineBasicBlock *
21373 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21374 MachineBasicBlock *BB) const {
21375 // This is pretty easy. We're taking the value that we received from
21376 // our load from the relocation, sticking it in either RDI (x86-64)
21377 // or EAX and doing an indirect call. The return value will then
21378 // be in the normal return register.
21379 MachineFunction *F = BB->getParent();
21380 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21381 DebugLoc DL = MI->getDebugLoc();
21383 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21384 assert(MI->getOperand(3).isGlobal() && "This should be a global");
21386 // Get a register mask for the lowered call.
21387 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21388 // proper register mask.
21389 const uint32_t *RegMask =
21390 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21391 if (Subtarget->is64Bit()) {
21392 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21393 TII->get(X86::MOV64rm), X86::RDI)
21395 .addImm(0).addReg(0)
21396 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21397 MI->getOperand(3).getTargetFlags())
21399 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21400 addDirectMem(MIB, X86::RDI);
21401 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21402 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21403 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21404 TII->get(X86::MOV32rm), X86::EAX)
21406 .addImm(0).addReg(0)
21407 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21408 MI->getOperand(3).getTargetFlags())
21410 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21411 addDirectMem(MIB, X86::EAX);
21412 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21414 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21415 TII->get(X86::MOV32rm), X86::EAX)
21416 .addReg(TII->getGlobalBaseReg(F))
21417 .addImm(0).addReg(0)
21418 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21419 MI->getOperand(3).getTargetFlags())
21421 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21422 addDirectMem(MIB, X86::EAX);
21423 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21426 MI->eraseFromParent(); // The pseudo instruction is gone now.
21430 MachineBasicBlock *
21431 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21432 MachineBasicBlock *MBB) const {
21433 DebugLoc DL = MI->getDebugLoc();
21434 MachineFunction *MF = MBB->getParent();
21435 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21436 MachineRegisterInfo &MRI = MF->getRegInfo();
21438 const BasicBlock *BB = MBB->getBasicBlock();
21439 MachineFunction::iterator I = ++MBB->getIterator();
21441 // Memory Reference
21442 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21443 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21446 unsigned MemOpndSlot = 0;
21448 unsigned CurOp = 0;
21450 DstReg = MI->getOperand(CurOp++).getReg();
21451 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21452 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21453 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21454 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21456 MemOpndSlot = CurOp;
21458 MVT PVT = getPointerTy(MF->getDataLayout());
21459 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21460 "Invalid Pointer Size!");
21462 // For v = setjmp(buf), we generate
21465 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21466 // SjLjSetup restoreMBB
21472 // v = phi(main, restore)
21475 // if base pointer being used, load it from frame
21478 MachineBasicBlock *thisMBB = MBB;
21479 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21480 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21481 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21482 MF->insert(I, mainMBB);
21483 MF->insert(I, sinkMBB);
21484 MF->push_back(restoreMBB);
21485 restoreMBB->setHasAddressTaken();
21487 MachineInstrBuilder MIB;
21489 // Transfer the remainder of BB and its successor edges to sinkMBB.
21490 sinkMBB->splice(sinkMBB->begin(), MBB,
21491 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21492 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21495 unsigned PtrStoreOpc = 0;
21496 unsigned LabelReg = 0;
21497 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21498 Reloc::Model RM = MF->getTarget().getRelocationModel();
21499 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21500 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21502 // Prepare IP either in reg or imm.
21503 if (!UseImmLabel) {
21504 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21505 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21506 LabelReg = MRI.createVirtualRegister(PtrRC);
21507 if (Subtarget->is64Bit()) {
21508 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21512 .addMBB(restoreMBB)
21515 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21516 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21517 .addReg(XII->getGlobalBaseReg(MF))
21520 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21524 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21526 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21527 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21528 if (i == X86::AddrDisp)
21529 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21531 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21534 MIB.addReg(LabelReg);
21536 MIB.addMBB(restoreMBB);
21537 MIB.setMemRefs(MMOBegin, MMOEnd);
21539 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21540 .addMBB(restoreMBB);
21542 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21543 MIB.addRegMask(RegInfo->getNoPreservedMask());
21544 thisMBB->addSuccessor(mainMBB);
21545 thisMBB->addSuccessor(restoreMBB);
21549 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21550 mainMBB->addSuccessor(sinkMBB);
21553 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21554 TII->get(X86::PHI), DstReg)
21555 .addReg(mainDstReg).addMBB(mainMBB)
21556 .addReg(restoreDstReg).addMBB(restoreMBB);
21559 if (RegInfo->hasBasePointer(*MF)) {
21560 const bool Uses64BitFramePtr =
21561 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21562 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21563 X86FI->setRestoreBasePointer(MF);
21564 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21565 unsigned BasePtr = RegInfo->getBaseRegister();
21566 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21567 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21568 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21569 .setMIFlag(MachineInstr::FrameSetup);
21571 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21572 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21573 restoreMBB->addSuccessor(sinkMBB);
21575 MI->eraseFromParent();
21579 MachineBasicBlock *
21580 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21581 MachineBasicBlock *MBB) const {
21582 DebugLoc DL = MI->getDebugLoc();
21583 MachineFunction *MF = MBB->getParent();
21584 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21585 MachineRegisterInfo &MRI = MF->getRegInfo();
21587 // Memory Reference
21588 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21589 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21591 MVT PVT = getPointerTy(MF->getDataLayout());
21592 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21593 "Invalid Pointer Size!");
21595 const TargetRegisterClass *RC =
21596 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21597 unsigned Tmp = MRI.createVirtualRegister(RC);
21598 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21599 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21600 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21601 unsigned SP = RegInfo->getStackRegister();
21603 MachineInstrBuilder MIB;
21605 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21606 const int64_t SPOffset = 2 * PVT.getStoreSize();
21608 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21609 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21612 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21613 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21614 MIB.addOperand(MI->getOperand(i));
21615 MIB.setMemRefs(MMOBegin, MMOEnd);
21617 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21618 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21619 if (i == X86::AddrDisp)
21620 MIB.addDisp(MI->getOperand(i), LabelOffset);
21622 MIB.addOperand(MI->getOperand(i));
21624 MIB.setMemRefs(MMOBegin, MMOEnd);
21626 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21627 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21628 if (i == X86::AddrDisp)
21629 MIB.addDisp(MI->getOperand(i), SPOffset);
21631 MIB.addOperand(MI->getOperand(i));
21633 MIB.setMemRefs(MMOBegin, MMOEnd);
21635 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21637 MI->eraseFromParent();
21641 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21642 // accumulator loops. Writing back to the accumulator allows the coalescer
21643 // to remove extra copies in the loop.
21644 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
21645 MachineBasicBlock *
21646 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21647 MachineBasicBlock *MBB) const {
21648 MachineOperand &AddendOp = MI->getOperand(3);
21650 // Bail out early if the addend isn't a register - we can't switch these.
21651 if (!AddendOp.isReg())
21654 MachineFunction &MF = *MBB->getParent();
21655 MachineRegisterInfo &MRI = MF.getRegInfo();
21657 // Check whether the addend is defined by a PHI:
21658 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21659 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21660 if (!AddendDef.isPHI())
21663 // Look for the following pattern:
21665 // %addend = phi [%entry, 0], [%loop, %result]
21667 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21671 // %addend = phi [%entry, 0], [%loop, %result]
21673 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21675 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21676 assert(AddendDef.getOperand(i).isReg());
21677 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21678 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21679 if (&PHISrcInst == MI) {
21680 // Found a matching instruction.
21681 unsigned NewFMAOpc = 0;
21682 switch (MI->getOpcode()) {
21683 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21684 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21685 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21686 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21687 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21688 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21689 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21690 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21691 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21692 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21693 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21694 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21695 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21696 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21697 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21698 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21699 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21700 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21701 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21702 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21704 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21705 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21706 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21707 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21708 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21709 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21710 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21711 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21712 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21713 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21714 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21715 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21716 default: llvm_unreachable("Unrecognized FMA variant.");
21719 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21720 MachineInstrBuilder MIB =
21721 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21722 .addOperand(MI->getOperand(0))
21723 .addOperand(MI->getOperand(3))
21724 .addOperand(MI->getOperand(2))
21725 .addOperand(MI->getOperand(1));
21726 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21727 MI->eraseFromParent();
21734 MachineBasicBlock *
21735 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21736 MachineBasicBlock *BB) const {
21737 switch (MI->getOpcode()) {
21738 default: llvm_unreachable("Unexpected instr type to insert");
21739 case X86::TAILJMPd64:
21740 case X86::TAILJMPr64:
21741 case X86::TAILJMPm64:
21742 case X86::TAILJMPd64_REX:
21743 case X86::TAILJMPr64_REX:
21744 case X86::TAILJMPm64_REX:
21745 llvm_unreachable("TAILJMP64 would not be touched here.");
21746 case X86::TCRETURNdi64:
21747 case X86::TCRETURNri64:
21748 case X86::TCRETURNmi64:
21750 case X86::WIN_ALLOCA:
21751 return EmitLoweredWinAlloca(MI, BB);
21752 case X86::SEG_ALLOCA_32:
21753 case X86::SEG_ALLOCA_64:
21754 return EmitLoweredSegAlloca(MI, BB);
21755 case X86::TLSCall_32:
21756 case X86::TLSCall_64:
21757 return EmitLoweredTLSCall(MI, BB);
21758 case X86::CMOV_FR32:
21759 case X86::CMOV_FR64:
21760 case X86::CMOV_GR8:
21761 case X86::CMOV_GR16:
21762 case X86::CMOV_GR32:
21763 case X86::CMOV_RFP32:
21764 case X86::CMOV_RFP64:
21765 case X86::CMOV_RFP80:
21766 case X86::CMOV_V2F64:
21767 case X86::CMOV_V2I64:
21768 case X86::CMOV_V4F32:
21769 case X86::CMOV_V4F64:
21770 case X86::CMOV_V4I64:
21771 case X86::CMOV_V16F32:
21772 case X86::CMOV_V8F32:
21773 case X86::CMOV_V8F64:
21774 case X86::CMOV_V8I64:
21775 case X86::CMOV_V8I1:
21776 case X86::CMOV_V16I1:
21777 case X86::CMOV_V32I1:
21778 case X86::CMOV_V64I1:
21779 return EmitLoweredSelect(MI, BB);
21781 case X86::RELEASE_FADD32mr:
21782 case X86::RELEASE_FADD64mr:
21783 return EmitLoweredAtomicFP(MI, BB);
21785 case X86::FP32_TO_INT16_IN_MEM:
21786 case X86::FP32_TO_INT32_IN_MEM:
21787 case X86::FP32_TO_INT64_IN_MEM:
21788 case X86::FP64_TO_INT16_IN_MEM:
21789 case X86::FP64_TO_INT32_IN_MEM:
21790 case X86::FP64_TO_INT64_IN_MEM:
21791 case X86::FP80_TO_INT16_IN_MEM:
21792 case X86::FP80_TO_INT32_IN_MEM:
21793 case X86::FP80_TO_INT64_IN_MEM: {
21794 MachineFunction *F = BB->getParent();
21795 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21796 DebugLoc DL = MI->getDebugLoc();
21798 // Change the floating point control register to use "round towards zero"
21799 // mode when truncating to an integer value.
21800 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21801 addFrameReference(BuildMI(*BB, MI, DL,
21802 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21804 // Load the old value of the high byte of the control word...
21806 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21807 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21810 // Set the high part to be round to zero...
21811 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21814 // Reload the modified control word now...
21815 addFrameReference(BuildMI(*BB, MI, DL,
21816 TII->get(X86::FLDCW16m)), CWFrameIdx);
21818 // Restore the memory image of control word to original value
21819 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21822 // Get the X86 opcode to use.
21824 switch (MI->getOpcode()) {
21825 default: llvm_unreachable("illegal opcode!");
21826 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21827 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21828 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21829 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21830 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21831 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21832 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21833 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21834 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21838 MachineOperand &Op = MI->getOperand(0);
21840 AM.BaseType = X86AddressMode::RegBase;
21841 AM.Base.Reg = Op.getReg();
21843 AM.BaseType = X86AddressMode::FrameIndexBase;
21844 AM.Base.FrameIndex = Op.getIndex();
21846 Op = MI->getOperand(1);
21848 AM.Scale = Op.getImm();
21849 Op = MI->getOperand(2);
21851 AM.IndexReg = Op.getImm();
21852 Op = MI->getOperand(3);
21853 if (Op.isGlobal()) {
21854 AM.GV = Op.getGlobal();
21856 AM.Disp = Op.getImm();
21858 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21859 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21861 // Reload the original control word now.
21862 addFrameReference(BuildMI(*BB, MI, DL,
21863 TII->get(X86::FLDCW16m)), CWFrameIdx);
21865 MI->eraseFromParent(); // The pseudo instruction is gone now.
21868 // String/text processing lowering.
21869 case X86::PCMPISTRM128REG:
21870 case X86::VPCMPISTRM128REG:
21871 case X86::PCMPISTRM128MEM:
21872 case X86::VPCMPISTRM128MEM:
21873 case X86::PCMPESTRM128REG:
21874 case X86::VPCMPESTRM128REG:
21875 case X86::PCMPESTRM128MEM:
21876 case X86::VPCMPESTRM128MEM:
21877 assert(Subtarget->hasSSE42() &&
21878 "Target must have SSE4.2 or AVX features enabled");
21879 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21881 // String/text processing lowering.
21882 case X86::PCMPISTRIREG:
21883 case X86::VPCMPISTRIREG:
21884 case X86::PCMPISTRIMEM:
21885 case X86::VPCMPISTRIMEM:
21886 case X86::PCMPESTRIREG:
21887 case X86::VPCMPESTRIREG:
21888 case X86::PCMPESTRIMEM:
21889 case X86::VPCMPESTRIMEM:
21890 assert(Subtarget->hasSSE42() &&
21891 "Target must have SSE4.2 or AVX features enabled");
21892 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21894 // Thread synchronization.
21896 return EmitMonitor(MI, BB, Subtarget);
21900 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21902 case X86::VASTART_SAVE_XMM_REGS:
21903 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21905 case X86::VAARG_64:
21906 return EmitVAARG64WithCustomInserter(MI, BB);
21908 case X86::EH_SjLj_SetJmp32:
21909 case X86::EH_SjLj_SetJmp64:
21910 return emitEHSjLjSetJmp(MI, BB);
21912 case X86::EH_SjLj_LongJmp32:
21913 case X86::EH_SjLj_LongJmp64:
21914 return emitEHSjLjLongJmp(MI, BB);
21916 case TargetOpcode::STATEPOINT:
21917 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21918 // this point in the process. We diverge later.
21919 return emitPatchPoint(MI, BB);
21921 case TargetOpcode::STACKMAP:
21922 case TargetOpcode::PATCHPOINT:
21923 return emitPatchPoint(MI, BB);
21925 case X86::VFMADDPDr213r:
21926 case X86::VFMADDPSr213r:
21927 case X86::VFMADDSDr213r:
21928 case X86::VFMADDSSr213r:
21929 case X86::VFMSUBPDr213r:
21930 case X86::VFMSUBPSr213r:
21931 case X86::VFMSUBSDr213r:
21932 case X86::VFMSUBSSr213r:
21933 case X86::VFNMADDPDr213r:
21934 case X86::VFNMADDPSr213r:
21935 case X86::VFNMADDSDr213r:
21936 case X86::VFNMADDSSr213r:
21937 case X86::VFNMSUBPDr213r:
21938 case X86::VFNMSUBPSr213r:
21939 case X86::VFNMSUBSDr213r:
21940 case X86::VFNMSUBSSr213r:
21941 case X86::VFMADDSUBPDr213r:
21942 case X86::VFMADDSUBPSr213r:
21943 case X86::VFMSUBADDPDr213r:
21944 case X86::VFMSUBADDPSr213r:
21945 case X86::VFMADDPDr213rY:
21946 case X86::VFMADDPSr213rY:
21947 case X86::VFMSUBPDr213rY:
21948 case X86::VFMSUBPSr213rY:
21949 case X86::VFNMADDPDr213rY:
21950 case X86::VFNMADDPSr213rY:
21951 case X86::VFNMSUBPDr213rY:
21952 case X86::VFNMSUBPSr213rY:
21953 case X86::VFMADDSUBPDr213rY:
21954 case X86::VFMADDSUBPSr213rY:
21955 case X86::VFMSUBADDPDr213rY:
21956 case X86::VFMSUBADDPSr213rY:
21957 return emitFMA3Instr(MI, BB);
21961 //===----------------------------------------------------------------------===//
21962 // X86 Optimization Hooks
21963 //===----------------------------------------------------------------------===//
21965 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21968 const SelectionDAG &DAG,
21969 unsigned Depth) const {
21970 unsigned BitWidth = KnownZero.getBitWidth();
21971 unsigned Opc = Op.getOpcode();
21972 assert((Opc >= ISD::BUILTIN_OP_END ||
21973 Opc == ISD::INTRINSIC_WO_CHAIN ||
21974 Opc == ISD::INTRINSIC_W_CHAIN ||
21975 Opc == ISD::INTRINSIC_VOID) &&
21976 "Should use MaskedValueIsZero if you don't know whether Op"
21977 " is a target node!");
21979 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21993 // These nodes' second result is a boolean.
21994 if (Op.getResNo() == 0)
21997 case X86ISD::SETCC:
21998 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22000 case ISD::INTRINSIC_WO_CHAIN: {
22001 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22002 unsigned NumLoBits = 0;
22005 case Intrinsic::x86_sse_movmsk_ps:
22006 case Intrinsic::x86_avx_movmsk_ps_256:
22007 case Intrinsic::x86_sse2_movmsk_pd:
22008 case Intrinsic::x86_avx_movmsk_pd_256:
22009 case Intrinsic::x86_mmx_pmovmskb:
22010 case Intrinsic::x86_sse2_pmovmskb_128:
22011 case Intrinsic::x86_avx2_pmovmskb: {
22012 // High bits of movmskp{s|d}, pmovmskb are known zero.
22014 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22015 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22016 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22017 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22018 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22019 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22020 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22021 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22023 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22032 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22034 const SelectionDAG &,
22035 unsigned Depth) const {
22036 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22037 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22038 return Op.getValueType().getScalarType().getSizeInBits();
22044 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22045 /// node is a GlobalAddress + offset.
22046 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22047 const GlobalValue* &GA,
22048 int64_t &Offset) const {
22049 if (N->getOpcode() == X86ISD::Wrapper) {
22050 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22051 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22052 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22056 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22059 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22060 /// same as extracting the high 128-bit part of 256-bit vector and then
22061 /// inserting the result into the low part of a new 256-bit vector
22062 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22063 EVT VT = SVOp->getValueType(0);
22064 unsigned NumElems = VT.getVectorNumElements();
22066 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22067 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22068 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22069 SVOp->getMaskElt(j) >= 0)
22075 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22076 /// same as extracting the low 128-bit part of 256-bit vector and then
22077 /// inserting the result into the high part of a new 256-bit vector
22078 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22079 EVT VT = SVOp->getValueType(0);
22080 unsigned NumElems = VT.getVectorNumElements();
22082 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22083 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22084 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22085 SVOp->getMaskElt(j) >= 0)
22091 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22092 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22093 TargetLowering::DAGCombinerInfo &DCI,
22094 const X86Subtarget* Subtarget) {
22096 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22097 SDValue V1 = SVOp->getOperand(0);
22098 SDValue V2 = SVOp->getOperand(1);
22099 EVT VT = SVOp->getValueType(0);
22100 unsigned NumElems = VT.getVectorNumElements();
22102 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22103 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22107 // V UNDEF BUILD_VECTOR UNDEF
22109 // CONCAT_VECTOR CONCAT_VECTOR
22112 // RESULT: V + zero extended
22114 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22115 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22116 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22119 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22122 // To match the shuffle mask, the first half of the mask should
22123 // be exactly the first vector, and all the rest a splat with the
22124 // first element of the second one.
22125 for (unsigned i = 0; i != NumElems/2; ++i)
22126 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22127 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22130 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22131 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22132 if (Ld->hasNUsesOfValue(1, 0)) {
22133 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22134 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22136 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22138 Ld->getPointerInfo(),
22139 Ld->getAlignment(),
22140 false/*isVolatile*/, true/*ReadMem*/,
22141 false/*WriteMem*/);
22143 // Make sure the newly-created LOAD is in the same position as Ld in
22144 // terms of dependency. We create a TokenFactor for Ld and ResNode,
22145 // and update uses of Ld's output chain to use the TokenFactor.
22146 if (Ld->hasAnyUseOfValue(1)) {
22147 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22148 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22149 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22150 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22151 SDValue(ResNode.getNode(), 1));
22154 return DAG.getBitcast(VT, ResNode);
22158 // Emit a zeroed vector and insert the desired subvector on its
22160 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22161 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22162 return DCI.CombineTo(N, InsV);
22165 //===--------------------------------------------------------------------===//
22166 // Combine some shuffles into subvector extracts and inserts:
22169 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22170 if (isShuffleHigh128VectorInsertLow(SVOp)) {
22171 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22172 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22173 return DCI.CombineTo(N, InsV);
22176 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22177 if (isShuffleLow128VectorInsertHigh(SVOp)) {
22178 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22179 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22180 return DCI.CombineTo(N, InsV);
22186 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22189 /// This is the leaf of the recursive combinine below. When we have found some
22190 /// chain of single-use x86 shuffle instructions and accumulated the combined
22191 /// shuffle mask represented by them, this will try to pattern match that mask
22192 /// into either a single instruction if there is a special purpose instruction
22193 /// for this operation, or into a PSHUFB instruction which is a fully general
22194 /// instruction but should only be used to replace chains over a certain depth.
22195 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22196 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22197 TargetLowering::DAGCombinerInfo &DCI,
22198 const X86Subtarget *Subtarget) {
22199 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22201 // Find the operand that enters the chain. Note that multiple uses are OK
22202 // here, we're not going to remove the operand we find.
22203 SDValue Input = Op.getOperand(0);
22204 while (Input.getOpcode() == ISD::BITCAST)
22205 Input = Input.getOperand(0);
22207 MVT VT = Input.getSimpleValueType();
22208 MVT RootVT = Root.getSimpleValueType();
22211 if (Mask.size() == 1) {
22212 int Index = Mask[0];
22213 assert((Index >= 0 || Index == SM_SentinelUndef ||
22214 Index == SM_SentinelZero) &&
22215 "Invalid shuffle index found!");
22217 // We may end up with an accumulated mask of size 1 as a result of
22218 // widening of shuffle operands (see function canWidenShuffleElements).
22219 // If the only shuffle index is equal to SM_SentinelZero then propagate
22220 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22221 // mask, and therefore the entire chain of shuffles can be folded away.
22222 if (Index == SM_SentinelZero)
22223 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22225 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22230 // Use the float domain if the operand type is a floating point type.
22231 bool FloatDomain = VT.isFloatingPoint();
22233 // For floating point shuffles, we don't have free copies in the shuffle
22234 // instructions or the ability to load as part of the instruction, so
22235 // canonicalize their shuffles to UNPCK or MOV variants.
22237 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22238 // vectors because it can have a load folded into it that UNPCK cannot. This
22239 // doesn't preclude something switching to the shorter encoding post-RA.
22241 // FIXME: Should teach these routines about AVX vector widths.
22242 if (FloatDomain && VT.getSizeInBits() == 128) {
22243 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22244 bool Lo = Mask.equals({0, 0});
22247 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22248 // is no slower than UNPCKLPD but has the option to fold the input operand
22249 // into even an unaligned memory load.
22250 if (Lo && Subtarget->hasSSE3()) {
22251 Shuffle = X86ISD::MOVDDUP;
22252 ShuffleVT = MVT::v2f64;
22254 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22255 // than the UNPCK variants.
22256 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22257 ShuffleVT = MVT::v4f32;
22259 if (Depth == 1 && Root->getOpcode() == Shuffle)
22260 return false; // Nothing to do!
22261 Op = DAG.getBitcast(ShuffleVT, Input);
22262 DCI.AddToWorklist(Op.getNode());
22263 if (Shuffle == X86ISD::MOVDDUP)
22264 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22266 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22267 DCI.AddToWorklist(Op.getNode());
22268 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22272 if (Subtarget->hasSSE3() &&
22273 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22274 bool Lo = Mask.equals({0, 0, 2, 2});
22275 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22276 MVT ShuffleVT = MVT::v4f32;
22277 if (Depth == 1 && Root->getOpcode() == Shuffle)
22278 return false; // Nothing to do!
22279 Op = DAG.getBitcast(ShuffleVT, Input);
22280 DCI.AddToWorklist(Op.getNode());
22281 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22282 DCI.AddToWorklist(Op.getNode());
22283 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22287 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22288 bool Lo = Mask.equals({0, 0, 1, 1});
22289 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22290 MVT ShuffleVT = MVT::v4f32;
22291 if (Depth == 1 && Root->getOpcode() == Shuffle)
22292 return false; // Nothing to do!
22293 Op = DAG.getBitcast(ShuffleVT, Input);
22294 DCI.AddToWorklist(Op.getNode());
22295 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22296 DCI.AddToWorklist(Op.getNode());
22297 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22303 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22304 // variants as none of these have single-instruction variants that are
22305 // superior to the UNPCK formulation.
22306 if (!FloatDomain && VT.getSizeInBits() == 128 &&
22307 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22308 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22309 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22311 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22312 bool Lo = Mask[0] == 0;
22313 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22314 if (Depth == 1 && Root->getOpcode() == Shuffle)
22315 return false; // Nothing to do!
22317 switch (Mask.size()) {
22319 ShuffleVT = MVT::v8i16;
22322 ShuffleVT = MVT::v16i8;
22325 llvm_unreachable("Impossible mask size!");
22327 Op = DAG.getBitcast(ShuffleVT, Input);
22328 DCI.AddToWorklist(Op.getNode());
22329 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22330 DCI.AddToWorklist(Op.getNode());
22331 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22336 // Don't try to re-form single instruction chains under any circumstances now
22337 // that we've done encoding canonicalization for them.
22341 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22342 // can replace them with a single PSHUFB instruction profitably. Intel's
22343 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22344 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22345 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22346 SmallVector<SDValue, 16> PSHUFBMask;
22347 int NumBytes = VT.getSizeInBits() / 8;
22348 int Ratio = NumBytes / Mask.size();
22349 for (int i = 0; i < NumBytes; ++i) {
22350 if (Mask[i / Ratio] == SM_SentinelUndef) {
22351 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22354 int M = Mask[i / Ratio] != SM_SentinelZero
22355 ? Ratio * Mask[i / Ratio] + i % Ratio
22357 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22359 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22360 Op = DAG.getBitcast(ByteVT, Input);
22361 DCI.AddToWorklist(Op.getNode());
22362 SDValue PSHUFBMaskOp =
22363 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22364 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22365 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22366 DCI.AddToWorklist(Op.getNode());
22367 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22372 // Failed to find any combines.
22376 /// \brief Fully generic combining of x86 shuffle instructions.
22378 /// This should be the last combine run over the x86 shuffle instructions. Once
22379 /// they have been fully optimized, this will recursively consider all chains
22380 /// of single-use shuffle instructions, build a generic model of the cumulative
22381 /// shuffle operation, and check for simpler instructions which implement this
22382 /// operation. We use this primarily for two purposes:
22384 /// 1) Collapse generic shuffles to specialized single instructions when
22385 /// equivalent. In most cases, this is just an encoding size win, but
22386 /// sometimes we will collapse multiple generic shuffles into a single
22387 /// special-purpose shuffle.
22388 /// 2) Look for sequences of shuffle instructions with 3 or more total
22389 /// instructions, and replace them with the slightly more expensive SSSE3
22390 /// PSHUFB instruction if available. We do this as the last combining step
22391 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
22392 /// a suitable short sequence of other instructions. The PHUFB will either
22393 /// use a register or have to read from memory and so is slightly (but only
22394 /// slightly) more expensive than the other shuffle instructions.
22396 /// Because this is inherently a quadratic operation (for each shuffle in
22397 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22398 /// This should never be an issue in practice as the shuffle lowering doesn't
22399 /// produce sequences of more than 8 instructions.
22401 /// FIXME: We will currently miss some cases where the redundant shuffling
22402 /// would simplify under the threshold for PSHUFB formation because of
22403 /// combine-ordering. To fix this, we should do the redundant instruction
22404 /// combining in this recursive walk.
22405 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22406 ArrayRef<int> RootMask,
22407 int Depth, bool HasPSHUFB,
22409 TargetLowering::DAGCombinerInfo &DCI,
22410 const X86Subtarget *Subtarget) {
22411 // Bound the depth of our recursive combine because this is ultimately
22412 // quadratic in nature.
22416 // Directly rip through bitcasts to find the underlying operand.
22417 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22418 Op = Op.getOperand(0);
22420 MVT VT = Op.getSimpleValueType();
22421 if (!VT.isVector())
22422 return false; // Bail if we hit a non-vector.
22424 assert(Root.getSimpleValueType().isVector() &&
22425 "Shuffles operate on vector types!");
22426 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22427 "Can only combine shuffles of the same vector register size.");
22429 if (!isTargetShuffle(Op.getOpcode()))
22431 SmallVector<int, 16> OpMask;
22433 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22434 // We only can combine unary shuffles which we can decode the mask for.
22435 if (!HaveMask || !IsUnary)
22438 assert(VT.getVectorNumElements() == OpMask.size() &&
22439 "Different mask size from vector size!");
22440 assert(((RootMask.size() > OpMask.size() &&
22441 RootMask.size() % OpMask.size() == 0) ||
22442 (OpMask.size() > RootMask.size() &&
22443 OpMask.size() % RootMask.size() == 0) ||
22444 OpMask.size() == RootMask.size()) &&
22445 "The smaller number of elements must divide the larger.");
22446 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22447 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22448 assert(((RootRatio == 1 && OpRatio == 1) ||
22449 (RootRatio == 1) != (OpRatio == 1)) &&
22450 "Must not have a ratio for both incoming and op masks!");
22452 SmallVector<int, 16> Mask;
22453 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22455 // Merge this shuffle operation's mask into our accumulated mask. Note that
22456 // this shuffle's mask will be the first applied to the input, followed by the
22457 // root mask to get us all the way to the root value arrangement. The reason
22458 // for this order is that we are recursing up the operation chain.
22459 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22460 int RootIdx = i / RootRatio;
22461 if (RootMask[RootIdx] < 0) {
22462 // This is a zero or undef lane, we're done.
22463 Mask.push_back(RootMask[RootIdx]);
22467 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22468 int OpIdx = RootMaskedIdx / OpRatio;
22469 if (OpMask[OpIdx] < 0) {
22470 // The incoming lanes are zero or undef, it doesn't matter which ones we
22472 Mask.push_back(OpMask[OpIdx]);
22476 // Ok, we have non-zero lanes, map them through.
22477 Mask.push_back(OpMask[OpIdx] * OpRatio +
22478 RootMaskedIdx % OpRatio);
22481 // See if we can recurse into the operand to combine more things.
22482 switch (Op.getOpcode()) {
22483 case X86ISD::PSHUFB:
22485 case X86ISD::PSHUFD:
22486 case X86ISD::PSHUFHW:
22487 case X86ISD::PSHUFLW:
22488 if (Op.getOperand(0).hasOneUse() &&
22489 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22490 HasPSHUFB, DAG, DCI, Subtarget))
22494 case X86ISD::UNPCKL:
22495 case X86ISD::UNPCKH:
22496 assert(Op.getOperand(0) == Op.getOperand(1) &&
22497 "We only combine unary shuffles!");
22498 // We can't check for single use, we have to check that this shuffle is the
22500 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22501 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22502 HasPSHUFB, DAG, DCI, Subtarget))
22507 // Minor canonicalization of the accumulated shuffle mask to make it easier
22508 // to match below. All this does is detect masks with squential pairs of
22509 // elements, and shrink them to the half-width mask. It does this in a loop
22510 // so it will reduce the size of the mask to the minimal width mask which
22511 // performs an equivalent shuffle.
22512 SmallVector<int, 16> WidenedMask;
22513 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22514 Mask = std::move(WidenedMask);
22515 WidenedMask.clear();
22518 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22522 /// \brief Get the PSHUF-style mask from PSHUF node.
22524 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22525 /// PSHUF-style masks that can be reused with such instructions.
22526 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22527 MVT VT = N.getSimpleValueType();
22528 SmallVector<int, 4> Mask;
22530 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22534 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22535 // matter. Check that the upper masks are repeats and remove them.
22536 if (VT.getSizeInBits() > 128) {
22537 int LaneElts = 128 / VT.getScalarSizeInBits();
22539 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22540 for (int j = 0; j < LaneElts; ++j)
22541 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22542 "Mask doesn't repeat in high 128-bit lanes!");
22544 Mask.resize(LaneElts);
22547 switch (N.getOpcode()) {
22548 case X86ISD::PSHUFD:
22550 case X86ISD::PSHUFLW:
22553 case X86ISD::PSHUFHW:
22554 Mask.erase(Mask.begin(), Mask.begin() + 4);
22555 for (int &M : Mask)
22559 llvm_unreachable("No valid shuffle instruction found!");
22563 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22565 /// We walk up the chain and look for a combinable shuffle, skipping over
22566 /// shuffles that we could hoist this shuffle's transformation past without
22567 /// altering anything.
22569 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22571 TargetLowering::DAGCombinerInfo &DCI) {
22572 assert(N.getOpcode() == X86ISD::PSHUFD &&
22573 "Called with something other than an x86 128-bit half shuffle!");
22576 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22577 // of the shuffles in the chain so that we can form a fresh chain to replace
22579 SmallVector<SDValue, 8> Chain;
22580 SDValue V = N.getOperand(0);
22581 for (; V.hasOneUse(); V = V.getOperand(0)) {
22582 switch (V.getOpcode()) {
22584 return SDValue(); // Nothing combined!
22587 // Skip bitcasts as we always know the type for the target specific
22591 case X86ISD::PSHUFD:
22592 // Found another dword shuffle.
22595 case X86ISD::PSHUFLW:
22596 // Check that the low words (being shuffled) are the identity in the
22597 // dword shuffle, and the high words are self-contained.
22598 if (Mask[0] != 0 || Mask[1] != 1 ||
22599 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22602 Chain.push_back(V);
22605 case X86ISD::PSHUFHW:
22606 // Check that the high words (being shuffled) are the identity in the
22607 // dword shuffle, and the low words are self-contained.
22608 if (Mask[2] != 2 || Mask[3] != 3 ||
22609 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22612 Chain.push_back(V);
22615 case X86ISD::UNPCKL:
22616 case X86ISD::UNPCKH:
22617 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22618 // shuffle into a preceding word shuffle.
22619 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22620 V.getSimpleValueType().getScalarType() != MVT::i16)
22623 // Search for a half-shuffle which we can combine with.
22624 unsigned CombineOp =
22625 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22626 if (V.getOperand(0) != V.getOperand(1) ||
22627 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22629 Chain.push_back(V);
22630 V = V.getOperand(0);
22632 switch (V.getOpcode()) {
22634 return SDValue(); // Nothing to combine.
22636 case X86ISD::PSHUFLW:
22637 case X86ISD::PSHUFHW:
22638 if (V.getOpcode() == CombineOp)
22641 Chain.push_back(V);
22645 V = V.getOperand(0);
22649 } while (V.hasOneUse());
22652 // Break out of the loop if we break out of the switch.
22656 if (!V.hasOneUse())
22657 // We fell out of the loop without finding a viable combining instruction.
22660 // Merge this node's mask and our incoming mask.
22661 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22662 for (int &M : Mask)
22664 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22665 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22667 // Rebuild the chain around this new shuffle.
22668 while (!Chain.empty()) {
22669 SDValue W = Chain.pop_back_val();
22671 if (V.getValueType() != W.getOperand(0).getValueType())
22672 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22674 switch (W.getOpcode()) {
22676 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22678 case X86ISD::UNPCKL:
22679 case X86ISD::UNPCKH:
22680 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22683 case X86ISD::PSHUFD:
22684 case X86ISD::PSHUFLW:
22685 case X86ISD::PSHUFHW:
22686 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22690 if (V.getValueType() != N.getValueType())
22691 V = DAG.getBitcast(N.getValueType(), V);
22693 // Return the new chain to replace N.
22697 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22700 /// We walk up the chain, skipping shuffles of the other half and looking
22701 /// through shuffles which switch halves trying to find a shuffle of the same
22702 /// pair of dwords.
22703 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22705 TargetLowering::DAGCombinerInfo &DCI) {
22707 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22708 "Called with something other than an x86 128-bit half shuffle!");
22710 unsigned CombineOpcode = N.getOpcode();
22712 // Walk up a single-use chain looking for a combinable shuffle.
22713 SDValue V = N.getOperand(0);
22714 for (; V.hasOneUse(); V = V.getOperand(0)) {
22715 switch (V.getOpcode()) {
22717 return false; // Nothing combined!
22720 // Skip bitcasts as we always know the type for the target specific
22724 case X86ISD::PSHUFLW:
22725 case X86ISD::PSHUFHW:
22726 if (V.getOpcode() == CombineOpcode)
22729 // Other-half shuffles are no-ops.
22732 // Break out of the loop if we break out of the switch.
22736 if (!V.hasOneUse())
22737 // We fell out of the loop without finding a viable combining instruction.
22740 // Combine away the bottom node as its shuffle will be accumulated into
22741 // a preceding shuffle.
22742 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22744 // Record the old value.
22747 // Merge this node's mask and our incoming mask (adjusted to account for all
22748 // the pshufd instructions encountered).
22749 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22750 for (int &M : Mask)
22752 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22753 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22755 // Check that the shuffles didn't cancel each other out. If not, we need to
22756 // combine to the new one.
22758 // Replace the combinable shuffle with the combined one, updating all users
22759 // so that we re-evaluate the chain here.
22760 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22765 /// \brief Try to combine x86 target specific shuffles.
22766 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22767 TargetLowering::DAGCombinerInfo &DCI,
22768 const X86Subtarget *Subtarget) {
22770 MVT VT = N.getSimpleValueType();
22771 SmallVector<int, 4> Mask;
22773 switch (N.getOpcode()) {
22774 case X86ISD::PSHUFD:
22775 case X86ISD::PSHUFLW:
22776 case X86ISD::PSHUFHW:
22777 Mask = getPSHUFShuffleMask(N);
22778 assert(Mask.size() == 4);
22784 // Nuke no-op shuffles that show up after combining.
22785 if (isNoopShuffleMask(Mask))
22786 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22788 // Look for simplifications involving one or two shuffle instructions.
22789 SDValue V = N.getOperand(0);
22790 switch (N.getOpcode()) {
22793 case X86ISD::PSHUFLW:
22794 case X86ISD::PSHUFHW:
22795 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22797 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22798 return SDValue(); // We combined away this shuffle, so we're done.
22800 // See if this reduces to a PSHUFD which is no more expensive and can
22801 // combine with more operations. Note that it has to at least flip the
22802 // dwords as otherwise it would have been removed as a no-op.
22803 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22804 int DMask[] = {0, 1, 2, 3};
22805 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22806 DMask[DOffset + 0] = DOffset + 1;
22807 DMask[DOffset + 1] = DOffset + 0;
22808 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22809 V = DAG.getBitcast(DVT, V);
22810 DCI.AddToWorklist(V.getNode());
22811 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22812 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22813 DCI.AddToWorklist(V.getNode());
22814 return DAG.getBitcast(VT, V);
22817 // Look for shuffle patterns which can be implemented as a single unpack.
22818 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22819 // only works when we have a PSHUFD followed by two half-shuffles.
22820 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22821 (V.getOpcode() == X86ISD::PSHUFLW ||
22822 V.getOpcode() == X86ISD::PSHUFHW) &&
22823 V.getOpcode() != N.getOpcode() &&
22825 SDValue D = V.getOperand(0);
22826 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22827 D = D.getOperand(0);
22828 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22829 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22830 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22831 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22832 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22834 for (int i = 0; i < 4; ++i) {
22835 WordMask[i + NOffset] = Mask[i] + NOffset;
22836 WordMask[i + VOffset] = VMask[i] + VOffset;
22838 // Map the word mask through the DWord mask.
22840 for (int i = 0; i < 8; ++i)
22841 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22842 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22843 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22844 // We can replace all three shuffles with an unpack.
22845 V = DAG.getBitcast(VT, D.getOperand(0));
22846 DCI.AddToWorklist(V.getNode());
22847 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22856 case X86ISD::PSHUFD:
22857 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22866 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22868 /// We combine this directly on the abstract vector shuffle nodes so it is
22869 /// easier to generically match. We also insert dummy vector shuffle nodes for
22870 /// the operands which explicitly discard the lanes which are unused by this
22871 /// operation to try to flow through the rest of the combiner the fact that
22872 /// they're unused.
22873 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22875 EVT VT = N->getValueType(0);
22877 // We only handle target-independent shuffles.
22878 // FIXME: It would be easy and harmless to use the target shuffle mask
22879 // extraction tool to support more.
22880 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22883 auto *SVN = cast<ShuffleVectorSDNode>(N);
22884 ArrayRef<int> Mask = SVN->getMask();
22885 SDValue V1 = N->getOperand(0);
22886 SDValue V2 = N->getOperand(1);
22888 // We require the first shuffle operand to be the SUB node, and the second to
22889 // be the ADD node.
22890 // FIXME: We should support the commuted patterns.
22891 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22894 // If there are other uses of these operations we can't fold them.
22895 if (!V1->hasOneUse() || !V2->hasOneUse())
22898 // Ensure that both operations have the same operands. Note that we can
22899 // commute the FADD operands.
22900 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22901 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22902 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22905 // We're looking for blends between FADD and FSUB nodes. We insist on these
22906 // nodes being lined up in a specific expected pattern.
22907 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22908 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22909 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22912 // Only specific types are legal at this point, assert so we notice if and
22913 // when these change.
22914 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22915 VT == MVT::v4f64) &&
22916 "Unknown vector type encountered!");
22918 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22921 /// PerformShuffleCombine - Performs several different shuffle combines.
22922 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22923 TargetLowering::DAGCombinerInfo &DCI,
22924 const X86Subtarget *Subtarget) {
22926 SDValue N0 = N->getOperand(0);
22927 SDValue N1 = N->getOperand(1);
22928 EVT VT = N->getValueType(0);
22930 // Don't create instructions with illegal types after legalize types has run.
22931 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22932 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22935 // If we have legalized the vector types, look for blends of FADD and FSUB
22936 // nodes that we can fuse into an ADDSUB node.
22937 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22938 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22941 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22942 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22943 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22944 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22946 // During Type Legalization, when promoting illegal vector types,
22947 // the backend might introduce new shuffle dag nodes and bitcasts.
22949 // This code performs the following transformation:
22950 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22951 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22953 // We do this only if both the bitcast and the BINOP dag nodes have
22954 // one use. Also, perform this transformation only if the new binary
22955 // operation is legal. This is to avoid introducing dag nodes that
22956 // potentially need to be further expanded (or custom lowered) into a
22957 // less optimal sequence of dag nodes.
22958 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22959 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22960 N0.getOpcode() == ISD::BITCAST) {
22961 SDValue BC0 = N0.getOperand(0);
22962 EVT SVT = BC0.getValueType();
22963 unsigned Opcode = BC0.getOpcode();
22964 unsigned NumElts = VT.getVectorNumElements();
22966 if (BC0.hasOneUse() && SVT.isVector() &&
22967 SVT.getVectorNumElements() * 2 == NumElts &&
22968 TLI.isOperationLegal(Opcode, VT)) {
22969 bool CanFold = false;
22981 unsigned SVTNumElts = SVT.getVectorNumElements();
22982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22983 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22984 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22985 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22986 CanFold = SVOp->getMaskElt(i) < 0;
22989 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22990 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22991 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22992 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22997 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22998 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22999 // consecutive, non-overlapping, and in the right order.
23000 SmallVector<SDValue, 16> Elts;
23001 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23002 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23004 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23007 if (isTargetShuffle(N->getOpcode())) {
23009 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23010 if (Shuffle.getNode())
23013 // Try recursively combining arbitrary sequences of x86 shuffle
23014 // instructions into higher-order shuffles. We do this after combining
23015 // specific PSHUF instruction sequences into their minimal form so that we
23016 // can evaluate how many specialized shuffle instructions are involved in
23017 // a particular chain.
23018 SmallVector<int, 1> NonceMask; // Just a placeholder.
23019 NonceMask.push_back(0);
23020 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23021 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23023 return SDValue(); // This routine will use CombineTo to replace N.
23029 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23030 /// specific shuffle of a load can be folded into a single element load.
23031 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23032 /// shuffles have been custom lowered so we need to handle those here.
23033 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23034 TargetLowering::DAGCombinerInfo &DCI) {
23035 if (DCI.isBeforeLegalizeOps())
23038 SDValue InVec = N->getOperand(0);
23039 SDValue EltNo = N->getOperand(1);
23041 if (!isa<ConstantSDNode>(EltNo))
23044 EVT OriginalVT = InVec.getValueType();
23046 if (InVec.getOpcode() == ISD::BITCAST) {
23047 // Don't duplicate a load with other uses.
23048 if (!InVec.hasOneUse())
23050 EVT BCVT = InVec.getOperand(0).getValueType();
23051 if (!BCVT.isVector() ||
23052 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23054 InVec = InVec.getOperand(0);
23057 EVT CurrentVT = InVec.getValueType();
23059 if (!isTargetShuffle(InVec.getOpcode()))
23062 // Don't duplicate a load with other uses.
23063 if (!InVec.hasOneUse())
23066 SmallVector<int, 16> ShuffleMask;
23068 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23069 ShuffleMask, UnaryShuffle))
23072 // Select the input vector, guarding against out of range extract vector.
23073 unsigned NumElems = CurrentVT.getVectorNumElements();
23074 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23075 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23076 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23077 : InVec.getOperand(1);
23079 // If inputs to shuffle are the same for both ops, then allow 2 uses
23080 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23081 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23083 if (LdNode.getOpcode() == ISD::BITCAST) {
23084 // Don't duplicate a load with other uses.
23085 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23088 AllowedUses = 1; // only allow 1 load use if we have a bitcast
23089 LdNode = LdNode.getOperand(0);
23092 if (!ISD::isNormalLoad(LdNode.getNode()))
23095 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23097 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23100 EVT EltVT = N->getValueType(0);
23101 // If there's a bitcast before the shuffle, check if the load type and
23102 // alignment is valid.
23103 unsigned Align = LN0->getAlignment();
23104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23105 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23106 EltVT.getTypeForEVT(*DAG.getContext()));
23108 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23111 // All checks match so transform back to vector_shuffle so that DAG combiner
23112 // can finish the job
23115 // Create shuffle node taking into account the case that its a unary shuffle
23116 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23117 : InVec.getOperand(1);
23118 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23119 InVec.getOperand(0), Shuffle,
23121 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23122 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23126 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23127 /// special and don't usually play with other vector types, it's better to
23128 /// handle them early to be sure we emit efficient code by avoiding
23129 /// store-load conversions.
23130 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
23131 if (N->getValueType(0) != MVT::x86mmx ||
23132 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
23133 N->getOperand(0)->getValueType(0) != MVT::v2i32)
23136 SDValue V = N->getOperand(0);
23137 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
23138 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
23139 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
23140 N->getValueType(0), V.getOperand(0));
23145 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23146 /// generation and convert it from being a bunch of shuffles and extracts
23147 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23148 /// storing the value and loading scalars back, while for x64 we should
23149 /// use 64-bit extracts and shifts.
23150 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23151 TargetLowering::DAGCombinerInfo &DCI) {
23152 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23155 SDValue InputVector = N->getOperand(0);
23156 SDLoc dl(InputVector);
23157 // Detect mmx to i32 conversion through a v2i32 elt extract.
23158 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23159 N->getValueType(0) == MVT::i32 &&
23160 InputVector.getValueType() == MVT::v2i32) {
23162 // The bitcast source is a direct mmx result.
23163 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23164 if (MMXSrc.getValueType() == MVT::x86mmx)
23165 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23166 N->getValueType(0),
23167 InputVector.getNode()->getOperand(0));
23169 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23170 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23171 MMXSrc.getValueType() == MVT::i64) {
23172 SDValue MMXSrcOp = MMXSrc.getOperand(0);
23173 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23174 MMXSrcOp.getValueType() == MVT::v1i64 &&
23175 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23176 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23177 N->getValueType(0), MMXSrcOp.getOperand(0));
23181 EVT VT = N->getValueType(0);
23183 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
23184 InputVector.getOpcode() == ISD::BITCAST &&
23185 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
23186 uint64_t ExtractedElt =
23187 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23188 uint64_t InputValue =
23189 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23190 uint64_t Res = (InputValue >> ExtractedElt) & 1;
23191 return DAG.getConstant(Res, dl, MVT::i1);
23193 // Only operate on vectors of 4 elements, where the alternative shuffling
23194 // gets to be more expensive.
23195 if (InputVector.getValueType() != MVT::v4i32)
23198 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23199 // single use which is a sign-extend or zero-extend, and all elements are
23201 SmallVector<SDNode *, 4> Uses;
23202 unsigned ExtractedElements = 0;
23203 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23204 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23205 if (UI.getUse().getResNo() != InputVector.getResNo())
23208 SDNode *Extract = *UI;
23209 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23212 if (Extract->getValueType(0) != MVT::i32)
23214 if (!Extract->hasOneUse())
23216 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23217 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23219 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23222 // Record which element was extracted.
23223 ExtractedElements |=
23224 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23226 Uses.push_back(Extract);
23229 // If not all the elements were used, this may not be worthwhile.
23230 if (ExtractedElements != 15)
23233 // Ok, we've now decided to do the transformation.
23234 // If 64-bit shifts are legal, use the extract-shift sequence,
23235 // otherwise bounce the vector off the cache.
23236 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23239 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23240 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23241 auto &DL = DAG.getDataLayout();
23242 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23243 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23244 DAG.getConstant(0, dl, VecIdxTy));
23245 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23246 DAG.getConstant(1, dl, VecIdxTy));
23248 SDValue ShAmt = DAG.getConstant(
23249 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23250 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23251 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23252 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23253 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23254 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23255 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23257 // Store the value to a temporary stack slot.
23258 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23259 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23260 MachinePointerInfo(), false, false, 0);
23262 EVT ElementType = InputVector.getValueType().getVectorElementType();
23263 unsigned EltSize = ElementType.getSizeInBits() / 8;
23265 // Replace each use (extract) with a load of the appropriate element.
23266 for (unsigned i = 0; i < 4; ++i) {
23267 uint64_t Offset = EltSize * i;
23268 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23269 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23271 SDValue ScalarAddr =
23272 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23274 // Load the scalar.
23275 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23276 ScalarAddr, MachinePointerInfo(),
23277 false, false, false, 0);
23282 // Replace the extracts
23283 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23284 UE = Uses.end(); UI != UE; ++UI) {
23285 SDNode *Extract = *UI;
23287 SDValue Idx = Extract->getOperand(1);
23288 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23289 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23292 // The replacement was made in place; don't return anything.
23297 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23298 const X86Subtarget *Subtarget) {
23300 SDValue Cond = N->getOperand(0);
23301 SDValue LHS = N->getOperand(1);
23302 SDValue RHS = N->getOperand(2);
23304 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23305 SDValue CondSrc = Cond->getOperand(0);
23306 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23307 Cond = CondSrc->getOperand(0);
23310 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23313 // A vselect where all conditions and data are constants can be optimized into
23314 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23315 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23316 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23319 unsigned MaskValue = 0;
23320 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23323 MVT VT = N->getSimpleValueType(0);
23324 unsigned NumElems = VT.getVectorNumElements();
23325 SmallVector<int, 8> ShuffleMask(NumElems, -1);
23326 for (unsigned i = 0; i < NumElems; ++i) {
23327 // Be sure we emit undef where we can.
23328 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23329 ShuffleMask[i] = -1;
23331 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23335 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23337 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23340 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23342 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23343 TargetLowering::DAGCombinerInfo &DCI,
23344 const X86Subtarget *Subtarget) {
23346 SDValue Cond = N->getOperand(0);
23347 // Get the LHS/RHS of the select.
23348 SDValue LHS = N->getOperand(1);
23349 SDValue RHS = N->getOperand(2);
23350 EVT VT = LHS.getValueType();
23351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23353 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23354 // instructions match the semantics of the common C idiom x<y?x:y but not
23355 // x<=y?x:y, because of how they handle negative zero (which can be
23356 // ignored in unsafe-math mode).
23357 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23358 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23359 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23360 (Subtarget->hasSSE2() ||
23361 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23362 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23364 unsigned Opcode = 0;
23365 // Check for x CC y ? x : y.
23366 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23367 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23371 // Converting this to a min would handle NaNs incorrectly, and swapping
23372 // the operands would cause it to handle comparisons between positive
23373 // and negative zero incorrectly.
23374 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23375 if (!DAG.getTarget().Options.UnsafeFPMath &&
23376 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23378 std::swap(LHS, RHS);
23380 Opcode = X86ISD::FMIN;
23383 // Converting this to a min would handle comparisons between positive
23384 // and negative zero incorrectly.
23385 if (!DAG.getTarget().Options.UnsafeFPMath &&
23386 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23388 Opcode = X86ISD::FMIN;
23391 // Converting this to a min would handle both negative zeros and NaNs
23392 // incorrectly, but we can swap the operands to fix both.
23393 std::swap(LHS, RHS);
23397 Opcode = X86ISD::FMIN;
23401 // Converting this to a max would handle comparisons between positive
23402 // and negative zero incorrectly.
23403 if (!DAG.getTarget().Options.UnsafeFPMath &&
23404 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23406 Opcode = X86ISD::FMAX;
23409 // Converting this to a max would handle NaNs incorrectly, and swapping
23410 // the operands would cause it to handle comparisons between positive
23411 // and negative zero incorrectly.
23412 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23413 if (!DAG.getTarget().Options.UnsafeFPMath &&
23414 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23416 std::swap(LHS, RHS);
23418 Opcode = X86ISD::FMAX;
23421 // Converting this to a max would handle both negative zeros and NaNs
23422 // incorrectly, but we can swap the operands to fix both.
23423 std::swap(LHS, RHS);
23427 Opcode = X86ISD::FMAX;
23430 // Check for x CC y ? y : x -- a min/max with reversed arms.
23431 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23432 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23436 // Converting this to a min would handle comparisons between positive
23437 // and negative zero incorrectly, and swapping the operands would
23438 // cause it to handle NaNs incorrectly.
23439 if (!DAG.getTarget().Options.UnsafeFPMath &&
23440 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23441 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23443 std::swap(LHS, RHS);
23445 Opcode = X86ISD::FMIN;
23448 // Converting this to a min would handle NaNs incorrectly.
23449 if (!DAG.getTarget().Options.UnsafeFPMath &&
23450 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23452 Opcode = X86ISD::FMIN;
23455 // Converting this to a min would handle both negative zeros and NaNs
23456 // incorrectly, but we can swap the operands to fix both.
23457 std::swap(LHS, RHS);
23461 Opcode = X86ISD::FMIN;
23465 // Converting this to a max would handle NaNs incorrectly.
23466 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23468 Opcode = X86ISD::FMAX;
23471 // Converting this to a max would handle comparisons between positive
23472 // and negative zero incorrectly, and swapping the operands would
23473 // cause it to handle NaNs incorrectly.
23474 if (!DAG.getTarget().Options.UnsafeFPMath &&
23475 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23476 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23478 std::swap(LHS, RHS);
23480 Opcode = X86ISD::FMAX;
23483 // Converting this to a max would handle both negative zeros and NaNs
23484 // incorrectly, but we can swap the operands to fix both.
23485 std::swap(LHS, RHS);
23489 Opcode = X86ISD::FMAX;
23495 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23498 EVT CondVT = Cond.getValueType();
23499 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23500 CondVT.getVectorElementType() == MVT::i1) {
23501 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23502 // lowering on KNL. In this case we convert it to
23503 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23504 // The same situation for all 128 and 256-bit vectors of i8 and i16.
23505 // Since SKX these selects have a proper lowering.
23506 EVT OpVT = LHS.getValueType();
23507 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23508 (OpVT.getVectorElementType() == MVT::i8 ||
23509 OpVT.getVectorElementType() == MVT::i16) &&
23510 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23511 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23512 DCI.AddToWorklist(Cond.getNode());
23513 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23516 // If this is a select between two integer constants, try to do some
23518 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23519 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23520 // Don't do this for crazy integer types.
23521 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23522 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23523 // so that TrueC (the true value) is larger than FalseC.
23524 bool NeedsCondInvert = false;
23526 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23527 // Efficiently invertible.
23528 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23529 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23530 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23531 NeedsCondInvert = true;
23532 std::swap(TrueC, FalseC);
23535 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23536 if (FalseC->getAPIntValue() == 0 &&
23537 TrueC->getAPIntValue().isPowerOf2()) {
23538 if (NeedsCondInvert) // Invert the condition if needed.
23539 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23540 DAG.getConstant(1, DL, Cond.getValueType()));
23542 // Zero extend the condition if needed.
23543 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23545 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23546 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23547 DAG.getConstant(ShAmt, DL, MVT::i8));
23550 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23551 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23552 if (NeedsCondInvert) // Invert the condition if needed.
23553 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23554 DAG.getConstant(1, DL, Cond.getValueType()));
23556 // Zero extend the condition if needed.
23557 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23558 FalseC->getValueType(0), Cond);
23559 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23560 SDValue(FalseC, 0));
23563 // Optimize cases that will turn into an LEA instruction. This requires
23564 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23565 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23566 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23567 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23569 bool isFastMultiplier = false;
23571 switch ((unsigned char)Diff) {
23573 case 1: // result = add base, cond
23574 case 2: // result = lea base( , cond*2)
23575 case 3: // result = lea base(cond, cond*2)
23576 case 4: // result = lea base( , cond*4)
23577 case 5: // result = lea base(cond, cond*4)
23578 case 8: // result = lea base( , cond*8)
23579 case 9: // result = lea base(cond, cond*8)
23580 isFastMultiplier = true;
23585 if (isFastMultiplier) {
23586 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23587 if (NeedsCondInvert) // Invert the condition if needed.
23588 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23589 DAG.getConstant(1, DL, Cond.getValueType()));
23591 // Zero extend the condition if needed.
23592 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23594 // Scale the condition by the difference.
23596 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23597 DAG.getConstant(Diff, DL,
23598 Cond.getValueType()));
23600 // Add the base if non-zero.
23601 if (FalseC->getAPIntValue() != 0)
23602 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23603 SDValue(FalseC, 0));
23610 // Canonicalize max and min:
23611 // (x > y) ? x : y -> (x >= y) ? x : y
23612 // (x < y) ? x : y -> (x <= y) ? x : y
23613 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23614 // the need for an extra compare
23615 // against zero. e.g.
23616 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23618 // testl %edi, %edi
23620 // cmovgl %edi, %eax
23624 // cmovsl %eax, %edi
23625 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23626 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23627 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23628 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23633 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23634 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23635 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23636 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23641 // Early exit check
23642 if (!TLI.isTypeLegal(VT))
23645 // Match VSELECTs into subs with unsigned saturation.
23646 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23647 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23648 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23649 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23650 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23652 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23653 // left side invert the predicate to simplify logic below.
23655 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23657 CC = ISD::getSetCCInverse(CC, true);
23658 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23662 if (Other.getNode() && Other->getNumOperands() == 2 &&
23663 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23664 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23665 SDValue CondRHS = Cond->getOperand(1);
23667 // Look for a general sub with unsigned saturation first.
23668 // x >= y ? x-y : 0 --> subus x, y
23669 // x > y ? x-y : 0 --> subus x, y
23670 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23671 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23672 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23674 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23675 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23676 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23677 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23678 // If the RHS is a constant we have to reverse the const
23679 // canonicalization.
23680 // x > C-1 ? x+-C : 0 --> subus x, C
23681 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23682 CondRHSConst->getAPIntValue() ==
23683 (-OpRHSConst->getAPIntValue() - 1))
23684 return DAG.getNode(
23685 X86ISD::SUBUS, DL, VT, OpLHS,
23686 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23688 // Another special case: If C was a sign bit, the sub has been
23689 // canonicalized into a xor.
23690 // FIXME: Would it be better to use computeKnownBits to determine
23691 // whether it's safe to decanonicalize the xor?
23692 // x s< 0 ? x^C : 0 --> subus x, C
23693 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23694 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23695 OpRHSConst->getAPIntValue().isSignBit())
23696 // Note that we have to rebuild the RHS constant here to ensure we
23697 // don't rely on particular values of undef lanes.
23698 return DAG.getNode(
23699 X86ISD::SUBUS, DL, VT, OpLHS,
23700 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23705 // Simplify vector selection if condition value type matches vselect
23707 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23708 assert(Cond.getValueType().isVector() &&
23709 "vector select expects a vector selector!");
23711 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23712 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23714 // Try invert the condition if true value is not all 1s and false value
23716 if (!TValIsAllOnes && !FValIsAllZeros &&
23717 // Check if the selector will be produced by CMPP*/PCMP*
23718 Cond.getOpcode() == ISD::SETCC &&
23719 // Check if SETCC has already been promoted
23720 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23722 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23723 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23725 if (TValIsAllZeros || FValIsAllOnes) {
23726 SDValue CC = Cond.getOperand(2);
23727 ISD::CondCode NewCC =
23728 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23729 Cond.getOperand(0).getValueType().isInteger());
23730 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23731 std::swap(LHS, RHS);
23732 TValIsAllOnes = FValIsAllOnes;
23733 FValIsAllZeros = TValIsAllZeros;
23737 if (TValIsAllOnes || FValIsAllZeros) {
23740 if (TValIsAllOnes && FValIsAllZeros)
23742 else if (TValIsAllOnes)
23744 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23745 else if (FValIsAllZeros)
23746 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23747 DAG.getBitcast(CondVT, LHS));
23749 return DAG.getBitcast(VT, Ret);
23753 // We should generate an X86ISD::BLENDI from a vselect if its argument
23754 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23755 // constants. This specific pattern gets generated when we split a
23756 // selector for a 512 bit vector in a machine without AVX512 (but with
23757 // 256-bit vectors), during legalization:
23759 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23761 // Iff we find this pattern and the build_vectors are built from
23762 // constants, we translate the vselect into a shuffle_vector that we
23763 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23764 if ((N->getOpcode() == ISD::VSELECT ||
23765 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23766 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23767 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23768 if (Shuffle.getNode())
23772 // If this is a *dynamic* select (non-constant condition) and we can match
23773 // this node with one of the variable blend instructions, restructure the
23774 // condition so that the blends can use the high bit of each element and use
23775 // SimplifyDemandedBits to simplify the condition operand.
23776 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23777 !DCI.isBeforeLegalize() &&
23778 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23779 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23781 // Don't optimize vector selects that map to mask-registers.
23785 // We can only handle the cases where VSELECT is directly legal on the
23786 // subtarget. We custom lower VSELECT nodes with constant conditions and
23787 // this makes it hard to see whether a dynamic VSELECT will correctly
23788 // lower, so we both check the operation's status and explicitly handle the
23789 // cases where a *dynamic* blend will fail even though a constant-condition
23790 // blend could be custom lowered.
23791 // FIXME: We should find a better way to handle this class of problems.
23792 // Potentially, we should combine constant-condition vselect nodes
23793 // pre-legalization into shuffles and not mark as many types as custom
23795 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23797 // FIXME: We don't support i16-element blends currently. We could and
23798 // should support them by making *all* the bits in the condition be set
23799 // rather than just the high bit and using an i8-element blend.
23800 if (VT.getScalarType() == MVT::i16)
23802 // Dynamic blending was only available from SSE4.1 onward.
23803 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23805 // Byte blends are only available in AVX2
23806 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23807 !Subtarget->hasAVX2())
23810 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23811 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23813 APInt KnownZero, KnownOne;
23814 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23815 DCI.isBeforeLegalizeOps());
23816 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23817 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23819 // If we changed the computation somewhere in the DAG, this change
23820 // will affect all users of Cond.
23821 // Make sure it is fine and update all the nodes so that we do not
23822 // use the generic VSELECT anymore. Otherwise, we may perform
23823 // wrong optimizations as we messed up with the actual expectation
23824 // for the vector boolean values.
23825 if (Cond != TLO.Old) {
23826 // Check all uses of that condition operand to check whether it will be
23827 // consumed by non-BLEND instructions, which may depend on all bits are
23829 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23831 if (I->getOpcode() != ISD::VSELECT)
23832 // TODO: Add other opcodes eventually lowered into BLEND.
23835 // Update all the users of the condition, before committing the change,
23836 // so that the VSELECT optimizations that expect the correct vector
23837 // boolean value will not be triggered.
23838 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23840 DAG.ReplaceAllUsesOfValueWith(
23842 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23843 Cond, I->getOperand(1), I->getOperand(2)));
23844 DCI.CommitTargetLoweringOpt(TLO);
23847 // At this point, only Cond is changed. Change the condition
23848 // just for N to keep the opportunity to optimize all other
23849 // users their own way.
23850 DAG.ReplaceAllUsesOfValueWith(
23852 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23853 TLO.New, N->getOperand(1), N->getOperand(2)));
23861 // Check whether a boolean test is testing a boolean value generated by
23862 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23865 // Simplify the following patterns:
23866 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23867 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23868 // to (Op EFLAGS Cond)
23870 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23871 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23872 // to (Op EFLAGS !Cond)
23874 // where Op could be BRCOND or CMOV.
23876 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23877 // Quit if not CMP and SUB with its value result used.
23878 if (Cmp.getOpcode() != X86ISD::CMP &&
23879 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23882 // Quit if not used as a boolean value.
23883 if (CC != X86::COND_E && CC != X86::COND_NE)
23886 // Check CMP operands. One of them should be 0 or 1 and the other should be
23887 // an SetCC or extended from it.
23888 SDValue Op1 = Cmp.getOperand(0);
23889 SDValue Op2 = Cmp.getOperand(1);
23892 const ConstantSDNode* C = nullptr;
23893 bool needOppositeCond = (CC == X86::COND_E);
23894 bool checkAgainstTrue = false; // Is it a comparison against 1?
23896 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23898 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23900 else // Quit if all operands are not constants.
23903 if (C->getZExtValue() == 1) {
23904 needOppositeCond = !needOppositeCond;
23905 checkAgainstTrue = true;
23906 } else if (C->getZExtValue() != 0)
23907 // Quit if the constant is neither 0 or 1.
23910 bool truncatedToBoolWithAnd = false;
23911 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23912 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23913 SetCC.getOpcode() == ISD::TRUNCATE ||
23914 SetCC.getOpcode() == ISD::AND) {
23915 if (SetCC.getOpcode() == ISD::AND) {
23917 ConstantSDNode *CS;
23918 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23919 CS->getZExtValue() == 1)
23921 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23922 CS->getZExtValue() == 1)
23926 SetCC = SetCC.getOperand(OpIdx);
23927 truncatedToBoolWithAnd = true;
23929 SetCC = SetCC.getOperand(0);
23932 switch (SetCC.getOpcode()) {
23933 case X86ISD::SETCC_CARRY:
23934 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23935 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23936 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23937 // truncated to i1 using 'and'.
23938 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23940 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23941 "Invalid use of SETCC_CARRY!");
23943 case X86ISD::SETCC:
23944 // Set the condition code or opposite one if necessary.
23945 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23946 if (needOppositeCond)
23947 CC = X86::GetOppositeBranchCondition(CC);
23948 return SetCC.getOperand(1);
23949 case X86ISD::CMOV: {
23950 // Check whether false/true value has canonical one, i.e. 0 or 1.
23951 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23952 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23953 // Quit if true value is not a constant.
23956 // Quit if false value is not a constant.
23958 SDValue Op = SetCC.getOperand(0);
23959 // Skip 'zext' or 'trunc' node.
23960 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23961 Op.getOpcode() == ISD::TRUNCATE)
23962 Op = Op.getOperand(0);
23963 // A special case for rdrand/rdseed, where 0 is set if false cond is
23965 if ((Op.getOpcode() != X86ISD::RDRAND &&
23966 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23969 // Quit if false value is not the constant 0 or 1.
23970 bool FValIsFalse = true;
23971 if (FVal && FVal->getZExtValue() != 0) {
23972 if (FVal->getZExtValue() != 1)
23974 // If FVal is 1, opposite cond is needed.
23975 needOppositeCond = !needOppositeCond;
23976 FValIsFalse = false;
23978 // Quit if TVal is not the constant opposite of FVal.
23979 if (FValIsFalse && TVal->getZExtValue() != 1)
23981 if (!FValIsFalse && TVal->getZExtValue() != 0)
23983 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23984 if (needOppositeCond)
23985 CC = X86::GetOppositeBranchCondition(CC);
23986 return SetCC.getOperand(3);
23993 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23995 /// (X86or (X86setcc) (X86setcc))
23996 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23997 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23998 X86::CondCode &CC1, SDValue &Flags,
24000 if (Cond->getOpcode() == X86ISD::CMP) {
24001 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24002 if (!CondOp1C || !CondOp1C->isNullValue())
24005 Cond = Cond->getOperand(0);
24010 SDValue SetCC0, SetCC1;
24011 switch (Cond->getOpcode()) {
24012 default: return false;
24019 SetCC0 = Cond->getOperand(0);
24020 SetCC1 = Cond->getOperand(1);
24024 // Make sure we have SETCC nodes, using the same flags value.
24025 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24026 SetCC1.getOpcode() != X86ISD::SETCC ||
24027 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24030 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24031 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24032 Flags = SetCC0->getOperand(1);
24036 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24037 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24038 TargetLowering::DAGCombinerInfo &DCI,
24039 const X86Subtarget *Subtarget) {
24042 // If the flag operand isn't dead, don't touch this CMOV.
24043 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24046 SDValue FalseOp = N->getOperand(0);
24047 SDValue TrueOp = N->getOperand(1);
24048 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24049 SDValue Cond = N->getOperand(3);
24051 if (CC == X86::COND_E || CC == X86::COND_NE) {
24052 switch (Cond.getOpcode()) {
24056 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24057 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24058 return (CC == X86::COND_E) ? FalseOp : TrueOp;
24064 Flags = checkBoolTestSetCCCombine(Cond, CC);
24065 if (Flags.getNode() &&
24066 // Extra check as FCMOV only supports a subset of X86 cond.
24067 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24068 SDValue Ops[] = { FalseOp, TrueOp,
24069 DAG.getConstant(CC, DL, MVT::i8), Flags };
24070 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24073 // If this is a select between two integer constants, try to do some
24074 // optimizations. Note that the operands are ordered the opposite of SELECT
24076 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24077 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24078 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24079 // larger than FalseC (the false value).
24080 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24081 CC = X86::GetOppositeBranchCondition(CC);
24082 std::swap(TrueC, FalseC);
24083 std::swap(TrueOp, FalseOp);
24086 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
24087 // This is efficient for any integer data type (including i8/i16) and
24089 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24090 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24091 DAG.getConstant(CC, DL, MVT::i8), Cond);
24093 // Zero extend the condition if needed.
24094 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24096 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24097 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24098 DAG.getConstant(ShAmt, DL, MVT::i8));
24099 if (N->getNumValues() == 2) // Dead flag value?
24100 return DCI.CombineTo(N, Cond, SDValue());
24104 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
24105 // for any integer data type, including i8/i16.
24106 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24107 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24108 DAG.getConstant(CC, DL, MVT::i8), Cond);
24110 // Zero extend the condition if needed.
24111 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24112 FalseC->getValueType(0), Cond);
24113 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24114 SDValue(FalseC, 0));
24116 if (N->getNumValues() == 2) // Dead flag value?
24117 return DCI.CombineTo(N, Cond, SDValue());
24121 // Optimize cases that will turn into an LEA instruction. This requires
24122 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24123 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24124 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24125 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24127 bool isFastMultiplier = false;
24129 switch ((unsigned char)Diff) {
24131 case 1: // result = add base, cond
24132 case 2: // result = lea base( , cond*2)
24133 case 3: // result = lea base(cond, cond*2)
24134 case 4: // result = lea base( , cond*4)
24135 case 5: // result = lea base(cond, cond*4)
24136 case 8: // result = lea base( , cond*8)
24137 case 9: // result = lea base(cond, cond*8)
24138 isFastMultiplier = true;
24143 if (isFastMultiplier) {
24144 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24145 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24146 DAG.getConstant(CC, DL, MVT::i8), Cond);
24147 // Zero extend the condition if needed.
24148 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24150 // Scale the condition by the difference.
24152 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24153 DAG.getConstant(Diff, DL, Cond.getValueType()));
24155 // Add the base if non-zero.
24156 if (FalseC->getAPIntValue() != 0)
24157 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24158 SDValue(FalseC, 0));
24159 if (N->getNumValues() == 2) // Dead flag value?
24160 return DCI.CombineTo(N, Cond, SDValue());
24167 // Handle these cases:
24168 // (select (x != c), e, c) -> select (x != c), e, x),
24169 // (select (x == c), c, e) -> select (x == c), x, e)
24170 // where the c is an integer constant, and the "select" is the combination
24171 // of CMOV and CMP.
24173 // The rationale for this change is that the conditional-move from a constant
24174 // needs two instructions, however, conditional-move from a register needs
24175 // only one instruction.
24177 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24178 // some instruction-combining opportunities. This opt needs to be
24179 // postponed as late as possible.
24181 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24182 // the DCI.xxxx conditions are provided to postpone the optimization as
24183 // late as possible.
24185 ConstantSDNode *CmpAgainst = nullptr;
24186 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24187 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24188 !isa<ConstantSDNode>(Cond.getOperand(0))) {
24190 if (CC == X86::COND_NE &&
24191 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24192 CC = X86::GetOppositeBranchCondition(CC);
24193 std::swap(TrueOp, FalseOp);
24196 if (CC == X86::COND_E &&
24197 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24198 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24199 DAG.getConstant(CC, DL, MVT::i8), Cond };
24200 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24205 // Fold and/or of setcc's to double CMOV:
24206 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24207 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24209 // This combine lets us generate:
24210 // cmovcc1 (jcc1 if we don't have CMOV)
24216 // cmovne (jne if we don't have CMOV)
24217 // When we can't use the CMOV instruction, it might increase branch
24219 // When we can use CMOV, or when there is no mispredict, this improves
24220 // throughput and reduces register pressure.
24222 if (CC == X86::COND_NE) {
24224 X86::CondCode CC0, CC1;
24226 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24228 std::swap(FalseOp, TrueOp);
24229 CC0 = X86::GetOppositeBranchCondition(CC0);
24230 CC1 = X86::GetOppositeBranchCondition(CC1);
24233 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24235 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24236 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24237 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24238 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24246 /// PerformMulCombine - Optimize a single multiply with constant into two
24247 /// in order to implement it with two cheaper instructions, e.g.
24248 /// LEA + SHL, LEA + LEA.
24249 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24250 TargetLowering::DAGCombinerInfo &DCI) {
24251 // An imul is usually smaller than the alternative sequence.
24252 if (DAG.getMachineFunction().getFunction()->optForMinSize())
24255 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24258 EVT VT = N->getValueType(0);
24259 if (VT != MVT::i64 && VT != MVT::i32)
24262 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24265 uint64_t MulAmt = C->getZExtValue();
24266 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24269 uint64_t MulAmt1 = 0;
24270 uint64_t MulAmt2 = 0;
24271 if ((MulAmt % 9) == 0) {
24273 MulAmt2 = MulAmt / 9;
24274 } else if ((MulAmt % 5) == 0) {
24276 MulAmt2 = MulAmt / 5;
24277 } else if ((MulAmt % 3) == 0) {
24279 MulAmt2 = MulAmt / 3;
24282 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24285 if (isPowerOf2_64(MulAmt2) &&
24286 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24287 // If second multiplifer is pow2, issue it first. We want the multiply by
24288 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24290 std::swap(MulAmt1, MulAmt2);
24293 if (isPowerOf2_64(MulAmt1))
24294 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24295 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24297 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24298 DAG.getConstant(MulAmt1, DL, VT));
24300 if (isPowerOf2_64(MulAmt2))
24301 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24302 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24304 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24305 DAG.getConstant(MulAmt2, DL, VT));
24307 // Do not add new nodes to DAG combiner worklist.
24308 DCI.CombineTo(N, NewMul, false);
24313 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24314 SDValue N0 = N->getOperand(0);
24315 SDValue N1 = N->getOperand(1);
24316 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24317 EVT VT = N0.getValueType();
24319 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24320 // since the result of setcc_c is all zero's or all ones.
24321 if (VT.isInteger() && !VT.isVector() &&
24322 N1C && N0.getOpcode() == ISD::AND &&
24323 N0.getOperand(1).getOpcode() == ISD::Constant) {
24324 SDValue N00 = N0.getOperand(0);
24325 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24326 APInt ShAmt = N1C->getAPIntValue();
24327 Mask = Mask.shl(ShAmt);
24328 bool MaskOK = false;
24329 // We can handle cases concerning bit-widening nodes containing setcc_c if
24330 // we carefully interrogate the mask to make sure we are semantics
24332 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24333 // of the underlying setcc_c operation if the setcc_c was zero extended.
24334 // Consider the following example:
24335 // zext(setcc_c) -> i32 0x0000FFFF
24336 // c1 -> i32 0x0000FFFF
24337 // c2 -> i32 0x00000001
24338 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24339 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
24340 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24342 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24343 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24345 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24346 N00.getOpcode() == ISD::ANY_EXTEND) &&
24347 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24348 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24350 if (MaskOK && Mask != 0) {
24352 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24356 // Hardware support for vector shifts is sparse which makes us scalarize the
24357 // vector operations in many cases. Also, on sandybridge ADD is faster than
24359 // (shl V, 1) -> add V,V
24360 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24361 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24362 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24363 // We shift all of the values by one. In many cases we do not have
24364 // hardware support for this operation. This is better expressed as an ADD
24366 if (N1SplatC->getAPIntValue() == 1)
24367 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24373 /// \brief Returns a vector of 0s if the node in input is a vector logical
24374 /// shift by a constant amount which is known to be bigger than or equal
24375 /// to the vector element size in bits.
24376 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24377 const X86Subtarget *Subtarget) {
24378 EVT VT = N->getValueType(0);
24380 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24381 (!Subtarget->hasInt256() ||
24382 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24385 SDValue Amt = N->getOperand(1);
24387 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24388 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24389 APInt ShiftAmt = AmtSplat->getAPIntValue();
24390 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24392 // SSE2/AVX2 logical shifts always return a vector of 0s
24393 // if the shift amount is bigger than or equal to
24394 // the element size. The constant shift amount will be
24395 // encoded as a 8-bit immediate.
24396 if (ShiftAmt.trunc(8).uge(MaxAmount))
24397 return getZeroVector(VT, Subtarget, DAG, DL);
24403 /// PerformShiftCombine - Combine shifts.
24404 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24405 TargetLowering::DAGCombinerInfo &DCI,
24406 const X86Subtarget *Subtarget) {
24407 if (N->getOpcode() == ISD::SHL)
24408 if (SDValue V = PerformSHLCombine(N, DAG))
24411 // Try to fold this logical shift into a zero vector.
24412 if (N->getOpcode() != ISD::SRA)
24413 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24419 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24420 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24421 // and friends. Likewise for OR -> CMPNEQSS.
24422 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24423 TargetLowering::DAGCombinerInfo &DCI,
24424 const X86Subtarget *Subtarget) {
24427 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24428 // we're requiring SSE2 for both.
24429 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24430 SDValue N0 = N->getOperand(0);
24431 SDValue N1 = N->getOperand(1);
24432 SDValue CMP0 = N0->getOperand(1);
24433 SDValue CMP1 = N1->getOperand(1);
24436 // The SETCCs should both refer to the same CMP.
24437 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24440 SDValue CMP00 = CMP0->getOperand(0);
24441 SDValue CMP01 = CMP0->getOperand(1);
24442 EVT VT = CMP00.getValueType();
24444 if (VT == MVT::f32 || VT == MVT::f64) {
24445 bool ExpectingFlags = false;
24446 // Check for any users that want flags:
24447 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24448 !ExpectingFlags && UI != UE; ++UI)
24449 switch (UI->getOpcode()) {
24454 ExpectingFlags = true;
24456 case ISD::CopyToReg:
24457 case ISD::SIGN_EXTEND:
24458 case ISD::ZERO_EXTEND:
24459 case ISD::ANY_EXTEND:
24463 if (!ExpectingFlags) {
24464 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24465 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24467 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24468 X86::CondCode tmp = cc0;
24473 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24474 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24475 // FIXME: need symbolic constants for these magic numbers.
24476 // See X86ATTInstPrinter.cpp:printSSECC().
24477 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24478 if (Subtarget->hasAVX512()) {
24479 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24481 DAG.getConstant(x86cc, DL, MVT::i8));
24482 if (N->getValueType(0) != MVT::i1)
24483 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24487 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24488 CMP00.getValueType(), CMP00, CMP01,
24489 DAG.getConstant(x86cc, DL,
24492 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24493 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24495 if (is64BitFP && !Subtarget->is64Bit()) {
24496 // On a 32-bit target, we cannot bitcast the 64-bit float to a
24497 // 64-bit integer, since that's not a legal type. Since
24498 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24499 // bits, but can do this little dance to extract the lowest 32 bits
24500 // and work with those going forward.
24501 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24503 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24504 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24505 Vector32, DAG.getIntPtrConstant(0, DL));
24509 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24510 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24511 DAG.getConstant(1, DL, IntVT));
24512 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24514 return OneBitOfTruth;
24522 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24523 /// so it can be folded inside ANDNP.
24524 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24525 EVT VT = N->getValueType(0);
24527 // Match direct AllOnes for 128 and 256-bit vectors
24528 if (ISD::isBuildVectorAllOnes(N))
24531 // Look through a bit convert.
24532 if (N->getOpcode() == ISD::BITCAST)
24533 N = N->getOperand(0).getNode();
24535 // Sometimes the operand may come from a insert_subvector building a 256-bit
24537 if (VT.is256BitVector() &&
24538 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24539 SDValue V1 = N->getOperand(0);
24540 SDValue V2 = N->getOperand(1);
24542 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24543 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24544 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24545 ISD::isBuildVectorAllOnes(V2.getNode()))
24552 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24553 // register. In most cases we actually compare or select YMM-sized registers
24554 // and mixing the two types creates horrible code. This method optimizes
24555 // some of the transition sequences.
24556 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24557 TargetLowering::DAGCombinerInfo &DCI,
24558 const X86Subtarget *Subtarget) {
24559 EVT VT = N->getValueType(0);
24560 if (!VT.is256BitVector())
24563 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24564 N->getOpcode() == ISD::ZERO_EXTEND ||
24565 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24567 SDValue Narrow = N->getOperand(0);
24568 EVT NarrowVT = Narrow->getValueType(0);
24569 if (!NarrowVT.is128BitVector())
24572 if (Narrow->getOpcode() != ISD::XOR &&
24573 Narrow->getOpcode() != ISD::AND &&
24574 Narrow->getOpcode() != ISD::OR)
24577 SDValue N0 = Narrow->getOperand(0);
24578 SDValue N1 = Narrow->getOperand(1);
24581 // The Left side has to be a trunc.
24582 if (N0.getOpcode() != ISD::TRUNCATE)
24585 // The type of the truncated inputs.
24586 EVT WideVT = N0->getOperand(0)->getValueType(0);
24590 // The right side has to be a 'trunc' or a constant vector.
24591 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24592 ConstantSDNode *RHSConstSplat = nullptr;
24593 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24594 RHSConstSplat = RHSBV->getConstantSplatNode();
24595 if (!RHSTrunc && !RHSConstSplat)
24598 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24600 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24603 // Set N0 and N1 to hold the inputs to the new wide operation.
24604 N0 = N0->getOperand(0);
24605 if (RHSConstSplat) {
24606 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24607 SDValue(RHSConstSplat, 0));
24608 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24609 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24610 } else if (RHSTrunc) {
24611 N1 = N1->getOperand(0);
24614 // Generate the wide operation.
24615 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24616 unsigned Opcode = N->getOpcode();
24618 case ISD::ANY_EXTEND:
24620 case ISD::ZERO_EXTEND: {
24621 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24622 APInt Mask = APInt::getAllOnesValue(InBits);
24623 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24624 return DAG.getNode(ISD::AND, DL, VT,
24625 Op, DAG.getConstant(Mask, DL, VT));
24627 case ISD::SIGN_EXTEND:
24628 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24629 Op, DAG.getValueType(NarrowVT));
24631 llvm_unreachable("Unexpected opcode");
24635 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24636 TargetLowering::DAGCombinerInfo &DCI,
24637 const X86Subtarget *Subtarget) {
24638 SDValue N0 = N->getOperand(0);
24639 SDValue N1 = N->getOperand(1);
24642 // A vector zext_in_reg may be represented as a shuffle,
24643 // feeding into a bitcast (this represents anyext) feeding into
24644 // an and with a mask.
24645 // We'd like to try to combine that into a shuffle with zero
24646 // plus a bitcast, removing the and.
24647 if (N0.getOpcode() != ISD::BITCAST ||
24648 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24651 // The other side of the AND should be a splat of 2^C, where C
24652 // is the number of bits in the source type.
24653 if (N1.getOpcode() == ISD::BITCAST)
24654 N1 = N1.getOperand(0);
24655 if (N1.getOpcode() != ISD::BUILD_VECTOR)
24657 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24659 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24660 EVT SrcType = Shuffle->getValueType(0);
24662 // We expect a single-source shuffle
24663 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24666 unsigned SrcSize = SrcType.getScalarSizeInBits();
24668 APInt SplatValue, SplatUndef;
24669 unsigned SplatBitSize;
24671 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24672 SplatBitSize, HasAnyUndefs))
24675 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24676 // Make sure the splat matches the mask we expect
24677 if (SplatBitSize > ResSize ||
24678 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24681 // Make sure the input and output size make sense
24682 if (SrcSize >= ResSize || ResSize % SrcSize)
24685 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24686 // The number of u's between each two values depends on the ratio between
24687 // the source and dest type.
24688 unsigned ZextRatio = ResSize / SrcSize;
24689 bool IsZext = true;
24690 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24691 if (i % ZextRatio) {
24692 if (Shuffle->getMaskElt(i) > 0) {
24698 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24699 // Expected element number
24709 // Ok, perform the transformation - replace the shuffle with
24710 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24711 // (instead of undef) where the k elements come from the zero vector.
24712 SmallVector<int, 8> Mask;
24713 unsigned NumElems = SrcType.getVectorNumElements();
24714 for (unsigned i = 0; i < NumElems; ++i)
24716 Mask.push_back(NumElems);
24718 Mask.push_back(i / ZextRatio);
24720 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24721 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24722 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24725 /// If both input operands of a logic op are being cast from floating point
24726 /// types, try to convert this into a floating point logic node to avoid
24727 /// unnecessary moves from SSE to integer registers.
24728 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24729 const X86Subtarget *Subtarget) {
24730 unsigned FPOpcode = ISD::DELETED_NODE;
24731 if (N->getOpcode() == ISD::AND)
24732 FPOpcode = X86ISD::FAND;
24733 else if (N->getOpcode() == ISD::OR)
24734 FPOpcode = X86ISD::FOR;
24735 else if (N->getOpcode() == ISD::XOR)
24736 FPOpcode = X86ISD::FXOR;
24738 assert(FPOpcode != ISD::DELETED_NODE &&
24739 "Unexpected input node for FP logic conversion");
24741 EVT VT = N->getValueType(0);
24742 SDValue N0 = N->getOperand(0);
24743 SDValue N1 = N->getOperand(1);
24745 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24746 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24747 (Subtarget->hasSSE2() && VT == MVT::i64))) {
24748 SDValue N00 = N0.getOperand(0);
24749 SDValue N10 = N1.getOperand(0);
24750 EVT N00Type = N00.getValueType();
24751 EVT N10Type = N10.getValueType();
24752 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24753 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24754 return DAG.getBitcast(VT, FPLogic);
24760 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24761 TargetLowering::DAGCombinerInfo &DCI,
24762 const X86Subtarget *Subtarget) {
24763 if (DCI.isBeforeLegalizeOps())
24766 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24769 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24772 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24775 EVT VT = N->getValueType(0);
24776 SDValue N0 = N->getOperand(0);
24777 SDValue N1 = N->getOperand(1);
24780 // Create BEXTR instructions
24781 // BEXTR is ((X >> imm) & (2**size-1))
24782 if (VT == MVT::i32 || VT == MVT::i64) {
24783 // Check for BEXTR.
24784 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24785 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24786 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24787 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24788 if (MaskNode && ShiftNode) {
24789 uint64_t Mask = MaskNode->getZExtValue();
24790 uint64_t Shift = ShiftNode->getZExtValue();
24791 if (isMask_64(Mask)) {
24792 uint64_t MaskSize = countPopulation(Mask);
24793 if (Shift + MaskSize <= VT.getSizeInBits())
24794 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24795 DAG.getConstant(Shift | (MaskSize << 8), DL,
24804 // Want to form ANDNP nodes:
24805 // 1) In the hopes of then easily combining them with OR and AND nodes
24806 // to form PBLEND/PSIGN.
24807 // 2) To match ANDN packed intrinsics
24808 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24811 // Check LHS for vnot
24812 if (N0.getOpcode() == ISD::XOR &&
24813 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24814 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24815 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24817 // Check RHS for vnot
24818 if (N1.getOpcode() == ISD::XOR &&
24819 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24820 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24821 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24826 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24827 TargetLowering::DAGCombinerInfo &DCI,
24828 const X86Subtarget *Subtarget) {
24829 if (DCI.isBeforeLegalizeOps())
24832 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24835 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24838 SDValue N0 = N->getOperand(0);
24839 SDValue N1 = N->getOperand(1);
24840 EVT VT = N->getValueType(0);
24842 // look for psign/blend
24843 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24844 if (!Subtarget->hasSSSE3() ||
24845 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24848 // Canonicalize pandn to RHS
24849 if (N0.getOpcode() == X86ISD::ANDNP)
24851 // or (and (m, y), (pandn m, x))
24852 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24853 SDValue Mask = N1.getOperand(0);
24854 SDValue X = N1.getOperand(1);
24856 if (N0.getOperand(0) == Mask)
24857 Y = N0.getOperand(1);
24858 if (N0.getOperand(1) == Mask)
24859 Y = N0.getOperand(0);
24861 // Check to see if the mask appeared in both the AND and ANDNP and
24865 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24866 // Look through mask bitcast.
24867 if (Mask.getOpcode() == ISD::BITCAST)
24868 Mask = Mask.getOperand(0);
24869 if (X.getOpcode() == ISD::BITCAST)
24870 X = X.getOperand(0);
24871 if (Y.getOpcode() == ISD::BITCAST)
24872 Y = Y.getOperand(0);
24874 EVT MaskVT = Mask.getValueType();
24876 // Validate that the Mask operand is a vector sra node.
24877 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24878 // there is no psrai.b
24879 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24880 unsigned SraAmt = ~0;
24881 if (Mask.getOpcode() == ISD::SRA) {
24882 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24883 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24884 SraAmt = AmtConst->getZExtValue();
24885 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24886 SDValue SraC = Mask.getOperand(1);
24887 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24889 if ((SraAmt + 1) != EltBits)
24894 // Now we know we at least have a plendvb with the mask val. See if
24895 // we can form a psignb/w/d.
24896 // psign = x.type == y.type == mask.type && y = sub(0, x);
24897 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24898 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24899 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24900 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24901 "Unsupported VT for PSIGN");
24902 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24903 return DAG.getBitcast(VT, Mask);
24905 // PBLENDVB only available on SSE 4.1
24906 if (!Subtarget->hasSSE41())
24909 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24911 X = DAG.getBitcast(BlendVT, X);
24912 Y = DAG.getBitcast(BlendVT, Y);
24913 Mask = DAG.getBitcast(BlendVT, Mask);
24914 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24915 return DAG.getBitcast(VT, Mask);
24919 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24922 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24923 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24925 // SHLD/SHRD instructions have lower register pressure, but on some
24926 // platforms they have higher latency than the equivalent
24927 // series of shifts/or that would otherwise be generated.
24928 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24929 // have higher latencies and we are not optimizing for size.
24930 if (!OptForSize && Subtarget->isSHLDSlow())
24933 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24935 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24937 if (!N0.hasOneUse() || !N1.hasOneUse())
24940 SDValue ShAmt0 = N0.getOperand(1);
24941 if (ShAmt0.getValueType() != MVT::i8)
24943 SDValue ShAmt1 = N1.getOperand(1);
24944 if (ShAmt1.getValueType() != MVT::i8)
24946 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24947 ShAmt0 = ShAmt0.getOperand(0);
24948 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24949 ShAmt1 = ShAmt1.getOperand(0);
24952 unsigned Opc = X86ISD::SHLD;
24953 SDValue Op0 = N0.getOperand(0);
24954 SDValue Op1 = N1.getOperand(0);
24955 if (ShAmt0.getOpcode() == ISD::SUB) {
24956 Opc = X86ISD::SHRD;
24957 std::swap(Op0, Op1);
24958 std::swap(ShAmt0, ShAmt1);
24961 unsigned Bits = VT.getSizeInBits();
24962 if (ShAmt1.getOpcode() == ISD::SUB) {
24963 SDValue Sum = ShAmt1.getOperand(0);
24964 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24965 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24966 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24967 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24968 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24969 return DAG.getNode(Opc, DL, VT,
24971 DAG.getNode(ISD::TRUNCATE, DL,
24974 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24975 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24977 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24978 return DAG.getNode(Opc, DL, VT,
24979 N0.getOperand(0), N1.getOperand(0),
24980 DAG.getNode(ISD::TRUNCATE, DL,
24987 // Generate NEG and CMOV for integer abs.
24988 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24989 EVT VT = N->getValueType(0);
24991 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24992 // 8-bit integer abs to NEG and CMOV.
24993 if (VT.isInteger() && VT.getSizeInBits() == 8)
24996 SDValue N0 = N->getOperand(0);
24997 SDValue N1 = N->getOperand(1);
25000 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25001 // and change it to SUB and CMOV.
25002 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25003 N0.getOpcode() == ISD::ADD &&
25004 N0.getOperand(1) == N1 &&
25005 N1.getOpcode() == ISD::SRA &&
25006 N1.getOperand(0) == N0.getOperand(0))
25007 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25008 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25009 // Generate SUB & CMOV.
25010 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25011 DAG.getConstant(0, DL, VT), N0.getOperand(0));
25013 SDValue Ops[] = { N0.getOperand(0), Neg,
25014 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25015 SDValue(Neg.getNode(), 1) };
25016 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25021 // Try to turn tests against the signbit in the form of:
25022 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25025 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25026 // This is only worth doing if the output type is i8.
25027 if (N->getValueType(0) != MVT::i8)
25030 SDValue N0 = N->getOperand(0);
25031 SDValue N1 = N->getOperand(1);
25033 // We should be performing an xor against a truncated shift.
25034 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25037 // Make sure we are performing an xor against one.
25038 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25041 // SetCC on x86 zero extends so only act on this if it's a logical shift.
25042 SDValue Shift = N0.getOperand(0);
25043 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25046 // Make sure we are truncating from one of i16, i32 or i64.
25047 EVT ShiftTy = Shift.getValueType();
25048 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25051 // Make sure the shift amount extracts the sign bit.
25052 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25053 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25056 // Create a greater-than comparison against -1.
25057 // N.B. Using SETGE against 0 works but we want a canonical looking
25058 // comparison, using SETGT matches up with what TranslateX86CC.
25060 SDValue ShiftOp = Shift.getOperand(0);
25061 EVT ShiftOpTy = ShiftOp.getValueType();
25062 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25063 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25067 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25068 TargetLowering::DAGCombinerInfo &DCI,
25069 const X86Subtarget *Subtarget) {
25070 if (DCI.isBeforeLegalizeOps())
25073 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25076 if (Subtarget->hasCMov())
25077 if (SDValue RV = performIntegerAbsCombine(N, DAG))
25080 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25086 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25087 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25088 TargetLowering::DAGCombinerInfo &DCI,
25089 const X86Subtarget *Subtarget) {
25090 LoadSDNode *Ld = cast<LoadSDNode>(N);
25091 EVT RegVT = Ld->getValueType(0);
25092 EVT MemVT = Ld->getMemoryVT();
25094 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25096 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25097 // into two 16-byte operations.
25098 ISD::LoadExtType Ext = Ld->getExtensionType();
25100 unsigned AddressSpace = Ld->getAddressSpace();
25101 unsigned Alignment = Ld->getAlignment();
25102 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25103 Ext == ISD::NON_EXTLOAD &&
25104 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25105 AddressSpace, Alignment, &Fast) && !Fast) {
25106 unsigned NumElems = RegVT.getVectorNumElements();
25110 SDValue Ptr = Ld->getBasePtr();
25111 SDValue Increment =
25112 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25114 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25116 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25117 Ld->getPointerInfo(), Ld->isVolatile(),
25118 Ld->isNonTemporal(), Ld->isInvariant(),
25120 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25121 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25122 Ld->getPointerInfo(), Ld->isVolatile(),
25123 Ld->isNonTemporal(), Ld->isInvariant(),
25124 std::min(16U, Alignment));
25125 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25127 Load2.getValue(1));
25129 SDValue NewVec = DAG.getUNDEF(RegVT);
25130 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25131 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25132 return DCI.CombineTo(N, NewVec, TF, true);
25138 /// PerformMLOADCombine - Resolve extending loads
25139 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25140 TargetLowering::DAGCombinerInfo &DCI,
25141 const X86Subtarget *Subtarget) {
25142 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25143 if (Mld->getExtensionType() != ISD::SEXTLOAD)
25146 EVT VT = Mld->getValueType(0);
25147 unsigned NumElems = VT.getVectorNumElements();
25148 EVT LdVT = Mld->getMemoryVT();
25151 assert(LdVT != VT && "Cannot extend to the same type");
25152 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25153 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25154 // From, To sizes and ElemCount must be pow of two
25155 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25156 "Unexpected size for extending masked load");
25158 unsigned SizeRatio = ToSz / FromSz;
25159 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25161 // Create a type on which we perform the shuffle
25162 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25163 LdVT.getScalarType(), NumElems*SizeRatio);
25164 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25166 // Convert Src0 value
25167 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25168 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25169 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25170 for (unsigned i = 0; i != NumElems; ++i)
25171 ShuffleVec[i] = i * SizeRatio;
25173 // Can't shuffle using an illegal type.
25174 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25175 "WideVecVT should be legal");
25176 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25177 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25179 // Prepare the new mask
25181 SDValue Mask = Mld->getMask();
25182 if (Mask.getValueType() == VT) {
25183 // Mask and original value have the same type
25184 NewMask = DAG.getBitcast(WideVecVT, Mask);
25185 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25186 for (unsigned i = 0; i != NumElems; ++i)
25187 ShuffleVec[i] = i * SizeRatio;
25188 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25189 ShuffleVec[i] = NumElems*SizeRatio;
25190 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25191 DAG.getConstant(0, dl, WideVecVT),
25195 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25196 unsigned WidenNumElts = NumElems*SizeRatio;
25197 unsigned MaskNumElts = VT.getVectorNumElements();
25198 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25201 unsigned NumConcat = WidenNumElts / MaskNumElts;
25202 SmallVector<SDValue, 16> Ops(NumConcat);
25203 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25205 for (unsigned i = 1; i != NumConcat; ++i)
25208 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25211 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25212 Mld->getBasePtr(), NewMask, WideSrc0,
25213 Mld->getMemoryVT(), Mld->getMemOperand(),
25215 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25216 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25218 /// PerformMSTORECombine - Resolve truncating stores
25219 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25220 const X86Subtarget *Subtarget) {
25221 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25222 if (!Mst->isTruncatingStore())
25225 EVT VT = Mst->getValue().getValueType();
25226 unsigned NumElems = VT.getVectorNumElements();
25227 EVT StVT = Mst->getMemoryVT();
25230 assert(StVT != VT && "Cannot truncate to the same type");
25231 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25232 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25236 // The truncating store is legal in some cases. For example
25237 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25238 // are designated for truncate store.
25239 // In this case we don't need any further transformations.
25240 if (TLI.isTruncStoreLegal(VT, StVT))
25243 // From, To sizes and ElemCount must be pow of two
25244 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25245 "Unexpected size for truncating masked store");
25246 // We are going to use the original vector elt for storing.
25247 // Accumulated smaller vector elements must be a multiple of the store size.
25248 assert (((NumElems * FromSz) % ToSz) == 0 &&
25249 "Unexpected ratio for truncating masked store");
25251 unsigned SizeRatio = FromSz / ToSz;
25252 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25254 // Create a type on which we perform the shuffle
25255 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25256 StVT.getScalarType(), NumElems*SizeRatio);
25258 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25260 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25261 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25262 for (unsigned i = 0; i != NumElems; ++i)
25263 ShuffleVec[i] = i * SizeRatio;
25265 // Can't shuffle using an illegal type.
25266 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25267 "WideVecVT should be legal");
25269 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25270 DAG.getUNDEF(WideVecVT),
25274 SDValue Mask = Mst->getMask();
25275 if (Mask.getValueType() == VT) {
25276 // Mask and original value have the same type
25277 NewMask = DAG.getBitcast(WideVecVT, Mask);
25278 for (unsigned i = 0; i != NumElems; ++i)
25279 ShuffleVec[i] = i * SizeRatio;
25280 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25281 ShuffleVec[i] = NumElems*SizeRatio;
25282 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25283 DAG.getConstant(0, dl, WideVecVT),
25287 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25288 unsigned WidenNumElts = NumElems*SizeRatio;
25289 unsigned MaskNumElts = VT.getVectorNumElements();
25290 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25293 unsigned NumConcat = WidenNumElts / MaskNumElts;
25294 SmallVector<SDValue, 16> Ops(NumConcat);
25295 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25297 for (unsigned i = 1; i != NumConcat; ++i)
25300 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25303 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25304 NewMask, StVT, Mst->getMemOperand(), false);
25306 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25307 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25308 const X86Subtarget *Subtarget) {
25309 StoreSDNode *St = cast<StoreSDNode>(N);
25310 EVT VT = St->getValue().getValueType();
25311 EVT StVT = St->getMemoryVT();
25313 SDValue StoredVal = St->getOperand(1);
25314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25316 // If we are saving a concatenation of two XMM registers and 32-byte stores
25317 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25319 unsigned AddressSpace = St->getAddressSpace();
25320 unsigned Alignment = St->getAlignment();
25321 if (VT.is256BitVector() && StVT == VT &&
25322 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25323 AddressSpace, Alignment, &Fast) && !Fast) {
25324 unsigned NumElems = VT.getVectorNumElements();
25328 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25329 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25332 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25333 SDValue Ptr0 = St->getBasePtr();
25334 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25336 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25337 St->getPointerInfo(), St->isVolatile(),
25338 St->isNonTemporal(), Alignment);
25339 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25340 St->getPointerInfo(), St->isVolatile(),
25341 St->isNonTemporal(),
25342 std::min(16U, Alignment));
25343 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25346 // Optimize trunc store (of multiple scalars) to shuffle and store.
25347 // First, pack all of the elements in one place. Next, store to memory
25348 // in fewer chunks.
25349 if (St->isTruncatingStore() && VT.isVector()) {
25350 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25351 unsigned NumElems = VT.getVectorNumElements();
25352 assert(StVT != VT && "Cannot truncate to the same type");
25353 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25354 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25356 // The truncating store is legal in some cases. For example
25357 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25358 // are designated for truncate store.
25359 // In this case we don't need any further transformations.
25360 if (TLI.isTruncStoreLegal(VT, StVT))
25363 // From, To sizes and ElemCount must be pow of two
25364 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25365 // We are going to use the original vector elt for storing.
25366 // Accumulated smaller vector elements must be a multiple of the store size.
25367 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25369 unsigned SizeRatio = FromSz / ToSz;
25371 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25373 // Create a type on which we perform the shuffle
25374 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25375 StVT.getScalarType(), NumElems*SizeRatio);
25377 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25379 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25380 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25381 for (unsigned i = 0; i != NumElems; ++i)
25382 ShuffleVec[i] = i * SizeRatio;
25384 // Can't shuffle using an illegal type.
25385 if (!TLI.isTypeLegal(WideVecVT))
25388 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25389 DAG.getUNDEF(WideVecVT),
25391 // At this point all of the data is stored at the bottom of the
25392 // register. We now need to save it to mem.
25394 // Find the largest store unit
25395 MVT StoreType = MVT::i8;
25396 for (MVT Tp : MVT::integer_valuetypes()) {
25397 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25401 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25402 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25403 (64 <= NumElems * ToSz))
25404 StoreType = MVT::f64;
25406 // Bitcast the original vector into a vector of store-size units
25407 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25408 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25409 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25410 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25411 SmallVector<SDValue, 8> Chains;
25412 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25413 TLI.getPointerTy(DAG.getDataLayout()));
25414 SDValue Ptr = St->getBasePtr();
25416 // Perform one or more big stores into memory.
25417 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25418 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25419 StoreType, ShuffWide,
25420 DAG.getIntPtrConstant(i, dl));
25421 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25422 St->getPointerInfo(), St->isVolatile(),
25423 St->isNonTemporal(), St->getAlignment());
25424 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25425 Chains.push_back(Ch);
25428 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25431 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
25432 // the FP state in cases where an emms may be missing.
25433 // A preferable solution to the general problem is to figure out the right
25434 // places to insert EMMS. This qualifies as a quick hack.
25436 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25437 if (VT.getSizeInBits() != 64)
25440 const Function *F = DAG.getMachineFunction().getFunction();
25441 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25443 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25444 if ((VT.isVector() ||
25445 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25446 isa<LoadSDNode>(St->getValue()) &&
25447 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25448 St->getChain().hasOneUse() && !St->isVolatile()) {
25449 SDNode* LdVal = St->getValue().getNode();
25450 LoadSDNode *Ld = nullptr;
25451 int TokenFactorIndex = -1;
25452 SmallVector<SDValue, 8> Ops;
25453 SDNode* ChainVal = St->getChain().getNode();
25454 // Must be a store of a load. We currently handle two cases: the load
25455 // is a direct child, and it's under an intervening TokenFactor. It is
25456 // possible to dig deeper under nested TokenFactors.
25457 if (ChainVal == LdVal)
25458 Ld = cast<LoadSDNode>(St->getChain());
25459 else if (St->getValue().hasOneUse() &&
25460 ChainVal->getOpcode() == ISD::TokenFactor) {
25461 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25462 if (ChainVal->getOperand(i).getNode() == LdVal) {
25463 TokenFactorIndex = i;
25464 Ld = cast<LoadSDNode>(St->getValue());
25466 Ops.push_back(ChainVal->getOperand(i));
25470 if (!Ld || !ISD::isNormalLoad(Ld))
25473 // If this is not the MMX case, i.e. we are just turning i64 load/store
25474 // into f64 load/store, avoid the transformation if there are multiple
25475 // uses of the loaded value.
25476 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25481 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25482 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25484 if (Subtarget->is64Bit() || F64IsLegal) {
25485 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25486 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25487 Ld->getPointerInfo(), Ld->isVolatile(),
25488 Ld->isNonTemporal(), Ld->isInvariant(),
25489 Ld->getAlignment());
25490 SDValue NewChain = NewLd.getValue(1);
25491 if (TokenFactorIndex != -1) {
25492 Ops.push_back(NewChain);
25493 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25495 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25496 St->getPointerInfo(),
25497 St->isVolatile(), St->isNonTemporal(),
25498 St->getAlignment());
25501 // Otherwise, lower to two pairs of 32-bit loads / stores.
25502 SDValue LoAddr = Ld->getBasePtr();
25503 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25504 DAG.getConstant(4, LdDL, MVT::i32));
25506 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25507 Ld->getPointerInfo(),
25508 Ld->isVolatile(), Ld->isNonTemporal(),
25509 Ld->isInvariant(), Ld->getAlignment());
25510 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25511 Ld->getPointerInfo().getWithOffset(4),
25512 Ld->isVolatile(), Ld->isNonTemporal(),
25514 MinAlign(Ld->getAlignment(), 4));
25516 SDValue NewChain = LoLd.getValue(1);
25517 if (TokenFactorIndex != -1) {
25518 Ops.push_back(LoLd);
25519 Ops.push_back(HiLd);
25520 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25523 LoAddr = St->getBasePtr();
25524 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25525 DAG.getConstant(4, StDL, MVT::i32));
25527 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25528 St->getPointerInfo(),
25529 St->isVolatile(), St->isNonTemporal(),
25530 St->getAlignment());
25531 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25532 St->getPointerInfo().getWithOffset(4),
25534 St->isNonTemporal(),
25535 MinAlign(St->getAlignment(), 4));
25536 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25539 // This is similar to the above case, but here we handle a scalar 64-bit
25540 // integer store that is extracted from a vector on a 32-bit target.
25541 // If we have SSE2, then we can treat it like a floating-point double
25542 // to get past legalization. The execution dependencies fixup pass will
25543 // choose the optimal machine instruction for the store if this really is
25544 // an integer or v2f32 rather than an f64.
25545 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25546 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25547 SDValue OldExtract = St->getOperand(1);
25548 SDValue ExtOp0 = OldExtract.getOperand(0);
25549 unsigned VecSize = ExtOp0.getValueSizeInBits();
25550 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25551 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25552 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25553 BitCast, OldExtract.getOperand(1));
25554 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25555 St->getPointerInfo(), St->isVolatile(),
25556 St->isNonTemporal(), St->getAlignment());
25562 /// Return 'true' if this vector operation is "horizontal"
25563 /// and return the operands for the horizontal operation in LHS and RHS. A
25564 /// horizontal operation performs the binary operation on successive elements
25565 /// of its first operand, then on successive elements of its second operand,
25566 /// returning the resulting values in a vector. For example, if
25567 /// A = < float a0, float a1, float a2, float a3 >
25569 /// B = < float b0, float b1, float b2, float b3 >
25570 /// then the result of doing a horizontal operation on A and B is
25571 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25572 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25573 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25574 /// set to A, RHS to B, and the routine returns 'true'.
25575 /// Note that the binary operation should have the property that if one of the
25576 /// operands is UNDEF then the result is UNDEF.
25577 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25578 // Look for the following pattern: if
25579 // A = < float a0, float a1, float a2, float a3 >
25580 // B = < float b0, float b1, float b2, float b3 >
25582 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25583 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25584 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25585 // which is A horizontal-op B.
25587 // At least one of the operands should be a vector shuffle.
25588 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25589 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25592 MVT VT = LHS.getSimpleValueType();
25594 assert((VT.is128BitVector() || VT.is256BitVector()) &&
25595 "Unsupported vector type for horizontal add/sub");
25597 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25598 // operate independently on 128-bit lanes.
25599 unsigned NumElts = VT.getVectorNumElements();
25600 unsigned NumLanes = VT.getSizeInBits()/128;
25601 unsigned NumLaneElts = NumElts / NumLanes;
25602 assert((NumLaneElts % 2 == 0) &&
25603 "Vector type should have an even number of elements in each lane");
25604 unsigned HalfLaneElts = NumLaneElts/2;
25606 // View LHS in the form
25607 // LHS = VECTOR_SHUFFLE A, B, LMask
25608 // If LHS is not a shuffle then pretend it is the shuffle
25609 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25610 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25613 SmallVector<int, 16> LMask(NumElts);
25614 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25615 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25616 A = LHS.getOperand(0);
25617 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25618 B = LHS.getOperand(1);
25619 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25620 std::copy(Mask.begin(), Mask.end(), LMask.begin());
25622 if (LHS.getOpcode() != ISD::UNDEF)
25624 for (unsigned i = 0; i != NumElts; ++i)
25628 // Likewise, view RHS in the form
25629 // RHS = VECTOR_SHUFFLE C, D, RMask
25631 SmallVector<int, 16> RMask(NumElts);
25632 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25633 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25634 C = RHS.getOperand(0);
25635 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25636 D = RHS.getOperand(1);
25637 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25638 std::copy(Mask.begin(), Mask.end(), RMask.begin());
25640 if (RHS.getOpcode() != ISD::UNDEF)
25642 for (unsigned i = 0; i != NumElts; ++i)
25646 // Check that the shuffles are both shuffling the same vectors.
25647 if (!(A == C && B == D) && !(A == D && B == C))
25650 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25651 if (!A.getNode() && !B.getNode())
25654 // If A and B occur in reverse order in RHS, then "swap" them (which means
25655 // rewriting the mask).
25657 ShuffleVectorSDNode::commuteMask(RMask);
25659 // At this point LHS and RHS are equivalent to
25660 // LHS = VECTOR_SHUFFLE A, B, LMask
25661 // RHS = VECTOR_SHUFFLE A, B, RMask
25662 // Check that the masks correspond to performing a horizontal operation.
25663 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25664 for (unsigned i = 0; i != NumLaneElts; ++i) {
25665 int LIdx = LMask[i+l], RIdx = RMask[i+l];
25667 // Ignore any UNDEF components.
25668 if (LIdx < 0 || RIdx < 0 ||
25669 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25670 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25673 // Check that successive elements are being operated on. If not, this is
25674 // not a horizontal operation.
25675 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25676 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25677 if (!(LIdx == Index && RIdx == Index + 1) &&
25678 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25683 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25684 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25688 /// Do target-specific dag combines on floating point adds.
25689 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25690 const X86Subtarget *Subtarget) {
25691 EVT VT = N->getValueType(0);
25692 SDValue LHS = N->getOperand(0);
25693 SDValue RHS = N->getOperand(1);
25695 // Try to synthesize horizontal adds from adds of shuffles.
25696 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25697 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25698 isHorizontalBinOp(LHS, RHS, true))
25699 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25703 /// Do target-specific dag combines on floating point subs.
25704 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25705 const X86Subtarget *Subtarget) {
25706 EVT VT = N->getValueType(0);
25707 SDValue LHS = N->getOperand(0);
25708 SDValue RHS = N->getOperand(1);
25710 // Try to synthesize horizontal subs from subs of shuffles.
25711 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25712 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25713 isHorizontalBinOp(LHS, RHS, false))
25714 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25718 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25719 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25720 const X86Subtarget *Subtarget) {
25721 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25723 // F[X]OR(0.0, x) -> x
25724 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25725 if (C->getValueAPF().isPosZero())
25726 return N->getOperand(1);
25728 // F[X]OR(x, 0.0) -> x
25729 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25730 if (C->getValueAPF().isPosZero())
25731 return N->getOperand(0);
25733 EVT VT = N->getValueType(0);
25734 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25736 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25737 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25739 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25740 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25741 unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25742 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25743 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25748 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25749 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25750 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25752 // Only perform optimizations if UnsafeMath is used.
25753 if (!DAG.getTarget().Options.UnsafeFPMath)
25756 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25757 // into FMINC and FMAXC, which are Commutative operations.
25758 unsigned NewOp = 0;
25759 switch (N->getOpcode()) {
25760 default: llvm_unreachable("unknown opcode");
25761 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25762 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25765 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25766 N->getOperand(0), N->getOperand(1));
25769 /// Do target-specific dag combines on X86ISD::FAND nodes.
25770 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25771 // FAND(0.0, x) -> 0.0
25772 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25773 if (C->getValueAPF().isPosZero())
25774 return N->getOperand(0);
25776 // FAND(x, 0.0) -> 0.0
25777 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25778 if (C->getValueAPF().isPosZero())
25779 return N->getOperand(1);
25784 /// Do target-specific dag combines on X86ISD::FANDN nodes
25785 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25786 // FANDN(0.0, x) -> x
25787 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25788 if (C->getValueAPF().isPosZero())
25789 return N->getOperand(1);
25791 // FANDN(x, 0.0) -> 0.0
25792 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25793 if (C->getValueAPF().isPosZero())
25794 return N->getOperand(1);
25799 static SDValue PerformBTCombine(SDNode *N,
25801 TargetLowering::DAGCombinerInfo &DCI) {
25802 // BT ignores high bits in the bit index operand.
25803 SDValue Op1 = N->getOperand(1);
25804 if (Op1.hasOneUse()) {
25805 unsigned BitWidth = Op1.getValueSizeInBits();
25806 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25807 APInt KnownZero, KnownOne;
25808 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25809 !DCI.isBeforeLegalizeOps());
25810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25811 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25812 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25813 DCI.CommitTargetLoweringOpt(TLO);
25818 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25819 SDValue Op = N->getOperand(0);
25820 if (Op.getOpcode() == ISD::BITCAST)
25821 Op = Op.getOperand(0);
25822 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25823 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25824 VT.getVectorElementType().getSizeInBits() ==
25825 OpVT.getVectorElementType().getSizeInBits()) {
25826 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25831 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25832 const X86Subtarget *Subtarget) {
25833 EVT VT = N->getValueType(0);
25834 if (!VT.isVector())
25837 SDValue N0 = N->getOperand(0);
25838 SDValue N1 = N->getOperand(1);
25839 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25842 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25843 // both SSE and AVX2 since there is no sign-extended shift right
25844 // operation on a vector with 64-bit elements.
25845 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25846 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25847 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25848 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25849 SDValue N00 = N0.getOperand(0);
25851 // EXTLOAD has a better solution on AVX2,
25852 // it may be replaced with X86ISD::VSEXT node.
25853 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25854 if (!ISD::isNormalLoad(N00.getNode()))
25857 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25858 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25860 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25866 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
25867 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
25868 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
25869 /// eliminate extend, add, and shift instructions.
25870 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
25871 const X86Subtarget *Subtarget) {
25872 // TODO: This should be valid for other integer types.
25873 EVT VT = Sext->getValueType(0);
25874 if (VT != MVT::i64)
25877 // We need an 'add nsw' feeding into the 'sext'.
25878 SDValue Add = Sext->getOperand(0);
25879 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
25882 // Having a constant operand to the 'add' ensures that we are not increasing
25883 // the instruction count because the constant is extended for free below.
25884 // A constant operand can also become the displacement field of an LEA.
25885 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
25889 // Don't make the 'add' bigger if there's no hope of combining it with some
25890 // other 'add' or 'shl' instruction.
25891 // TODO: It may be profitable to generate simpler LEA instructions in place
25892 // of single 'add' instructions, but the cost model for selecting an LEA
25893 // currently has a high threshold.
25894 bool HasLEAPotential = false;
25895 for (auto *User : Sext->uses()) {
25896 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
25897 HasLEAPotential = true;
25901 if (!HasLEAPotential)
25904 // Everything looks good, so pull the 'sext' ahead of the 'add'.
25905 int64_t AddConstant = AddOp1->getSExtValue();
25906 SDValue AddOp0 = Add.getOperand(0);
25907 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
25908 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
25910 // The wider add is guaranteed to not wrap because both operands are
25913 Flags.setNoSignedWrap(true);
25914 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
25917 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25918 TargetLowering::DAGCombinerInfo &DCI,
25919 const X86Subtarget *Subtarget) {
25920 SDValue N0 = N->getOperand(0);
25921 EVT VT = N->getValueType(0);
25922 EVT SVT = VT.getScalarType();
25923 EVT InVT = N0.getValueType();
25924 EVT InSVT = InVT.getScalarType();
25927 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25928 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25929 // This exposes the sext to the sdivrem lowering, so that it directly extends
25930 // from AH (which we otherwise need to do contortions to access).
25931 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25932 InVT == MVT::i8 && VT == MVT::i32) {
25933 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25934 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25935 N0.getOperand(0), N0.getOperand(1));
25936 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25937 return R.getValue(1);
25940 if (!DCI.isBeforeLegalizeOps()) {
25941 if (InVT == MVT::i1) {
25942 SDValue Zero = DAG.getConstant(0, DL, VT);
25944 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25945 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25950 if (VT.isVector() && Subtarget->hasSSE2()) {
25951 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25952 EVT InVT = N.getValueType();
25953 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25954 Size / InVT.getScalarSizeInBits());
25955 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25956 DAG.getUNDEF(InVT));
25958 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25961 // If target-size is less than 128-bits, extend to a type that would extend
25962 // to 128 bits, extend that and extract the original target vector.
25963 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25964 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25965 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25966 unsigned Scale = 128 / VT.getSizeInBits();
25968 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25969 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25970 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25971 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25972 DAG.getIntPtrConstant(0, DL));
25975 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25976 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25977 if (VT.getSizeInBits() == 128 &&
25978 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25979 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25980 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25981 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25984 // On pre-AVX2 targets, split into 128-bit nodes of
25985 // ISD::SIGN_EXTEND_VECTOR_INREG.
25986 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25987 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25988 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25989 unsigned NumVecs = VT.getSizeInBits() / 128;
25990 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25991 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25992 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25994 SmallVector<SDValue, 8> Opnds;
25995 for (unsigned i = 0, Offset = 0; i != NumVecs;
25996 ++i, Offset += NumSubElts) {
25997 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25998 DAG.getIntPtrConstant(Offset, DL));
25999 SrcVec = ExtendVecSize(DL, SrcVec, 128);
26000 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26001 Opnds.push_back(SrcVec);
26003 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26007 if (Subtarget->hasAVX() && VT.isVector() && VT.getSizeInBits() == 256)
26008 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26011 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26017 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26018 const X86Subtarget* Subtarget) {
26020 EVT VT = N->getValueType(0);
26022 // Let legalize expand this if it isn't a legal type yet.
26023 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26026 EVT ScalarVT = VT.getScalarType();
26027 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26028 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26029 !Subtarget->hasAVX512()))
26032 SDValue A = N->getOperand(0);
26033 SDValue B = N->getOperand(1);
26034 SDValue C = N->getOperand(2);
26036 bool NegA = (A.getOpcode() == ISD::FNEG);
26037 bool NegB = (B.getOpcode() == ISD::FNEG);
26038 bool NegC = (C.getOpcode() == ISD::FNEG);
26040 // Negative multiplication when NegA xor NegB
26041 bool NegMul = (NegA != NegB);
26043 A = A.getOperand(0);
26045 B = B.getOperand(0);
26047 C = C.getOperand(0);
26051 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26053 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26055 return DAG.getNode(Opcode, dl, VT, A, B, C);
26058 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26059 TargetLowering::DAGCombinerInfo &DCI,
26060 const X86Subtarget *Subtarget) {
26061 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
26062 // (and (i32 x86isd::setcc_carry), 1)
26063 // This eliminates the zext. This transformation is necessary because
26064 // ISD::SETCC is always legalized to i8.
26066 SDValue N0 = N->getOperand(0);
26067 EVT VT = N->getValueType(0);
26069 if (N0.getOpcode() == ISD::AND &&
26071 N0.getOperand(0).hasOneUse()) {
26072 SDValue N00 = N0.getOperand(0);
26073 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26075 if (!C || C->getZExtValue() != 1)
26077 return DAG.getNode(ISD::AND, dl, VT,
26078 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26079 N00.getOperand(0), N00.getOperand(1)),
26080 DAG.getConstant(1, dl, VT));
26084 if (N0.getOpcode() == ISD::TRUNCATE &&
26086 N0.getOperand(0).hasOneUse()) {
26087 SDValue N00 = N0.getOperand(0);
26088 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26089 return DAG.getNode(ISD::AND, dl, VT,
26090 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26091 N00.getOperand(0), N00.getOperand(1)),
26092 DAG.getConstant(1, dl, VT));
26096 if (VT.is256BitVector())
26097 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26100 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26101 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26102 // This exposes the zext to the udivrem lowering, so that it directly extends
26103 // from AH (which we otherwise need to do contortions to access).
26104 if (N0.getOpcode() == ISD::UDIVREM &&
26105 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26106 (VT == MVT::i32 || VT == MVT::i64)) {
26107 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26108 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26109 N0.getOperand(0), N0.getOperand(1));
26110 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26111 return R.getValue(1);
26117 // Optimize x == -y --> x+y == 0
26118 // x != -y --> x+y != 0
26119 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26120 const X86Subtarget* Subtarget) {
26121 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26122 SDValue LHS = N->getOperand(0);
26123 SDValue RHS = N->getOperand(1);
26124 EVT VT = N->getValueType(0);
26127 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26129 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26130 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26131 LHS.getOperand(1));
26132 return DAG.getSetCC(DL, N->getValueType(0), addV,
26133 DAG.getConstant(0, DL, addV.getValueType()), CC);
26135 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26137 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26138 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26139 RHS.getOperand(1));
26140 return DAG.getSetCC(DL, N->getValueType(0), addV,
26141 DAG.getConstant(0, DL, addV.getValueType()), CC);
26144 if (VT.getScalarType() == MVT::i1 &&
26145 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26147 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26148 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26149 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26151 if (!IsSEXT0 || !IsVZero1) {
26152 // Swap the operands and update the condition code.
26153 std::swap(LHS, RHS);
26154 CC = ISD::getSetCCSwappedOperands(CC);
26156 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26157 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26158 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26161 if (IsSEXT0 && IsVZero1) {
26162 assert(VT == LHS.getOperand(0).getValueType() &&
26163 "Uexpected operand type");
26164 if (CC == ISD::SETGT)
26165 return DAG.getConstant(0, DL, VT);
26166 if (CC == ISD::SETLE)
26167 return DAG.getConstant(1, DL, VT);
26168 if (CC == ISD::SETEQ || CC == ISD::SETGE)
26169 return DAG.getNOT(DL, LHS.getOperand(0), VT);
26171 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26172 "Unexpected condition code!");
26173 return LHS.getOperand(0);
26180 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
26181 SelectionDAG &DAG) {
26183 MVT VT = Load->getSimpleValueType(0);
26184 MVT EVT = VT.getVectorElementType();
26185 SDValue Addr = Load->getOperand(1);
26186 SDValue NewAddr = DAG.getNode(
26187 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
26188 DAG.getConstant(Index * EVT.getStoreSize(), dl,
26189 Addr.getSimpleValueType()));
26192 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
26193 DAG.getMachineFunction().getMachineMemOperand(
26194 Load->getMemOperand(), 0, EVT.getStoreSize()));
26198 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
26199 const X86Subtarget *Subtarget) {
26201 MVT VT = N->getOperand(1)->getSimpleValueType(0);
26202 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
26203 "X86insertps is only defined for v4x32");
26205 SDValue Ld = N->getOperand(1);
26206 if (MayFoldLoad(Ld)) {
26207 // Extract the countS bits from the immediate so we can get the proper
26208 // address when narrowing the vector load to a specific element.
26209 // When the second source op is a memory address, insertps doesn't use
26210 // countS and just gets an f32 from that address.
26211 unsigned DestIndex =
26212 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
26214 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
26216 // Create this as a scalar to vector to match the instruction pattern.
26217 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
26218 // countS bits are ignored when loading from memory on insertps, which
26219 // means we don't need to explicitly set them to 0.
26220 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
26221 LoadScalarToVector, N->getOperand(2));
26226 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26227 SDValue V0 = N->getOperand(0);
26228 SDValue V1 = N->getOperand(1);
26230 EVT VT = N->getValueType(0);
26232 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26233 // operands and changing the mask to 1. This saves us a bunch of
26234 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26235 // x86InstrInfo knows how to commute this back after instruction selection
26236 // if it would help register allocation.
26238 // TODO: If optimizing for size or a processor that doesn't suffer from
26239 // partial register update stalls, this should be transformed into a MOVSD
26240 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26242 if (VT == MVT::v2f64)
26243 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26244 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26245 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26246 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26252 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26253 // as "sbb reg,reg", since it can be extended without zext and produces
26254 // an all-ones bit which is more useful than 0/1 in some cases.
26255 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26258 return DAG.getNode(ISD::AND, DL, VT,
26259 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26260 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26262 DAG.getConstant(1, DL, VT));
26263 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26264 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26265 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26266 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26270 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26271 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26272 TargetLowering::DAGCombinerInfo &DCI,
26273 const X86Subtarget *Subtarget) {
26275 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26276 SDValue EFLAGS = N->getOperand(1);
26278 if (CC == X86::COND_A) {
26279 // Try to convert COND_A into COND_B in an attempt to facilitate
26280 // materializing "setb reg".
26282 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26283 // cannot take an immediate as its first operand.
26285 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26286 EFLAGS.getValueType().isInteger() &&
26287 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26288 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26289 EFLAGS.getNode()->getVTList(),
26290 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26291 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26292 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26296 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26297 // a zext and produces an all-ones bit which is more useful than 0/1 in some
26299 if (CC == X86::COND_B)
26300 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26302 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26303 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26304 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26310 // Optimize branch condition evaluation.
26312 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26313 TargetLowering::DAGCombinerInfo &DCI,
26314 const X86Subtarget *Subtarget) {
26316 SDValue Chain = N->getOperand(0);
26317 SDValue Dest = N->getOperand(1);
26318 SDValue EFLAGS = N->getOperand(3);
26319 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26321 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26322 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26323 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26330 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26331 SelectionDAG &DAG) {
26332 // Take advantage of vector comparisons producing 0 or -1 in each lane to
26333 // optimize away operation when it's from a constant.
26335 // The general transformation is:
26336 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26337 // AND(VECTOR_CMP(x,y), constant2)
26338 // constant2 = UNARYOP(constant)
26340 // Early exit if this isn't a vector operation, the operand of the
26341 // unary operation isn't a bitwise AND, or if the sizes of the operations
26342 // aren't the same.
26343 EVT VT = N->getValueType(0);
26344 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26345 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26346 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26349 // Now check that the other operand of the AND is a constant. We could
26350 // make the transformation for non-constant splats as well, but it's unclear
26351 // that would be a benefit as it would not eliminate any operations, just
26352 // perform one more step in scalar code before moving to the vector unit.
26353 if (BuildVectorSDNode *BV =
26354 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26355 // Bail out if the vector isn't a constant.
26356 if (!BV->isConstant())
26359 // Everything checks out. Build up the new and improved node.
26361 EVT IntVT = BV->getValueType(0);
26362 // Create a new constant of the appropriate type for the transformed
26364 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26365 // The AND node needs bitcasts to/from an integer vector type around it.
26366 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26367 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26368 N->getOperand(0)->getOperand(0), MaskConst);
26369 SDValue Res = DAG.getBitcast(VT, NewAnd);
26376 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26377 const X86Subtarget *Subtarget) {
26378 SDValue Op0 = N->getOperand(0);
26379 EVT VT = N->getValueType(0);
26380 EVT InVT = Op0.getValueType();
26381 EVT InSVT = InVT.getScalarType();
26382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26384 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26385 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26386 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26388 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26389 InVT.getVectorNumElements());
26390 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26392 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26393 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26395 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26401 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26402 const X86Subtarget *Subtarget) {
26403 // First try to optimize away the conversion entirely when it's
26404 // conditionally from a constant. Vectors only.
26405 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26408 // Now move on to more general possibilities.
26409 SDValue Op0 = N->getOperand(0);
26410 EVT VT = N->getValueType(0);
26411 EVT InVT = Op0.getValueType();
26412 EVT InSVT = InVT.getScalarType();
26414 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26415 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26416 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26418 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26419 InVT.getVectorNumElements());
26420 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26421 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26424 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26425 // a 32-bit target where SSE doesn't support i64->FP operations.
26426 if (Op0.getOpcode() == ISD::LOAD) {
26427 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26428 EVT LdVT = Ld->getValueType(0);
26430 // This transformation is not supported if the result type is f16
26431 if (VT == MVT::f16)
26434 if (!Ld->isVolatile() && !VT.isVector() &&
26435 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26436 !Subtarget->is64Bit() && LdVT == MVT::i64) {
26437 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26438 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26439 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26446 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26447 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26448 X86TargetLowering::DAGCombinerInfo &DCI) {
26449 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26450 // the result is either zero or one (depending on the input carry bit).
26451 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26452 if (X86::isZeroNode(N->getOperand(0)) &&
26453 X86::isZeroNode(N->getOperand(1)) &&
26454 // We don't have a good way to replace an EFLAGS use, so only do this when
26456 SDValue(N, 1).use_empty()) {
26458 EVT VT = N->getValueType(0);
26459 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26460 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26461 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26462 DAG.getConstant(X86::COND_B, DL,
26465 DAG.getConstant(1, DL, VT));
26466 return DCI.CombineTo(N, Res1, CarryOut);
26472 // fold (add Y, (sete X, 0)) -> adc 0, Y
26473 // (add Y, (setne X, 0)) -> sbb -1, Y
26474 // (sub (sete X, 0), Y) -> sbb 0, Y
26475 // (sub (setne X, 0), Y) -> adc -1, Y
26476 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26479 // Look through ZExts.
26480 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26481 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26484 SDValue SetCC = Ext.getOperand(0);
26485 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26488 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26489 if (CC != X86::COND_E && CC != X86::COND_NE)
26492 SDValue Cmp = SetCC.getOperand(1);
26493 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26494 !X86::isZeroNode(Cmp.getOperand(1)) ||
26495 !Cmp.getOperand(0).getValueType().isInteger())
26498 SDValue CmpOp0 = Cmp.getOperand(0);
26499 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26500 DAG.getConstant(1, DL, CmpOp0.getValueType()));
26502 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26503 if (CC == X86::COND_NE)
26504 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26505 DL, OtherVal.getValueType(), OtherVal,
26506 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26508 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26509 DL, OtherVal.getValueType(), OtherVal,
26510 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26513 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26514 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26515 const X86Subtarget *Subtarget) {
26516 EVT VT = N->getValueType(0);
26517 SDValue Op0 = N->getOperand(0);
26518 SDValue Op1 = N->getOperand(1);
26520 // Try to synthesize horizontal adds from adds of shuffles.
26521 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26522 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26523 isHorizontalBinOp(Op0, Op1, true))
26524 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26526 return OptimizeConditionalInDecrement(N, DAG);
26529 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26530 const X86Subtarget *Subtarget) {
26531 SDValue Op0 = N->getOperand(0);
26532 SDValue Op1 = N->getOperand(1);
26534 // X86 can't encode an immediate LHS of a sub. See if we can push the
26535 // negation into a preceding instruction.
26536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26537 // If the RHS of the sub is a XOR with one use and a constant, invert the
26538 // immediate. Then add one to the LHS of the sub so we can turn
26539 // X-Y -> X+~Y+1, saving one register.
26540 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26541 isa<ConstantSDNode>(Op1.getOperand(1))) {
26542 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26543 EVT VT = Op0.getValueType();
26544 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26546 DAG.getConstant(~XorC, SDLoc(Op1), VT));
26547 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26548 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26552 // Try to synthesize horizontal adds from adds of shuffles.
26553 EVT VT = N->getValueType(0);
26554 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26555 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26556 isHorizontalBinOp(Op0, Op1, true))
26557 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26559 return OptimizeConditionalInDecrement(N, DAG);
26562 /// performVZEXTCombine - Performs build vector combines
26563 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26564 TargetLowering::DAGCombinerInfo &DCI,
26565 const X86Subtarget *Subtarget) {
26567 MVT VT = N->getSimpleValueType(0);
26568 SDValue Op = N->getOperand(0);
26569 MVT OpVT = Op.getSimpleValueType();
26570 MVT OpEltVT = OpVT.getVectorElementType();
26571 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26573 // (vzext (bitcast (vzext (x)) -> (vzext x)
26575 while (V.getOpcode() == ISD::BITCAST)
26576 V = V.getOperand(0);
26578 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26579 MVT InnerVT = V.getSimpleValueType();
26580 MVT InnerEltVT = InnerVT.getVectorElementType();
26582 // If the element sizes match exactly, we can just do one larger vzext. This
26583 // is always an exact type match as vzext operates on integer types.
26584 if (OpEltVT == InnerEltVT) {
26585 assert(OpVT == InnerVT && "Types must match for vzext!");
26586 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26589 // The only other way we can combine them is if only a single element of the
26590 // inner vzext is used in the input to the outer vzext.
26591 if (InnerEltVT.getSizeInBits() < InputBits)
26594 // In this case, the inner vzext is completely dead because we're going to
26595 // only look at bits inside of the low element. Just do the outer vzext on
26596 // a bitcast of the input to the inner.
26597 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26600 // Check if we can bypass extracting and re-inserting an element of an input
26601 // vector. Essentially:
26602 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26603 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26604 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26605 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26606 SDValue ExtractedV = V.getOperand(0);
26607 SDValue OrigV = ExtractedV.getOperand(0);
26608 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26609 if (ExtractIdx->getZExtValue() == 0) {
26610 MVT OrigVT = OrigV.getSimpleValueType();
26611 // Extract a subvector if necessary...
26612 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26613 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26614 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26615 OrigVT.getVectorNumElements() / Ratio);
26616 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26617 DAG.getIntPtrConstant(0, DL));
26619 Op = DAG.getBitcast(OpVT, OrigV);
26620 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26627 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26628 DAGCombinerInfo &DCI) const {
26629 SelectionDAG &DAG = DCI.DAG;
26630 switch (N->getOpcode()) {
26632 case ISD::EXTRACT_VECTOR_ELT:
26633 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26636 case X86ISD::SHRUNKBLEND:
26637 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26638 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
26639 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26640 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
26641 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
26642 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
26643 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
26646 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
26647 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
26648 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
26649 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
26650 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
26651 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26652 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
26653 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
26654 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26655 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26656 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
26657 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
26659 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
26661 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
26662 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
26663 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
26664 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
26665 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
26666 case ISD::ANY_EXTEND:
26667 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
26668 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
26669 case ISD::SIGN_EXTEND_INREG:
26670 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26671 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
26672 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26673 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26674 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
26675 case X86ISD::SHUFP: // Handle all target specific shuffles
26676 case X86ISD::PALIGNR:
26677 case X86ISD::UNPCKH:
26678 case X86ISD::UNPCKL:
26679 case X86ISD::MOVHLPS:
26680 case X86ISD::MOVLHPS:
26681 case X86ISD::PSHUFB:
26682 case X86ISD::PSHUFD:
26683 case X86ISD::PSHUFHW:
26684 case X86ISD::PSHUFLW:
26685 case X86ISD::MOVSS:
26686 case X86ISD::MOVSD:
26687 case X86ISD::VPERMILPI:
26688 case X86ISD::VPERM2X128:
26689 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26690 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
26691 case X86ISD::INSERTPS: {
26692 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26693 return PerformINSERTPSCombine(N, DAG, Subtarget);
26696 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
26702 /// isTypeDesirableForOp - Return true if the target has native support for
26703 /// the specified value type and it is 'desirable' to use the type for the
26704 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26705 /// instruction encodings are longer and some i16 instructions are slow.
26706 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26707 if (!isTypeLegal(VT))
26709 if (VT != MVT::i16)
26716 case ISD::SIGN_EXTEND:
26717 case ISD::ZERO_EXTEND:
26718 case ISD::ANY_EXTEND:
26731 /// IsDesirableToPromoteOp - This method query the target whether it is
26732 /// beneficial for dag combiner to promote the specified node. If true, it
26733 /// should return the desired promotion type by reference.
26734 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26735 EVT VT = Op.getValueType();
26736 if (VT != MVT::i16)
26739 bool Promote = false;
26740 bool Commute = false;
26741 switch (Op.getOpcode()) {
26744 LoadSDNode *LD = cast<LoadSDNode>(Op);
26745 // If the non-extending load has a single use and it's not live out, then it
26746 // might be folded.
26747 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26748 Op.hasOneUse()*/) {
26749 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26750 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26751 // The only case where we'd want to promote LOAD (rather then it being
26752 // promoted as an operand is when it's only use is liveout.
26753 if (UI->getOpcode() != ISD::CopyToReg)
26760 case ISD::SIGN_EXTEND:
26761 case ISD::ZERO_EXTEND:
26762 case ISD::ANY_EXTEND:
26767 SDValue N0 = Op.getOperand(0);
26768 // Look out for (store (shl (load), x)).
26769 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26782 SDValue N0 = Op.getOperand(0);
26783 SDValue N1 = Op.getOperand(1);
26784 if (!Commute && MayFoldLoad(N1))
26786 // Avoid disabling potential load folding opportunities.
26787 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26789 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26799 //===----------------------------------------------------------------------===//
26800 // X86 Inline Assembly Support
26801 //===----------------------------------------------------------------------===//
26803 // Helper to match a string separated by whitespace.
26804 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26805 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26807 for (StringRef Piece : Pieces) {
26808 if (!S.startswith(Piece)) // Check if the piece matches.
26811 S = S.substr(Piece.size());
26812 StringRef::size_type Pos = S.find_first_not_of(" \t");
26813 if (Pos == 0) // We matched a prefix.
26822 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26824 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26825 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26826 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26827 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26829 if (AsmPieces.size() == 3)
26831 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26838 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26839 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26841 std::string AsmStr = IA->getAsmString();
26843 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26844 if (!Ty || Ty->getBitWidth() % 16 != 0)
26847 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26848 SmallVector<StringRef, 4> AsmPieces;
26849 SplitString(AsmStr, AsmPieces, ";\n");
26851 switch (AsmPieces.size()) {
26852 default: return false;
26854 // FIXME: this should verify that we are targeting a 486 or better. If not,
26855 // we will turn this bswap into something that will be lowered to logical
26856 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26857 // lower so don't worry about this.
26859 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26860 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26861 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26862 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26863 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26864 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26865 // No need to check constraints, nothing other than the equivalent of
26866 // "=r,0" would be valid here.
26867 return IntrinsicLowering::LowerToByteSwap(CI);
26870 // rorw $$8, ${0:w} --> llvm.bswap.i16
26871 if (CI->getType()->isIntegerTy(16) &&
26872 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26873 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26874 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26876 StringRef ConstraintsStr = IA->getConstraintString();
26877 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26878 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26879 if (clobbersFlagRegisters(AsmPieces))
26880 return IntrinsicLowering::LowerToByteSwap(CI);
26884 if (CI->getType()->isIntegerTy(32) &&
26885 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26886 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26887 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26888 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26890 StringRef ConstraintsStr = IA->getConstraintString();
26891 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26892 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26893 if (clobbersFlagRegisters(AsmPieces))
26894 return IntrinsicLowering::LowerToByteSwap(CI);
26897 if (CI->getType()->isIntegerTy(64)) {
26898 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26899 if (Constraints.size() >= 2 &&
26900 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26901 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26902 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26903 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26904 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26905 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26906 return IntrinsicLowering::LowerToByteSwap(CI);
26914 /// getConstraintType - Given a constraint letter, return the type of
26915 /// constraint it is for this target.
26916 X86TargetLowering::ConstraintType
26917 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26918 if (Constraint.size() == 1) {
26919 switch (Constraint[0]) {
26930 return C_RegisterClass;
26954 return TargetLowering::getConstraintType(Constraint);
26957 /// Examine constraint type and operand type and determine a weight value.
26958 /// This object must already have been set up with the operand type
26959 /// and the current alternative constraint selected.
26960 TargetLowering::ConstraintWeight
26961 X86TargetLowering::getSingleConstraintMatchWeight(
26962 AsmOperandInfo &info, const char *constraint) const {
26963 ConstraintWeight weight = CW_Invalid;
26964 Value *CallOperandVal = info.CallOperandVal;
26965 // If we don't have a value, we can't do a match,
26966 // but allow it at the lowest weight.
26967 if (!CallOperandVal)
26969 Type *type = CallOperandVal->getType();
26970 // Look at the constraint type.
26971 switch (*constraint) {
26973 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26984 if (CallOperandVal->getType()->isIntegerTy())
26985 weight = CW_SpecificReg;
26990 if (type->isFloatingPointTy())
26991 weight = CW_SpecificReg;
26994 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26995 weight = CW_SpecificReg;
26999 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27000 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27001 weight = CW_Register;
27004 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27005 if (C->getZExtValue() <= 31)
27006 weight = CW_Constant;
27010 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27011 if (C->getZExtValue() <= 63)
27012 weight = CW_Constant;
27016 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27017 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27018 weight = CW_Constant;
27022 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27023 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27024 weight = CW_Constant;
27028 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27029 if (C->getZExtValue() <= 3)
27030 weight = CW_Constant;
27034 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27035 if (C->getZExtValue() <= 0xff)
27036 weight = CW_Constant;
27041 if (isa<ConstantFP>(CallOperandVal)) {
27042 weight = CW_Constant;
27046 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27047 if ((C->getSExtValue() >= -0x80000000LL) &&
27048 (C->getSExtValue() <= 0x7fffffffLL))
27049 weight = CW_Constant;
27053 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27054 if (C->getZExtValue() <= 0xffffffff)
27055 weight = CW_Constant;
27062 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27063 /// with another that has more specific requirements based on the type of the
27064 /// corresponding operand.
27065 const char *X86TargetLowering::
27066 LowerXConstraint(EVT ConstraintVT) const {
27067 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27068 // 'f' like normal targets.
27069 if (ConstraintVT.isFloatingPoint()) {
27070 if (Subtarget->hasSSE2())
27072 if (Subtarget->hasSSE1())
27076 return TargetLowering::LowerXConstraint(ConstraintVT);
27079 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27080 /// vector. If it is invalid, don't add anything to Ops.
27081 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27082 std::string &Constraint,
27083 std::vector<SDValue>&Ops,
27084 SelectionDAG &DAG) const {
27087 // Only support length 1 constraints for now.
27088 if (Constraint.length() > 1) return;
27090 char ConstraintLetter = Constraint[0];
27091 switch (ConstraintLetter) {
27094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27095 if (C->getZExtValue() <= 31) {
27096 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27097 Op.getValueType());
27103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27104 if (C->getZExtValue() <= 63) {
27105 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27106 Op.getValueType());
27112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27113 if (isInt<8>(C->getSExtValue())) {
27114 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27115 Op.getValueType());
27121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27122 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27123 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27124 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27125 Op.getValueType());
27131 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27132 if (C->getZExtValue() <= 3) {
27133 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27134 Op.getValueType());
27140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27141 if (C->getZExtValue() <= 255) {
27142 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27143 Op.getValueType());
27149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27150 if (C->getZExtValue() <= 127) {
27151 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27152 Op.getValueType());
27158 // 32-bit signed value
27159 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27160 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27161 C->getSExtValue())) {
27162 // Widen to 64 bits here to get it sign extended.
27163 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27166 // FIXME gcc accepts some relocatable values here too, but only in certain
27167 // memory models; it's complicated.
27172 // 32-bit unsigned value
27173 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27174 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27175 C->getZExtValue())) {
27176 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27177 Op.getValueType());
27181 // FIXME gcc accepts some relocatable values here too, but only in certain
27182 // memory models; it's complicated.
27186 // Literal immediates are always ok.
27187 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27188 // Widen to 64 bits here to get it sign extended.
27189 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27193 // In any sort of PIC mode addresses need to be computed at runtime by
27194 // adding in a register or some sort of table lookup. These can't
27195 // be used as immediates.
27196 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27199 // If we are in non-pic codegen mode, we allow the address of a global (with
27200 // an optional displacement) to be used with 'i'.
27201 GlobalAddressSDNode *GA = nullptr;
27202 int64_t Offset = 0;
27204 // Match either (GA), (GA+C), (GA+C1+C2), etc.
27206 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27207 Offset += GA->getOffset();
27209 } else if (Op.getOpcode() == ISD::ADD) {
27210 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27211 Offset += C->getZExtValue();
27212 Op = Op.getOperand(0);
27215 } else if (Op.getOpcode() == ISD::SUB) {
27216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27217 Offset += -C->getZExtValue();
27218 Op = Op.getOperand(0);
27223 // Otherwise, this isn't something we can handle, reject it.
27227 const GlobalValue *GV = GA->getGlobal();
27228 // If we require an extra load to get this address, as in PIC mode, we
27229 // can't accept it.
27230 if (isGlobalStubReference(
27231 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27234 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27235 GA->getValueType(0), Offset);
27240 if (Result.getNode()) {
27241 Ops.push_back(Result);
27244 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27247 std::pair<unsigned, const TargetRegisterClass *>
27248 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27249 StringRef Constraint,
27251 // First, see if this is a constraint that directly corresponds to an LLVM
27253 if (Constraint.size() == 1) {
27254 // GCC Constraint Letters
27255 switch (Constraint[0]) {
27257 // TODO: Slight differences here in allocation order and leaving
27258 // RIP in the class. Do they matter any more here than they do
27259 // in the normal allocation?
27260 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27261 if (Subtarget->is64Bit()) {
27262 if (VT == MVT::i32 || VT == MVT::f32)
27263 return std::make_pair(0U, &X86::GR32RegClass);
27264 if (VT == MVT::i16)
27265 return std::make_pair(0U, &X86::GR16RegClass);
27266 if (VT == MVT::i8 || VT == MVT::i1)
27267 return std::make_pair(0U, &X86::GR8RegClass);
27268 if (VT == MVT::i64 || VT == MVT::f64)
27269 return std::make_pair(0U, &X86::GR64RegClass);
27272 // 32-bit fallthrough
27273 case 'Q': // Q_REGS
27274 if (VT == MVT::i32 || VT == MVT::f32)
27275 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27276 if (VT == MVT::i16)
27277 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27278 if (VT == MVT::i8 || VT == MVT::i1)
27279 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27280 if (VT == MVT::i64)
27281 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27283 case 'r': // GENERAL_REGS
27284 case 'l': // INDEX_REGS
27285 if (VT == MVT::i8 || VT == MVT::i1)
27286 return std::make_pair(0U, &X86::GR8RegClass);
27287 if (VT == MVT::i16)
27288 return std::make_pair(0U, &X86::GR16RegClass);
27289 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27290 return std::make_pair(0U, &X86::GR32RegClass);
27291 return std::make_pair(0U, &X86::GR64RegClass);
27292 case 'R': // LEGACY_REGS
27293 if (VT == MVT::i8 || VT == MVT::i1)
27294 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27295 if (VT == MVT::i16)
27296 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27297 if (VT == MVT::i32 || !Subtarget->is64Bit())
27298 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27299 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27300 case 'f': // FP Stack registers.
27301 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27302 // value to the correct fpstack register class.
27303 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27304 return std::make_pair(0U, &X86::RFP32RegClass);
27305 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27306 return std::make_pair(0U, &X86::RFP64RegClass);
27307 return std::make_pair(0U, &X86::RFP80RegClass);
27308 case 'y': // MMX_REGS if MMX allowed.
27309 if (!Subtarget->hasMMX()) break;
27310 return std::make_pair(0U, &X86::VR64RegClass);
27311 case 'Y': // SSE_REGS if SSE2 allowed
27312 if (!Subtarget->hasSSE2()) break;
27314 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27315 if (!Subtarget->hasSSE1()) break;
27317 switch (VT.SimpleTy) {
27319 // Scalar SSE types.
27322 return std::make_pair(0U, &X86::FR32RegClass);
27325 return std::make_pair(0U, &X86::FR64RegClass);
27333 return std::make_pair(0U, &X86::VR128RegClass);
27341 return std::make_pair(0U, &X86::VR256RegClass);
27346 return std::make_pair(0U, &X86::VR512RegClass);
27352 // Use the default implementation in TargetLowering to convert the register
27353 // constraint into a member of a register class.
27354 std::pair<unsigned, const TargetRegisterClass*> Res;
27355 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27357 // Not found as a standard register?
27359 // Map st(0) -> st(7) -> ST0
27360 if (Constraint.size() == 7 && Constraint[0] == '{' &&
27361 tolower(Constraint[1]) == 's' &&
27362 tolower(Constraint[2]) == 't' &&
27363 Constraint[3] == '(' &&
27364 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27365 Constraint[5] == ')' &&
27366 Constraint[6] == '}') {
27368 Res.first = X86::FP0+Constraint[4]-'0';
27369 Res.second = &X86::RFP80RegClass;
27373 // GCC allows "st(0)" to be called just plain "st".
27374 if (StringRef("{st}").equals_lower(Constraint)) {
27375 Res.first = X86::FP0;
27376 Res.second = &X86::RFP80RegClass;
27381 if (StringRef("{flags}").equals_lower(Constraint)) {
27382 Res.first = X86::EFLAGS;
27383 Res.second = &X86::CCRRegClass;
27387 // 'A' means EAX + EDX.
27388 if (Constraint == "A") {
27389 Res.first = X86::EAX;
27390 Res.second = &X86::GR32_ADRegClass;
27396 // Otherwise, check to see if this is a register class of the wrong value
27397 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27398 // turn into {ax},{dx}.
27399 // MVT::Other is used to specify clobber names.
27400 if (Res.second->hasType(VT) || VT == MVT::Other)
27401 return Res; // Correct type already, nothing to do.
27403 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27404 // return "eax". This should even work for things like getting 64bit integer
27405 // registers when given an f64 type.
27406 const TargetRegisterClass *Class = Res.second;
27407 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27408 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27409 unsigned Size = VT.getSizeInBits();
27410 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27411 : Size == 16 ? MVT::i16
27412 : Size == 32 ? MVT::i32
27413 : Size == 64 ? MVT::i64
27415 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27417 Res.first = DestReg;
27418 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27419 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27420 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27421 : &X86::GR64RegClass;
27422 assert(Res.second->contains(Res.first) && "Register in register class");
27424 // No register found/type mismatch.
27426 Res.second = nullptr;
27428 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27429 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27430 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27431 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27432 Class == &X86::VR512RegClass) {
27433 // Handle references to XMM physical registers that got mapped into the
27434 // wrong class. This can happen with constraints like {xmm0} where the
27435 // target independent register mapper will just pick the first match it can
27436 // find, ignoring the required type.
27438 if (VT == MVT::f32 || VT == MVT::i32)
27439 Res.second = &X86::FR32RegClass;
27440 else if (VT == MVT::f64 || VT == MVT::i64)
27441 Res.second = &X86::FR64RegClass;
27442 else if (X86::VR128RegClass.hasType(VT))
27443 Res.second = &X86::VR128RegClass;
27444 else if (X86::VR256RegClass.hasType(VT))
27445 Res.second = &X86::VR256RegClass;
27446 else if (X86::VR512RegClass.hasType(VT))
27447 Res.second = &X86::VR512RegClass;
27449 // Type mismatch and not a clobber: Return an error;
27451 Res.second = nullptr;
27458 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27459 const AddrMode &AM, Type *Ty,
27460 unsigned AS) const {
27461 // Scaling factors are not free at all.
27462 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27463 // will take 2 allocations in the out of order engine instead of 1
27464 // for plain addressing mode, i.e. inst (reg1).
27466 // vaddps (%rsi,%drx), %ymm0, %ymm1
27467 // Requires two allocations (one for the load, one for the computation)
27469 // vaddps (%rsi), %ymm0, %ymm1
27470 // Requires just 1 allocation, i.e., freeing allocations for other operations
27471 // and having less micro operations to execute.
27473 // For some X86 architectures, this is even worse because for instance for
27474 // stores, the complex addressing mode forces the instruction to use the
27475 // "load" ports instead of the dedicated "store" port.
27476 // E.g., on Haswell:
27477 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27478 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27479 if (isLegalAddressingMode(DL, AM, Ty, AS))
27480 // Scale represents reg2 * scale, thus account for 1
27481 // as soon as we use a second register.
27482 return AM.Scale != 0;
27486 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27487 // Integer division on x86 is expensive. However, when aggressively optimizing
27488 // for code size, we prefer to use a div instruction, as it is usually smaller
27489 // than the alternative sequence.
27490 // The exception to this is vector division. Since x86 doesn't have vector
27491 // integer division, leaving the division as-is is a loss even in terms of
27492 // size, because it will have to be scalarized, while the alternative code
27493 // sequence can be performed in vector form.
27494 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27495 Attribute::MinSize);
27496 return OptSize && !VT.isVector();
27499 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27500 TargetLowering::ArgListTy& Args) const {
27501 // The MCU psABI requires some arguments to be passed in-register.
27502 // For regular calls, the inreg arguments are marked by the front-end.
27503 // However, for compiler generated library calls, we have to patch this
27505 if (!Subtarget->isTargetMCU() || !Args.size())
27508 unsigned FreeRegs = 3;
27509 for (auto &Arg : Args) {
27510 // For library functions, we do not expect any fancy types.
27511 unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27512 unsigned SizeInRegs = (Size + 31) / 32;
27513 if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27516 Arg.isInReg = true;
27517 FreeRegs -= SizeInRegs;