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 "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
62 #define DEBUG_TYPE "x86-isel"
64 STATISTIC(NumTailCalls, "Number of tail calls");
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67 "x86-experimental-vector-widening-legalization", cl::init(false),
68 cl::desc("Enable an experimental vector type legalization through widening "
69 "rather than promotion."),
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73 const X86Subtarget &STI)
74 : TargetLowering(TM), Subtarget(&STI) {
75 X86ScalarSSEf64 = Subtarget->hasSSE2();
76 X86ScalarSSEf32 = Subtarget->hasSSE1();
77 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
79 // Set up the TargetLowering object.
81 // X86 is weird. It always uses i8 for shift amounts and setcc results.
82 setBooleanContents(ZeroOrOneBooleanContent);
83 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
86 // For 64-bit, since we have so many registers, use the ILP scheduler.
87 // For 32-bit, use the register pressure specific scheduling.
88 // For Atom, always use ILP scheduling.
89 if (Subtarget->isAtom())
90 setSchedulingPreference(Sched::ILP);
91 else if (Subtarget->is64Bit())
92 setSchedulingPreference(Sched::ILP);
94 setSchedulingPreference(Sched::RegPressure);
95 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
98 // Bypass expensive divides on Atom when compiling with O2.
99 if (TM.getOptLevel() >= CodeGenOpt::Default) {
100 if (Subtarget->hasSlowDivide32())
101 addBypassSlowDiv(32, 8);
102 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103 addBypassSlowDiv(64, 16);
106 if (Subtarget->isTargetKnownWindowsMSVC()) {
107 // Setup Windows compiler runtime calls.
108 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110 setLibcallName(RTLIB::SREM_I64, "_allrem");
111 setLibcallName(RTLIB::UREM_I64, "_aullrem");
112 setLibcallName(RTLIB::MUL_I64, "_allmul");
113 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
120 if (Subtarget->isTargetDarwin()) {
121 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122 setUseUnderscoreSetJmp(false);
123 setUseUnderscoreLongJmp(false);
124 } else if (Subtarget->isTargetWindowsGNU()) {
125 // MS runtime is weird: it exports _setjmp, but longjmp!
126 setUseUnderscoreSetJmp(true);
127 setUseUnderscoreLongJmp(false);
129 setUseUnderscoreSetJmp(true);
130 setUseUnderscoreLongJmp(true);
133 // Set up the register classes.
134 addRegisterClass(MVT::i8, &X86::GR8RegClass);
135 addRegisterClass(MVT::i16, &X86::GR16RegClass);
136 addRegisterClass(MVT::i32, &X86::GR32RegClass);
137 if (Subtarget->is64Bit())
138 addRegisterClass(MVT::i64, &X86::GR64RegClass);
140 for (MVT VT : MVT::integer_valuetypes())
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
143 // We don't accept any truncstore of integer registers.
144 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
151 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
153 // SETOEQ and SETUNE require checking two conditions.
154 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
161 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
163 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
165 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
167 if (Subtarget->is64Bit()) {
168 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169 // f32/f64 are legal, f80 is custom.
170 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
173 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
174 } else if (!Subtarget->useSoftFloat()) {
175 // We have an algorithm for SSE2->double, and we turn this into a
176 // 64-bit FILD followed by conditional FADD for other targets.
177 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
178 // We have an algorithm for SSE2, and we turn this into a 64-bit
179 // FILD or VCVTUSI2SS/SD for other targets.
180 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
183 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
185 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
188 if (!Subtarget->useSoftFloat()) {
189 // SSE has no i16 to fp conversion, only i32
190 if (X86ScalarSSEf32) {
191 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
192 // f32 and f64 cases are Legal, f80 case is not
193 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
196 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
200 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (!Subtarget->useSoftFloat()) {
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 if (X86ScalarSSEf32) {
215 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
216 // f32 and f64 cases are Legal, f80 case is not
217 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
219 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
240 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
243 } else if (!Subtarget->useSoftFloat()) {
244 // Since AVX is a superset of SSE3, only check for SSE here.
245 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246 // Expand FP_TO_UINT into a select.
247 // FIXME: We would like to use a Custom expander here eventually to do
248 // the optimal thing for SSE vs. the default expansion in the legalizer.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
251 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252 // With SSE3 we can use fisttpll to convert to a signed i64; without
253 // SSE, we're stuck with a fistpll.
254 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
259 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260 if (!X86ScalarSSEf64) {
261 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
262 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
263 if (Subtarget->is64Bit()) {
264 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
265 // Without SSE, i64->f64 goes through memory.
266 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
268 } else if (!Subtarget->is64Bit())
269 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
271 // Scalar integer divide and remainder are lowered to use operations that
272 // produce two results, to match the available instructions. This exposes
273 // the two-result form to trivial CSE, which is able to combine x/y and x%y
274 // into a single instruction.
276 // Scalar integer multiply-high is also lowered to use two-result
277 // operations, to match the available instructions. However, plain multiply
278 // (low) operations are left as Legal, as there are single-result
279 // instructions for this in x86. Using the two-result multiply instructions
280 // when both high and low results are needed must be arranged by dagcombine.
281 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
282 setOperationAction(ISD::MULHS, VT, Expand);
283 setOperationAction(ISD::MULHU, VT, Expand);
284 setOperationAction(ISD::SDIV, VT, Expand);
285 setOperationAction(ISD::UDIV, VT, Expand);
286 setOperationAction(ISD::SREM, VT, Expand);
287 setOperationAction(ISD::UREM, VT, Expand);
289 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
290 setOperationAction(ISD::ADDC, VT, Custom);
291 setOperationAction(ISD::ADDE, VT, Custom);
292 setOperationAction(ISD::SUBC, VT, Custom);
293 setOperationAction(ISD::SUBE, VT, Custom);
296 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
297 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
298 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
299 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
300 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
301 setOperationAction(ISD::BR_CC , MVT::f128, Expand);
302 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
303 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
305 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::f128, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
313 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
314 if (Subtarget->is64Bit())
315 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
318 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
319 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
321 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
322 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
323 // is. We should promote the value to 64-bits to solve this.
324 // This is what the CRT headers do - `fmodf` is an inline header
325 // function casting to f64 and calling `fmod`.
326 setOperationAction(ISD::FREM , MVT::f32 , Promote);
328 setOperationAction(ISD::FREM , MVT::f32 , Expand);
331 setOperationAction(ISD::FREM , MVT::f64 , Expand);
332 setOperationAction(ISD::FREM , MVT::f80 , Expand);
333 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
335 // Promote the i8 variants and force them on up to i32 which has a shorter
337 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
339 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
340 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
341 if (Subtarget->hasBMI()) {
342 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
344 if (Subtarget->is64Bit())
345 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
347 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
348 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
349 if (Subtarget->is64Bit())
350 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
353 if (Subtarget->hasLZCNT()) {
354 // When promoting the i8 variants, force them to i32 for a shorter
356 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
357 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
359 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
362 if (Subtarget->is64Bit())
363 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
365 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
366 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
367 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
369 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
370 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
371 if (Subtarget->is64Bit()) {
372 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
377 // Special handling for half-precision floating point conversions.
378 // If we don't have F16C support, then lower half float conversions
379 // into library calls.
380 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
381 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
385 // There's never any support for operations beyond MVT::f32.
386 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
387 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
388 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
389 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
391 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
392 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
393 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
394 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
395 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
396 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
398 if (Subtarget->hasPOPCNT()) {
399 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
401 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
402 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
403 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
404 if (Subtarget->is64Bit())
405 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
408 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
410 if (!Subtarget->hasMOVBE())
411 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
413 // These should be promoted to a larger select which is supported.
414 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
415 // X86 wants to expand cmov itself.
416 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
417 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
418 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
419 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f128 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
429 setOperationAction(ISD::SETCC , MVT::f128 , Custom);
430 setOperationAction(ISD::SETCCE , MVT::i8 , Custom);
431 setOperationAction(ISD::SETCCE , MVT::i16 , Custom);
432 setOperationAction(ISD::SETCCE , MVT::i32 , Custom);
433 if (Subtarget->is64Bit()) {
434 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
435 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
436 setOperationAction(ISD::SETCCE , MVT::i64 , Custom);
438 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
439 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
440 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
441 // support continuation, user-level threading, and etc.. As a result, no
442 // other SjLj exception interfaces are implemented and please don't build
443 // your own exception handling based on them.
444 // LLVM/Clang supports zero-cost DWARF exception handling.
445 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
446 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
449 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
450 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
451 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
452 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
453 if (Subtarget->is64Bit())
454 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
455 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
456 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
457 if (Subtarget->is64Bit()) {
458 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
459 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
460 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
461 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
462 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
464 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
465 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
466 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
467 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
468 if (Subtarget->is64Bit()) {
469 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
470 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
471 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
474 if (Subtarget->hasSSE1())
475 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
477 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
479 // Expand certain atomics
480 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
486 if (Subtarget->hasCmpxchg16b()) {
487 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
490 // FIXME - use subtarget debug flags
491 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
492 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
493 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
496 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
497 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
499 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
500 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
502 setOperationAction(ISD::TRAP, MVT::Other, Legal);
503 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
505 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
506 setOperationAction(ISD::VASTART , MVT::Other, Custom);
507 setOperationAction(ISD::VAEND , MVT::Other, Expand);
508 if (Subtarget->is64Bit()) {
509 setOperationAction(ISD::VAARG , MVT::Other, Custom);
510 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
512 // TargetInfo::CharPtrBuiltinVaList
513 setOperationAction(ISD::VAARG , MVT::Other, Expand);
514 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
517 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
518 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
520 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
522 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
523 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
524 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
526 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
527 // f32 and f64 use SSE.
528 // Set up the FP register classes.
529 addRegisterClass(MVT::f32, &X86::FR32RegClass);
530 addRegisterClass(MVT::f64, &X86::FR64RegClass);
532 // Use ANDPD to simulate FABS.
533 setOperationAction(ISD::FABS , MVT::f64, Custom);
534 setOperationAction(ISD::FABS , MVT::f32, Custom);
536 // Use XORP to simulate FNEG.
537 setOperationAction(ISD::FNEG , MVT::f64, Custom);
538 setOperationAction(ISD::FNEG , MVT::f32, Custom);
540 // Use ANDPD and ORPD to simulate FCOPYSIGN.
541 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
542 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
544 // Lower this to FGETSIGNx86 plus an AND.
545 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
546 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
548 // We don't support sin/cos/fmod
549 setOperationAction(ISD::FSIN , MVT::f64, Expand);
550 setOperationAction(ISD::FCOS , MVT::f64, Expand);
551 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
552 setOperationAction(ISD::FSIN , MVT::f32, Expand);
553 setOperationAction(ISD::FCOS , MVT::f32, Expand);
554 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
556 // Expand FP immediates into loads from the stack, except for the special
558 addLegalFPImmediate(APFloat(+0.0)); // xorpd
559 addLegalFPImmediate(APFloat(+0.0f)); // xorps
560 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
561 // Use SSE for f32, x87 for f64.
562 // Set up the FP register classes.
563 addRegisterClass(MVT::f32, &X86::FR32RegClass);
564 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
566 // Use ANDPS to simulate FABS.
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f32, Custom);
572 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
574 // Use ANDPS and ORPS to simulate FCOPYSIGN.
575 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
576 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
578 // We don't support sin/cos/fmod
579 setOperationAction(ISD::FSIN , MVT::f32, Expand);
580 setOperationAction(ISD::FCOS , MVT::f32, Expand);
581 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
583 // Special cases we handle for FP constants.
584 addLegalFPImmediate(APFloat(+0.0f)); // xorps
585 addLegalFPImmediate(APFloat(+0.0)); // FLD0
586 addLegalFPImmediate(APFloat(+1.0)); // FLD1
587 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
588 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
590 if (!TM.Options.UnsafeFPMath) {
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FCOS , MVT::f64, Expand);
593 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
595 } else if (!Subtarget->useSoftFloat()) {
596 // f32 and f64 in x87.
597 // Set up the FP register classes.
598 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
599 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
601 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
602 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
606 if (!TM.Options.UnsafeFPMath) {
607 setOperationAction(ISD::FSIN , MVT::f64, Expand);
608 setOperationAction(ISD::FSIN , MVT::f32, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FCOS , MVT::f32, Expand);
611 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
614 addLegalFPImmediate(APFloat(+0.0)); // FLD0
615 addLegalFPImmediate(APFloat(+1.0)); // FLD1
616 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
617 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
618 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
619 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
620 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
621 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
624 // We don't support FMA.
625 setOperationAction(ISD::FMA, MVT::f64, Expand);
626 setOperationAction(ISD::FMA, MVT::f32, Expand);
628 // Long double always uses X87, except f128 in MMX.
629 if (!Subtarget->useSoftFloat()) {
630 if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
631 addRegisterClass(MVT::f128, &X86::FR128RegClass);
632 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
633 setOperationAction(ISD::FABS , MVT::f128, Custom);
634 setOperationAction(ISD::FNEG , MVT::f128, Custom);
635 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
638 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
639 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
640 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
642 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
643 addLegalFPImmediate(TmpFlt); // FLD0
645 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
648 APFloat TmpFlt2(+1.0);
649 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
651 addLegalFPImmediate(TmpFlt2); // FLD1
652 TmpFlt2.changeSign();
653 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
656 if (!TM.Options.UnsafeFPMath) {
657 setOperationAction(ISD::FSIN , MVT::f80, Expand);
658 setOperationAction(ISD::FCOS , MVT::f80, Expand);
659 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
662 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
663 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
664 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
665 setOperationAction(ISD::FRINT, MVT::f80, Expand);
666 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
667 setOperationAction(ISD::FMA, MVT::f80, Expand);
670 // Always use a library call for pow.
671 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
675 setOperationAction(ISD::FLOG, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
681 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
683 // First set operation action for all vector types to either promote
684 // (for widening) or expand (for scalarization). Then we will selectively
685 // turn on ones that can be effectively codegen'd.
686 for (MVT VT : MVT::vector_valuetypes()) {
687 setOperationAction(ISD::ADD , VT, Expand);
688 setOperationAction(ISD::SUB , VT, Expand);
689 setOperationAction(ISD::FADD, VT, Expand);
690 setOperationAction(ISD::FNEG, VT, Expand);
691 setOperationAction(ISD::FSUB, VT, Expand);
692 setOperationAction(ISD::MUL , VT, Expand);
693 setOperationAction(ISD::FMUL, VT, Expand);
694 setOperationAction(ISD::SDIV, VT, Expand);
695 setOperationAction(ISD::UDIV, VT, Expand);
696 setOperationAction(ISD::FDIV, VT, Expand);
697 setOperationAction(ISD::SREM, VT, Expand);
698 setOperationAction(ISD::UREM, VT, Expand);
699 setOperationAction(ISD::LOAD, VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
705 setOperationAction(ISD::FABS, VT, Expand);
706 setOperationAction(ISD::FSIN, VT, Expand);
707 setOperationAction(ISD::FSINCOS, VT, Expand);
708 setOperationAction(ISD::FCOS, VT, Expand);
709 setOperationAction(ISD::FSINCOS, VT, Expand);
710 setOperationAction(ISD::FREM, VT, Expand);
711 setOperationAction(ISD::FMA, VT, Expand);
712 setOperationAction(ISD::FPOWI, VT, Expand);
713 setOperationAction(ISD::FSQRT, VT, Expand);
714 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
715 setOperationAction(ISD::FFLOOR, VT, Expand);
716 setOperationAction(ISD::FCEIL, VT, Expand);
717 setOperationAction(ISD::FTRUNC, VT, Expand);
718 setOperationAction(ISD::FRINT, VT, Expand);
719 setOperationAction(ISD::FNEARBYINT, VT, Expand);
720 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
721 setOperationAction(ISD::MULHS, VT, Expand);
722 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
723 setOperationAction(ISD::MULHU, VT, Expand);
724 setOperationAction(ISD::SDIVREM, VT, Expand);
725 setOperationAction(ISD::UDIVREM, VT, Expand);
726 setOperationAction(ISD::FPOW, VT, Expand);
727 setOperationAction(ISD::CTPOP, VT, Expand);
728 setOperationAction(ISD::CTTZ, VT, Expand);
729 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
730 setOperationAction(ISD::CTLZ, VT, Expand);
731 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
732 setOperationAction(ISD::SHL, VT, Expand);
733 setOperationAction(ISD::SRA, VT, Expand);
734 setOperationAction(ISD::SRL, VT, Expand);
735 setOperationAction(ISD::ROTL, VT, Expand);
736 setOperationAction(ISD::ROTR, VT, Expand);
737 setOperationAction(ISD::BSWAP, VT, Expand);
738 setOperationAction(ISD::SETCC, VT, Expand);
739 setOperationAction(ISD::FLOG, VT, Expand);
740 setOperationAction(ISD::FLOG2, VT, Expand);
741 setOperationAction(ISD::FLOG10, VT, Expand);
742 setOperationAction(ISD::FEXP, VT, Expand);
743 setOperationAction(ISD::FEXP2, VT, Expand);
744 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
745 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
746 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
747 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
748 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
749 setOperationAction(ISD::TRUNCATE, VT, Expand);
750 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
751 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
752 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
753 setOperationAction(ISD::VSELECT, VT, Expand);
754 setOperationAction(ISD::SELECT_CC, VT, Expand);
755 for (MVT InnerVT : MVT::vector_valuetypes()) {
756 setTruncStoreAction(InnerVT, VT, Expand);
758 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
759 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
761 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
762 // types, we have to deal with them whether we ask for Expansion or not.
763 // Setting Expand causes its own optimisation problems though, so leave
765 if (VT.getVectorElementType() == MVT::i1)
766 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
768 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
769 // split/scalarized right now.
770 if (VT.getVectorElementType() == MVT::f16)
771 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
775 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
776 // with -msoft-float, disable use of MMX as well.
777 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
778 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
779 // No operations on x86mmx supported, everything uses intrinsics.
782 // MMX-sized vectors (other than x86mmx) are expected to be expanded
783 // into smaller operations.
784 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
785 setOperationAction(ISD::MULHS, MMXTy, Expand);
786 setOperationAction(ISD::AND, MMXTy, Expand);
787 setOperationAction(ISD::OR, MMXTy, Expand);
788 setOperationAction(ISD::XOR, MMXTy, Expand);
789 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
790 setOperationAction(ISD::SELECT, MMXTy, Expand);
791 setOperationAction(ISD::BITCAST, MMXTy, Expand);
793 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
795 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
796 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
798 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
799 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
800 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
801 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
802 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
803 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
804 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
805 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
806 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
807 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
808 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
810 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
811 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
814 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
815 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
817 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
818 // registers cannot be used even for integer operations.
819 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
820 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
821 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
822 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
824 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
825 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
826 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
827 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
828 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
829 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
830 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
831 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
832 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
833 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
834 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
835 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
836 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
837 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
838 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
839 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
840 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
841 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
842 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
843 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
844 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
845 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
846 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
848 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
849 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
850 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
851 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
853 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
854 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
855 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
856 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
861 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
866 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
867 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
869 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
870 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
871 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
872 // ISD::CTTZ v2i64 - scalarization is faster.
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
874 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
875 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
876 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
878 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
880 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
882 setOperationAction(ISD::VSELECT, VT, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
886 // We support custom legalizing of sext and anyext loads for specific
887 // memory vector types which we can load as a scalar (or sequence of
888 // scalars) and extend in-register to a legal 128-bit vector type. For sext
889 // loads these must work with a single scalar load.
890 for (MVT VT : MVT::integer_vector_valuetypes()) {
891 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
892 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
893 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
894 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
895 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
896 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
897 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
898 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
899 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
902 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
903 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
905 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
906 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
907 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
909 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
911 if (Subtarget->is64Bit()) {
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
916 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
917 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
918 setOperationAction(ISD::AND, VT, Promote);
919 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
920 setOperationAction(ISD::OR, VT, Promote);
921 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
922 setOperationAction(ISD::XOR, VT, Promote);
923 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
924 setOperationAction(ISD::LOAD, VT, Promote);
925 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
926 setOperationAction(ISD::SELECT, VT, Promote);
927 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
930 // Custom lower v2i64 and v2f64 selects.
931 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
932 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
933 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
934 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
936 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
939 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
941 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
942 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
943 // As there is no 64-bit GPR available, we need build a special custom
944 // sequence to convert from v2i32 to v2f32.
945 if (!Subtarget->is64Bit())
946 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
948 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
949 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
951 for (MVT VT : MVT::fp_vector_valuetypes())
952 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
954 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
955 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
956 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
959 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
960 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
961 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
962 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
963 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
964 setOperationAction(ISD::FRINT, RoundedTy, Legal);
965 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
968 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
969 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
971 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
972 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
973 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
974 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
975 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
977 // FIXME: Do we need to handle scalar-to-vector here?
978 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
980 // We directly match byte blends in the backend as they match the VSELECT
982 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
984 // SSE41 brings specific instructions for doing vector sign extend even in
985 // cases where we don't have SRA.
986 for (MVT VT : MVT::integer_vector_valuetypes()) {
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
988 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
989 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
992 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
997 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
998 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1004 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1005 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1007 // i8 and i16 vectors are custom because the source register and source
1008 // source memory operand types are not the same width. f32 vectors are
1009 // custom since the immediate controlling the insert encodes additional
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1014 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1018 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1021 // FIXME: these should be Legal, but that's only for the case where
1022 // the index is constant. For now custom expand to deal with that.
1023 if (Subtarget->is64Bit()) {
1024 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1029 if (Subtarget->hasSSE2()) {
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1031 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1034 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1035 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1037 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1038 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1040 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1041 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1043 // In the customized shift lowering, the legal cases in AVX2 will be
1045 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1049 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1051 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1052 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1055 if (Subtarget->hasXOP()) {
1056 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1062 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1063 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1066 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1067 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1071 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1072 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1074 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1075 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1076 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1078 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1088 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1091 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1101 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1102 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1104 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1105 // even though v8i16 is a legal type.
1106 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1107 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1108 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1110 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1111 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1112 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1114 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1115 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1117 for (MVT VT : MVT::fp_vector_valuetypes())
1118 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1120 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1121 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1123 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1124 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1126 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1127 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1131 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1132 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1135 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1136 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1139 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1140 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1142 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1143 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1145 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1146 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1148 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1149 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1153 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1154 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1158 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1159 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1162 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1163 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1165 if (Subtarget->hasAnyFMA()) {
1166 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1170 setOperationAction(ISD::FMA, MVT::f32, Legal);
1171 setOperationAction(ISD::FMA, MVT::f64, Legal);
1174 if (Subtarget->hasInt256()) {
1175 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1176 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1177 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1178 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1180 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1181 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1182 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1183 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1185 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1186 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1187 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1188 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1190 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1191 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1192 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1193 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1196 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1197 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1199 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1200 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1202 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1203 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1205 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1206 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1208 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1209 // when we have a 256bit-wide blend with immediate.
1210 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1212 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1217 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1218 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1224 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1225 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1227 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1228 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1229 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1230 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1232 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1233 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1234 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1235 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1237 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1238 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1239 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1240 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1243 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1244 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1246 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1247 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1249 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1250 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1252 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1253 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1256 // In the customized shift lowering, the legal cases in AVX2 will be
1258 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1259 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1261 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1262 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1264 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1265 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1267 // Custom lower several nodes for 256-bit types.
1268 for (MVT VT : MVT::vector_valuetypes()) {
1269 if (VT.getScalarSizeInBits() >= 32) {
1270 setOperationAction(ISD::MLOAD, VT, Legal);
1271 setOperationAction(ISD::MSTORE, VT, Legal);
1273 // Extract subvector is special because the value type
1274 // (result) is 128-bit but the source is 256-bit wide.
1275 if (VT.is128BitVector()) {
1276 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1278 // Do not attempt to custom lower other non-256-bit vectors
1279 if (!VT.is256BitVector())
1282 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1283 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1284 setOperationAction(ISD::VSELECT, VT, Custom);
1285 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1286 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1287 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1288 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1289 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1292 if (Subtarget->hasInt256())
1293 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1295 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1296 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1297 setOperationAction(ISD::AND, VT, Promote);
1298 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1299 setOperationAction(ISD::OR, VT, Promote);
1300 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1301 setOperationAction(ISD::XOR, VT, Promote);
1302 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1303 setOperationAction(ISD::LOAD, VT, Promote);
1304 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1305 setOperationAction(ISD::SELECT, VT, Promote);
1306 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1310 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1311 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1316 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1317 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1318 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1320 for (MVT VT : MVT::fp_vector_valuetypes())
1321 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1323 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1325 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1329 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1330 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1331 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1332 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1333 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1334 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1336 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1337 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1338 setOperationAction(ISD::SETCCE, MVT::i1, Custom);
1339 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1340 setOperationAction(ISD::XOR, MVT::i1, Legal);
1341 setOperationAction(ISD::OR, MVT::i1, Legal);
1342 setOperationAction(ISD::AND, MVT::i1, Legal);
1343 setOperationAction(ISD::SUB, MVT::i1, Custom);
1344 setOperationAction(ISD::ADD, MVT::i1, Custom);
1345 setOperationAction(ISD::MUL, MVT::i1, Custom);
1346 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1349 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1350 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1352 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1357 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1358 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1360 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1364 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1366 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1367 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1368 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1370 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1373 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1384 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1385 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1387 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1388 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1389 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1390 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1391 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1392 if (Subtarget->hasVLX()){
1393 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1394 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1395 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1396 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1397 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1399 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1400 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1401 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1402 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1403 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1405 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1406 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1407 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1408 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1410 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1411 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1412 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1413 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1414 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1415 if (Subtarget->hasDQI()) {
1416 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1417 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1419 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1421 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1422 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1423 if (Subtarget->hasVLX()) {
1424 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1425 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1426 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1427 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1428 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1429 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1430 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1431 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1434 if (Subtarget->hasVLX()) {
1435 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1436 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1437 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1438 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1439 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1440 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1441 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1442 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1444 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1445 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1446 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1447 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1448 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1449 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1450 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1453 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1456 if (Subtarget->hasDQI()) {
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1460 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1461 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1462 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1463 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1464 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1465 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1466 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1467 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1468 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1469 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1475 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1477 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1478 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1480 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1484 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1485 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1486 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1487 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1488 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1493 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1495 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1496 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1497 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1498 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1499 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1500 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1501 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1502 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1504 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1505 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1507 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1508 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1510 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1512 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1513 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1515 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1516 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1518 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1519 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1521 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1522 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1523 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1524 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1525 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1526 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1528 if (Subtarget->hasCDI()) {
1529 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1530 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1531 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Expand);
1532 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Expand);
1534 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1535 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1536 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1537 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Expand);
1539 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Expand);
1540 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Expand);
1541 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Expand);
1543 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1544 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1546 if (Subtarget->hasVLX()) {
1547 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1548 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1549 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1550 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1552 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1553 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1554 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1557 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1558 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1559 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1562 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1563 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1564 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1567 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1568 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1570 } // Subtarget->hasCDI()
1572 if (Subtarget->hasDQI()) {
1573 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1574 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1575 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1577 // Custom lower several nodes.
1578 for (MVT VT : MVT::vector_valuetypes()) {
1579 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1581 setOperationAction(ISD::AND, VT, Legal);
1582 setOperationAction(ISD::OR, VT, Legal);
1583 setOperationAction(ISD::XOR, VT, Legal);
1585 if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1586 setOperationAction(ISD::MGATHER, VT, Custom);
1587 setOperationAction(ISD::MSCATTER, VT, Custom);
1589 // Extract subvector is special because the value type
1590 // (result) is 256/128-bit but the source is 512-bit wide.
1591 if (VT.is128BitVector() || VT.is256BitVector()) {
1592 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1594 if (VT.getVectorElementType() == MVT::i1)
1595 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1597 // Do not attempt to custom lower other non-512-bit vectors
1598 if (!VT.is512BitVector())
1601 if (EltSize >= 32) {
1602 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1603 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1604 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1605 setOperationAction(ISD::VSELECT, VT, Legal);
1606 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1607 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1608 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1609 setOperationAction(ISD::MLOAD, VT, Legal);
1610 setOperationAction(ISD::MSTORE, VT, Legal);
1611 setOperationAction(ISD::MGATHER, VT, Legal);
1612 setOperationAction(ISD::MSCATTER, VT, Custom);
1615 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1616 setOperationAction(ISD::SELECT, VT, Promote);
1617 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1621 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1622 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1623 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1625 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1626 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1628 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1629 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1630 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1631 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1632 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1633 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1634 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1635 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1636 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1637 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1638 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1641 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1642 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1645 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1646 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1649 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1650 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1651 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1652 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1653 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1654 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1657 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1658 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1662 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1663 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1664 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1665 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1666 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1667 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1669 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1671 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1672 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1673 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1674 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1675 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1676 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1677 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1678 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1680 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1681 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1682 if (Subtarget->hasVLX())
1683 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1685 if (Subtarget->hasCDI()) {
1686 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1687 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1689 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Expand);
1692 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1693 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1694 setOperationAction(ISD::VSELECT, VT, Legal);
1695 setOperationAction(ISD::SRL, VT, Custom);
1696 setOperationAction(ISD::SHL, VT, Custom);
1697 setOperationAction(ISD::SRA, VT, Custom);
1699 setOperationAction(ISD::AND, VT, Promote);
1700 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1701 setOperationAction(ISD::OR, VT, Promote);
1702 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1703 setOperationAction(ISD::XOR, VT, Promote);
1704 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1708 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1709 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1710 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1712 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1713 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1715 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1716 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1717 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1718 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1719 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1720 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1721 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1722 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1723 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1725 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1726 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1727 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1728 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1729 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1730 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1731 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1732 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1734 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1735 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1736 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1737 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1738 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1739 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1740 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1741 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1744 // We want to custom lower some of our intrinsics.
1745 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1746 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1747 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1748 if (!Subtarget->is64Bit()) {
1749 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1750 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1753 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1754 // handle type legalization for these operations here.
1756 // FIXME: We really should do custom legalization for addition and
1757 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1758 // than generic legalization for 64-bit multiplication-with-overflow, though.
1759 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1760 if (VT == MVT::i64 && !Subtarget->is64Bit())
1762 // Add/Sub/Mul with overflow operations are custom lowered.
1763 setOperationAction(ISD::SADDO, VT, Custom);
1764 setOperationAction(ISD::UADDO, VT, Custom);
1765 setOperationAction(ISD::SSUBO, VT, Custom);
1766 setOperationAction(ISD::USUBO, VT, Custom);
1767 setOperationAction(ISD::SMULO, VT, Custom);
1768 setOperationAction(ISD::UMULO, VT, Custom);
1771 if (!Subtarget->is64Bit()) {
1772 // These libcalls are not available in 32-bit.
1773 setLibcallName(RTLIB::SHL_I128, nullptr);
1774 setLibcallName(RTLIB::SRL_I128, nullptr);
1775 setLibcallName(RTLIB::SRA_I128, nullptr);
1778 // Combine sin / cos into one node or libcall if possible.
1779 if (Subtarget->hasSinCos()) {
1780 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1781 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1782 if (Subtarget->isTargetDarwin()) {
1783 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1784 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1785 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1786 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1790 if (Subtarget->isTargetWin64()) {
1791 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1792 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1793 setOperationAction(ISD::SREM, MVT::i128, Custom);
1794 setOperationAction(ISD::UREM, MVT::i128, Custom);
1795 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1796 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1799 // We have target-specific dag combine patterns for the following nodes:
1800 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1801 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1802 setTargetDAGCombine(ISD::BITCAST);
1803 setTargetDAGCombine(ISD::VSELECT);
1804 setTargetDAGCombine(ISD::SELECT);
1805 setTargetDAGCombine(ISD::SHL);
1806 setTargetDAGCombine(ISD::SRA);
1807 setTargetDAGCombine(ISD::SRL);
1808 setTargetDAGCombine(ISD::OR);
1809 setTargetDAGCombine(ISD::AND);
1810 setTargetDAGCombine(ISD::ADD);
1811 setTargetDAGCombine(ISD::FADD);
1812 setTargetDAGCombine(ISD::FSUB);
1813 setTargetDAGCombine(ISD::FNEG);
1814 setTargetDAGCombine(ISD::FMA);
1815 setTargetDAGCombine(ISD::FMINNUM);
1816 setTargetDAGCombine(ISD::FMAXNUM);
1817 setTargetDAGCombine(ISD::SUB);
1818 setTargetDAGCombine(ISD::LOAD);
1819 setTargetDAGCombine(ISD::MLOAD);
1820 setTargetDAGCombine(ISD::STORE);
1821 setTargetDAGCombine(ISD::MSTORE);
1822 setTargetDAGCombine(ISD::TRUNCATE);
1823 setTargetDAGCombine(ISD::ZERO_EXTEND);
1824 setTargetDAGCombine(ISD::ANY_EXTEND);
1825 setTargetDAGCombine(ISD::SIGN_EXTEND);
1826 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1827 setTargetDAGCombine(ISD::SINT_TO_FP);
1828 setTargetDAGCombine(ISD::UINT_TO_FP);
1829 setTargetDAGCombine(ISD::SETCC);
1830 setTargetDAGCombine(ISD::BUILD_VECTOR);
1831 setTargetDAGCombine(ISD::MUL);
1832 setTargetDAGCombine(ISD::XOR);
1833 setTargetDAGCombine(ISD::MSCATTER);
1834 setTargetDAGCombine(ISD::MGATHER);
1836 computeRegisterProperties(Subtarget->getRegisterInfo());
1838 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1839 MaxStoresPerMemsetOptSize = 8;
1840 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1841 MaxStoresPerMemcpyOptSize = 4;
1842 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1843 MaxStoresPerMemmoveOptSize = 4;
1844 setPrefLoopAlignment(4); // 2^4 bytes.
1846 // A predictable cmov does not hurt on an in-order CPU.
1847 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1848 PredictableSelectIsExpensive = !Subtarget->isAtom();
1849 EnableExtLdPromotion = true;
1850 setPrefFunctionAlignment(4); // 2^4 bytes.
1852 verifyIntrinsicTables();
1855 // This has so far only been implemented for 64-bit MachO.
1856 bool X86TargetLowering::useLoadStackGuardNode() const {
1857 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1860 TargetLoweringBase::LegalizeTypeAction
1861 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1862 if (ExperimentalVectorWideningLegalization &&
1863 VT.getVectorNumElements() != 1 &&
1864 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1865 return TypeWidenVector;
1867 return TargetLoweringBase::getPreferredVectorAction(VT);
1870 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1873 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1875 if (VT.isSimple()) {
1876 MVT VVT = VT.getSimpleVT();
1877 const unsigned NumElts = VVT.getVectorNumElements();
1878 const MVT EltVT = VVT.getVectorElementType();
1879 if (VVT.is512BitVector()) {
1880 if (Subtarget->hasAVX512())
1881 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1882 EltVT == MVT::f32 || EltVT == MVT::f64)
1884 case 8: return MVT::v8i1;
1885 case 16: return MVT::v16i1;
1887 if (Subtarget->hasBWI())
1888 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1890 case 32: return MVT::v32i1;
1891 case 64: return MVT::v64i1;
1895 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1896 if (Subtarget->hasVLX())
1897 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1898 EltVT == MVT::f32 || EltVT == MVT::f64)
1900 case 2: return MVT::v2i1;
1901 case 4: return MVT::v4i1;
1902 case 8: return MVT::v8i1;
1904 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1905 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1907 case 8: return MVT::v8i1;
1908 case 16: return MVT::v16i1;
1909 case 32: return MVT::v32i1;
1914 return VT.changeVectorElementTypeToInteger();
1917 /// Helper for getByValTypeAlignment to determine
1918 /// the desired ByVal argument alignment.
1919 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1922 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1923 if (VTy->getBitWidth() == 128)
1925 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1926 unsigned EltAlign = 0;
1927 getMaxByValAlign(ATy->getElementType(), EltAlign);
1928 if (EltAlign > MaxAlign)
1929 MaxAlign = EltAlign;
1930 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1931 for (auto *EltTy : STy->elements()) {
1932 unsigned EltAlign = 0;
1933 getMaxByValAlign(EltTy, EltAlign);
1934 if (EltAlign > MaxAlign)
1935 MaxAlign = EltAlign;
1942 /// Return the desired alignment for ByVal aggregate
1943 /// function arguments in the caller parameter area. For X86, aggregates
1944 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1945 /// are at 4-byte boundaries.
1946 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1947 const DataLayout &DL) const {
1948 if (Subtarget->is64Bit()) {
1949 // Max of 8 and alignment of type.
1950 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1957 if (Subtarget->hasSSE1())
1958 getMaxByValAlign(Ty, Align);
1962 /// Returns the target specific optimal type for load
1963 /// and store operations as a result of memset, memcpy, and memmove
1964 /// lowering. If DstAlign is zero that means it's safe to destination
1965 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1966 /// means there isn't a need to check it against alignment requirement,
1967 /// probably because the source does not need to be loaded. If 'IsMemset' is
1968 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1969 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1970 /// source is constant so it does not need to be loaded.
1971 /// It returns EVT::Other if the type should be determined using generic
1972 /// target-independent logic.
1974 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1975 unsigned DstAlign, unsigned SrcAlign,
1976 bool IsMemset, bool ZeroMemset,
1978 MachineFunction &MF) const {
1979 const Function *F = MF.getFunction();
1980 if ((!IsMemset || ZeroMemset) &&
1981 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1983 (!Subtarget->isUnalignedMem16Slow() ||
1984 ((DstAlign == 0 || DstAlign >= 16) &&
1985 (SrcAlign == 0 || SrcAlign >= 16)))) {
1987 // FIXME: Check if unaligned 32-byte accesses are slow.
1988 if (Subtarget->hasInt256())
1990 if (Subtarget->hasFp256())
1993 if (Subtarget->hasSSE2())
1995 if (Subtarget->hasSSE1())
1997 } else if (!MemcpyStrSrc && Size >= 8 &&
1998 !Subtarget->is64Bit() &&
1999 Subtarget->hasSSE2()) {
2000 // Do not use f64 to lower memcpy if source is string constant. It's
2001 // better to use i32 to avoid the loads.
2005 // This is a compromise. If we reach here, unaligned accesses may be slow on
2006 // this target. However, creating smaller, aligned accesses could be even
2007 // slower and would certainly be a lot more code.
2008 if (Subtarget->is64Bit() && Size >= 8)
2013 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2015 return X86ScalarSSEf32;
2016 else if (VT == MVT::f64)
2017 return X86ScalarSSEf64;
2022 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2027 switch (VT.getSizeInBits()) {
2029 // 8-byte and under are always assumed to be fast.
2033 *Fast = !Subtarget->isUnalignedMem16Slow();
2036 *Fast = !Subtarget->isUnalignedMem32Slow();
2038 // TODO: What about AVX-512 (512-bit) accesses?
2041 // Misaligned accesses of any size are always allowed.
2045 /// Return the entry encoding for a jump table in the
2046 /// current function. The returned value is a member of the
2047 /// MachineJumpTableInfo::JTEntryKind enum.
2048 unsigned X86TargetLowering::getJumpTableEncoding() const {
2049 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2051 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2052 Subtarget->isPICStyleGOT())
2053 return MachineJumpTableInfo::EK_Custom32;
2055 // Otherwise, use the normal jump table encoding heuristics.
2056 return TargetLowering::getJumpTableEncoding();
2059 bool X86TargetLowering::useSoftFloat() const {
2060 return Subtarget->useSoftFloat();
2064 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2065 const MachineBasicBlock *MBB,
2066 unsigned uid,MCContext &Ctx) const{
2067 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2068 Subtarget->isPICStyleGOT());
2069 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2071 return MCSymbolRefExpr::create(MBB->getSymbol(),
2072 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2075 /// Returns relocation base for the given PIC jumptable.
2076 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2077 SelectionDAG &DAG) const {
2078 if (!Subtarget->is64Bit())
2079 // This doesn't have SDLoc associated with it, but is not really the
2080 // same as a Register.
2081 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2082 getPointerTy(DAG.getDataLayout()));
2086 /// This returns the relocation base for the given PIC jumptable,
2087 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2088 const MCExpr *X86TargetLowering::
2089 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2090 MCContext &Ctx) const {
2091 // X86-64 uses RIP relative addressing based on the jump table label.
2092 if (Subtarget->isPICStyleRIPRel())
2093 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2095 // Otherwise, the reference is relative to the PIC base.
2096 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2099 std::pair<const TargetRegisterClass *, uint8_t>
2100 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2102 const TargetRegisterClass *RRC = nullptr;
2104 switch (VT.SimpleTy) {
2106 return TargetLowering::findRepresentativeClass(TRI, VT);
2107 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2108 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2111 RRC = &X86::VR64RegClass;
2113 case MVT::f32: case MVT::f64:
2114 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2115 case MVT::v4f32: case MVT::v2f64:
2116 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2118 RRC = &X86::VR128RegClass;
2121 return std::make_pair(RRC, Cost);
2124 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2125 unsigned &Offset) const {
2126 if (!Subtarget->isTargetLinux())
2129 if (Subtarget->is64Bit()) {
2130 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2132 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2144 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2145 if (!Subtarget->isTargetAndroid())
2146 return TargetLowering::getSafeStackPointerLocation(IRB);
2148 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2149 // definition of TLS_SLOT_SAFESTACK in
2150 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2151 unsigned AddressSpace, Offset;
2152 if (Subtarget->is64Bit()) {
2153 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2155 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2165 return ConstantExpr::getIntToPtr(
2166 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2167 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2170 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2171 unsigned DestAS) const {
2172 assert(SrcAS != DestAS && "Expected different address spaces!");
2174 return SrcAS < 256 && DestAS < 256;
2177 //===----------------------------------------------------------------------===//
2178 // Return Value Calling Convention Implementation
2179 //===----------------------------------------------------------------------===//
2181 #include "X86GenCallingConv.inc"
2183 bool X86TargetLowering::CanLowerReturn(
2184 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2185 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2186 SmallVector<CCValAssign, 16> RVLocs;
2187 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2188 return CCInfo.CheckReturn(Outs, RetCC_X86);
2191 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2192 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2197 X86TargetLowering::LowerReturn(SDValue Chain,
2198 CallingConv::ID CallConv, bool isVarArg,
2199 const SmallVectorImpl<ISD::OutputArg> &Outs,
2200 const SmallVectorImpl<SDValue> &OutVals,
2201 SDLoc dl, SelectionDAG &DAG) const {
2202 MachineFunction &MF = DAG.getMachineFunction();
2203 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2205 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2206 report_fatal_error("X86 interrupts may not return any value");
2208 SmallVector<CCValAssign, 16> RVLocs;
2209 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2210 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2213 SmallVector<SDValue, 6> RetOps;
2214 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2215 // Operand #1 = Bytes To Pop
2216 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2219 // Copy the result values into the output registers.
2220 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2221 CCValAssign &VA = RVLocs[i];
2222 assert(VA.isRegLoc() && "Can only return in registers!");
2223 SDValue ValToCopy = OutVals[i];
2224 EVT ValVT = ValToCopy.getValueType();
2226 // Promote values to the appropriate types.
2227 if (VA.getLocInfo() == CCValAssign::SExt)
2228 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229 else if (VA.getLocInfo() == CCValAssign::ZExt)
2230 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2231 else if (VA.getLocInfo() == CCValAssign::AExt) {
2232 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2233 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2235 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2237 else if (VA.getLocInfo() == CCValAssign::BCvt)
2238 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2240 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2241 "Unexpected FP-extend for return value.");
2243 // If this is x86-64, and we disabled SSE, we can't return FP values,
2244 // or SSE or MMX vectors.
2245 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2246 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2247 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2248 report_fatal_error("SSE register return with SSE disabled");
2250 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2251 // llvm-gcc has never done it right and no one has noticed, so this
2252 // should be OK for now.
2253 if (ValVT == MVT::f64 &&
2254 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2255 report_fatal_error("SSE2 register return with SSE2 disabled");
2257 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2258 // the RET instruction and handled by the FP Stackifier.
2259 if (VA.getLocReg() == X86::FP0 ||
2260 VA.getLocReg() == X86::FP1) {
2261 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2262 // change the value to the FP stack register class.
2263 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2264 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2265 RetOps.push_back(ValToCopy);
2266 // Don't emit a copytoreg.
2270 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2271 // which is returned in RAX / RDX.
2272 if (Subtarget->is64Bit()) {
2273 if (ValVT == MVT::x86mmx) {
2274 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2275 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2276 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2278 // If we don't have SSE2 available, convert to v4f32 so the generated
2279 // register is legal.
2280 if (!Subtarget->hasSSE2())
2281 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2287 Flag = Chain.getValue(1);
2288 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2291 // All x86 ABIs require that for returning structs by value we copy
2292 // the sret argument into %rax/%eax (depending on ABI) for the return.
2293 // We saved the argument into a virtual register in the entry block,
2294 // so now we copy the value out and into %rax/%eax.
2296 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2297 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2298 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2299 // either case FuncInfo->setSRetReturnReg() will have been called.
2300 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2301 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2302 getPointerTy(MF.getDataLayout()));
2305 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2306 X86::RAX : X86::EAX;
2307 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2308 Flag = Chain.getValue(1);
2310 // RAX/EAX now acts like a return value.
2312 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2315 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2316 const MCPhysReg *I =
2317 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2320 if (X86::GR64RegClass.contains(*I))
2321 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2323 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2327 RetOps[0] = Chain; // Update chain.
2329 // Add the flag if we have it.
2331 RetOps.push_back(Flag);
2333 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2334 if (CallConv == CallingConv::X86_INTR)
2335 opcode = X86ISD::IRET;
2336 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2339 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2340 if (N->getNumValues() != 1)
2342 if (!N->hasNUsesOfValue(1, 0))
2345 SDValue TCChain = Chain;
2346 SDNode *Copy = *N->use_begin();
2347 if (Copy->getOpcode() == ISD::CopyToReg) {
2348 // If the copy has a glue operand, we conservatively assume it isn't safe to
2349 // perform a tail call.
2350 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2352 TCChain = Copy->getOperand(0);
2353 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2356 bool HasRet = false;
2357 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2359 if (UI->getOpcode() != X86ISD::RET_FLAG)
2361 // If we are returning more than one value, we can definitely
2362 // not make a tail call see PR19530
2363 if (UI->getNumOperands() > 4)
2365 if (UI->getNumOperands() == 4 &&
2366 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2379 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2380 ISD::NodeType ExtendKind) const {
2382 // TODO: Is this also valid on 32-bit?
2383 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2384 ReturnMVT = MVT::i8;
2386 ReturnMVT = MVT::i32;
2388 EVT MinVT = getRegisterType(Context, ReturnMVT);
2389 return VT.bitsLT(MinVT) ? MinVT : VT;
2392 /// Lower the result values of a call into the
2393 /// appropriate copies out of appropriate physical registers.
2396 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2397 CallingConv::ID CallConv, bool isVarArg,
2398 const SmallVectorImpl<ISD::InputArg> &Ins,
2399 SDLoc dl, SelectionDAG &DAG,
2400 SmallVectorImpl<SDValue> &InVals) const {
2402 // Assign locations to each value returned by this call.
2403 SmallVector<CCValAssign, 16> RVLocs;
2404 bool Is64Bit = Subtarget->is64Bit();
2405 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2407 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2409 // Copy all of the result registers out of their specified physreg.
2410 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2411 CCValAssign &VA = RVLocs[i];
2412 EVT CopyVT = VA.getLocVT();
2414 // If this is x86-64, and we disabled SSE, we can't return FP values
2415 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2416 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2417 report_fatal_error("SSE register return with SSE disabled");
2420 // If we prefer to use the value in xmm registers, copy it out as f80 and
2421 // use a truncate to move it from fp stack reg to xmm reg.
2422 bool RoundAfterCopy = false;
2423 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2424 isScalarFPTypeInSSEReg(VA.getValVT())) {
2426 RoundAfterCopy = (CopyVT != VA.getLocVT());
2429 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2430 CopyVT, InFlag).getValue(1);
2431 SDValue Val = Chain.getValue(0);
2434 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2435 // This truncation won't change the value.
2436 DAG.getIntPtrConstant(1, dl));
2438 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2439 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2441 InFlag = Chain.getValue(2);
2442 InVals.push_back(Val);
2448 //===----------------------------------------------------------------------===//
2449 // C & StdCall & Fast Calling Convention implementation
2450 //===----------------------------------------------------------------------===//
2451 // StdCall calling convention seems to be standard for many Windows' API
2452 // routines and around. It differs from C calling convention just a little:
2453 // callee should clean up the stack, not caller. Symbols should be also
2454 // decorated in some fancy way :) It doesn't support any vector arguments.
2455 // For info on fast calling convention see Fast Calling Convention (tail call)
2456 // implementation LowerX86_32FastCCCallTo.
2458 /// CallIsStructReturn - Determines whether a call uses struct return
2460 enum StructReturnType {
2465 static StructReturnType
2466 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2468 return NotStructReturn;
2470 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2471 if (!Flags.isSRet())
2472 return NotStructReturn;
2473 if (Flags.isInReg() || IsMCU)
2474 return RegStructReturn;
2475 return StackStructReturn;
2478 /// Determines whether a function uses struct return semantics.
2479 static StructReturnType
2480 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2482 return NotStructReturn;
2484 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2485 if (!Flags.isSRet())
2486 return NotStructReturn;
2487 if (Flags.isInReg() || IsMCU)
2488 return RegStructReturn;
2489 return StackStructReturn;
2492 /// Make a copy of an aggregate at address specified by "Src" to address
2493 /// "Dst" with size and alignment information specified by the specific
2494 /// parameter attribute. The copy will be passed as a byval function parameter.
2496 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2497 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2499 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2501 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2502 /*isVolatile*/false, /*AlwaysInline=*/true,
2503 /*isTailCall*/false,
2504 MachinePointerInfo(), MachinePointerInfo());
2507 /// Return true if the calling convention is one that we can guarantee TCO for.
2508 static bool canGuaranteeTCO(CallingConv::ID CC) {
2509 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2510 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2513 /// Return true if we might ever do TCO for calls with this calling convention.
2514 static bool mayTailCallThisCC(CallingConv::ID CC) {
2516 // C calling conventions:
2517 case CallingConv::C:
2518 case CallingConv::X86_64_Win64:
2519 case CallingConv::X86_64_SysV:
2520 // Callee pop conventions:
2521 case CallingConv::X86_ThisCall:
2522 case CallingConv::X86_StdCall:
2523 case CallingConv::X86_VectorCall:
2524 case CallingConv::X86_FastCall:
2527 return canGuaranteeTCO(CC);
2531 /// Return true if the function is being made into a tailcall target by
2532 /// changing its ABI.
2533 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2534 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2537 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2539 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2540 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2544 CallingConv::ID CalleeCC = CS.getCallingConv();
2545 if (!mayTailCallThisCC(CalleeCC))
2552 X86TargetLowering::LowerMemArgument(SDValue Chain,
2553 CallingConv::ID CallConv,
2554 const SmallVectorImpl<ISD::InputArg> &Ins,
2555 SDLoc dl, SelectionDAG &DAG,
2556 const CCValAssign &VA,
2557 MachineFrameInfo *MFI,
2559 // Create the nodes corresponding to a load from this parameter slot.
2560 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2561 bool AlwaysUseMutable = shouldGuaranteeTCO(
2562 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2563 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2566 // If value is passed by pointer we have address passed instead of the value
2568 bool ExtendedInMem = VA.isExtInLoc() &&
2569 VA.getValVT().getScalarType() == MVT::i1;
2571 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2572 ValVT = VA.getLocVT();
2574 ValVT = VA.getValVT();
2576 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2577 // taken by a return address.
2579 if (CallConv == CallingConv::X86_INTR) {
2580 const X86Subtarget& Subtarget =
2581 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2582 // X86 interrupts may take one or two arguments.
2583 // On the stack there will be no return address as in regular call.
2584 // Offset of last argument need to be set to -4/-8 bytes.
2585 // Where offset of the first argument out of two, should be set to 0 bytes.
2586 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2589 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2590 // changed with more analysis.
2591 // In case of tail call optimization mark all arguments mutable. Since they
2592 // could be overwritten by lowering of arguments in case of a tail call.
2593 if (Flags.isByVal()) {
2594 unsigned Bytes = Flags.getByValSize();
2595 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2596 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2597 // Adjust SP offset of interrupt parameter.
2598 if (CallConv == CallingConv::X86_INTR) {
2599 MFI->setObjectOffset(FI, Offset);
2601 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2603 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2604 VA.getLocMemOffset(), isImmutable);
2605 // Adjust SP offset of interrupt parameter.
2606 if (CallConv == CallingConv::X86_INTR) {
2607 MFI->setObjectOffset(FI, Offset);
2610 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2611 SDValue Val = DAG.getLoad(
2612 ValVT, dl, Chain, FIN,
2613 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2615 return ExtendedInMem ?
2616 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2620 // FIXME: Get this from tablegen.
2621 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2622 const X86Subtarget *Subtarget) {
2623 assert(Subtarget->is64Bit());
2625 if (Subtarget->isCallingConvWin64(CallConv)) {
2626 static const MCPhysReg GPR64ArgRegsWin64[] = {
2627 X86::RCX, X86::RDX, X86::R8, X86::R9
2629 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2632 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2633 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2635 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2638 // FIXME: Get this from tablegen.
2639 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2640 CallingConv::ID CallConv,
2641 const X86Subtarget *Subtarget) {
2642 assert(Subtarget->is64Bit());
2643 if (Subtarget->isCallingConvWin64(CallConv)) {
2644 // The XMM registers which might contain var arg parameters are shadowed
2645 // in their paired GPR. So we only need to save the GPR to their home
2647 // TODO: __vectorcall will change this.
2651 const Function *Fn = MF.getFunction();
2652 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2653 bool isSoftFloat = Subtarget->useSoftFloat();
2654 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2655 "SSE register cannot be used when SSE is disabled!");
2656 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2657 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2661 static const MCPhysReg XMMArgRegs64Bit[] = {
2662 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2663 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2665 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2668 SDValue X86TargetLowering::LowerFormalArguments(
2669 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2670 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2671 SmallVectorImpl<SDValue> &InVals) const {
2672 MachineFunction &MF = DAG.getMachineFunction();
2673 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2674 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2676 const Function* Fn = MF.getFunction();
2677 if (Fn->hasExternalLinkage() &&
2678 Subtarget->isTargetCygMing() &&
2679 Fn->getName() == "main")
2680 FuncInfo->setForceFramePointer(true);
2682 MachineFrameInfo *MFI = MF.getFrameInfo();
2683 bool Is64Bit = Subtarget->is64Bit();
2684 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2686 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2687 "Var args not supported with calling convention fastcc, ghc or hipe");
2689 if (CallConv == CallingConv::X86_INTR) {
2690 bool isLegal = Ins.size() == 1 ||
2691 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2692 (!Is64Bit && Ins[1].VT == MVT::i32)));
2694 report_fatal_error("X86 interrupts may take one or two arguments");
2697 // Assign locations to all of the incoming arguments.
2698 SmallVector<CCValAssign, 16> ArgLocs;
2699 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2701 // Allocate shadow area for Win64
2703 CCInfo.AllocateStack(32, 8);
2705 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2707 unsigned LastVal = ~0U;
2709 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2710 CCValAssign &VA = ArgLocs[i];
2711 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2713 assert(VA.getValNo() != LastVal &&
2714 "Don't support value assigned to multiple locs yet");
2716 LastVal = VA.getValNo();
2718 if (VA.isRegLoc()) {
2719 EVT RegVT = VA.getLocVT();
2720 const TargetRegisterClass *RC;
2721 if (RegVT == MVT::i32)
2722 RC = &X86::GR32RegClass;
2723 else if (Is64Bit && RegVT == MVT::i64)
2724 RC = &X86::GR64RegClass;
2725 else if (RegVT == MVT::f32)
2726 RC = &X86::FR32RegClass;
2727 else if (RegVT == MVT::f64)
2728 RC = &X86::FR64RegClass;
2729 else if (RegVT == MVT::f128)
2730 RC = &X86::FR128RegClass;
2731 else if (RegVT.is512BitVector())
2732 RC = &X86::VR512RegClass;
2733 else if (RegVT.is256BitVector())
2734 RC = &X86::VR256RegClass;
2735 else if (RegVT.is128BitVector())
2736 RC = &X86::VR128RegClass;
2737 else if (RegVT == MVT::x86mmx)
2738 RC = &X86::VR64RegClass;
2739 else if (RegVT == MVT::i1)
2740 RC = &X86::VK1RegClass;
2741 else if (RegVT == MVT::v8i1)
2742 RC = &X86::VK8RegClass;
2743 else if (RegVT == MVT::v16i1)
2744 RC = &X86::VK16RegClass;
2745 else if (RegVT == MVT::v32i1)
2746 RC = &X86::VK32RegClass;
2747 else if (RegVT == MVT::v64i1)
2748 RC = &X86::VK64RegClass;
2750 llvm_unreachable("Unknown argument type!");
2752 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2753 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2755 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2756 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2758 if (VA.getLocInfo() == CCValAssign::SExt)
2759 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2760 DAG.getValueType(VA.getValVT()));
2761 else if (VA.getLocInfo() == CCValAssign::ZExt)
2762 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2763 DAG.getValueType(VA.getValVT()));
2764 else if (VA.getLocInfo() == CCValAssign::BCvt)
2765 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2767 if (VA.isExtInLoc()) {
2768 // Handle MMX values passed in XMM regs.
2769 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2770 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2772 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2775 assert(VA.isMemLoc());
2776 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2779 // If value is passed via pointer - do a load.
2780 if (VA.getLocInfo() == CCValAssign::Indirect)
2781 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2782 MachinePointerInfo(), false, false, false, 0);
2784 InVals.push_back(ArgValue);
2787 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2788 // All x86 ABIs require that for returning structs by value we copy the
2789 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2790 // the argument into a virtual register so that we can access it from the
2792 if (Ins[i].Flags.isSRet()) {
2793 unsigned Reg = FuncInfo->getSRetReturnReg();
2795 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2796 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2797 FuncInfo->setSRetReturnReg(Reg);
2799 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2800 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2805 unsigned StackSize = CCInfo.getNextStackOffset();
2806 // Align stack specially for tail calls.
2807 if (shouldGuaranteeTCO(CallConv,
2808 MF.getTarget().Options.GuaranteedTailCallOpt))
2809 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2811 // If the function takes variable number of arguments, make a frame index for
2812 // the start of the first vararg value... for expansion of llvm.va_start. We
2813 // can skip this if there are no va_start calls.
2814 if (MFI->hasVAStart() &&
2815 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2816 CallConv != CallingConv::X86_ThisCall))) {
2817 FuncInfo->setVarArgsFrameIndex(
2818 MFI->CreateFixedObject(1, StackSize, true));
2821 // Figure out if XMM registers are in use.
2822 assert(!(Subtarget->useSoftFloat() &&
2823 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2824 "SSE register cannot be used when SSE is disabled!");
2826 // 64-bit calling conventions support varargs and register parameters, so we
2827 // have to do extra work to spill them in the prologue.
2828 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2829 // Find the first unallocated argument registers.
2830 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2831 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2832 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2833 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2834 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2835 "SSE register cannot be used when SSE is disabled!");
2837 // Gather all the live in physical registers.
2838 SmallVector<SDValue, 6> LiveGPRs;
2839 SmallVector<SDValue, 8> LiveXMMRegs;
2841 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2842 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2844 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2846 if (!ArgXMMs.empty()) {
2847 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2848 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2849 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2850 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2851 LiveXMMRegs.push_back(
2852 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2857 // Get to the caller-allocated home save location. Add 8 to account
2858 // for the return address.
2859 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2860 FuncInfo->setRegSaveFrameIndex(
2861 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2862 // Fixup to set vararg frame on shadow area (4 x i64).
2864 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2866 // For X86-64, if there are vararg parameters that are passed via
2867 // registers, then we must store them to their spots on the stack so
2868 // they may be loaded by deferencing the result of va_next.
2869 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2870 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2871 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2872 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2875 // Store the integer parameter registers.
2876 SmallVector<SDValue, 8> MemOps;
2877 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2878 getPointerTy(DAG.getDataLayout()));
2879 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2880 for (SDValue Val : LiveGPRs) {
2881 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2882 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2884 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2885 MachinePointerInfo::getFixedStack(
2886 DAG.getMachineFunction(),
2887 FuncInfo->getRegSaveFrameIndex(), Offset),
2889 MemOps.push_back(Store);
2893 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2894 // Now store the XMM (fp + vector) parameter registers.
2895 SmallVector<SDValue, 12> SaveXMMOps;
2896 SaveXMMOps.push_back(Chain);
2897 SaveXMMOps.push_back(ALVal);
2898 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2899 FuncInfo->getRegSaveFrameIndex(), dl));
2900 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2901 FuncInfo->getVarArgsFPOffset(), dl));
2902 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2904 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2905 MVT::Other, SaveXMMOps));
2908 if (!MemOps.empty())
2909 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2912 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2913 // Find the largest legal vector type.
2914 MVT VecVT = MVT::Other;
2915 // FIXME: Only some x86_32 calling conventions support AVX512.
2916 if (Subtarget->hasAVX512() &&
2917 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2918 CallConv == CallingConv::Intel_OCL_BI)))
2919 VecVT = MVT::v16f32;
2920 else if (Subtarget->hasAVX())
2922 else if (Subtarget->hasSSE2())
2925 // We forward some GPRs and some vector types.
2926 SmallVector<MVT, 2> RegParmTypes;
2927 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2928 RegParmTypes.push_back(IntVT);
2929 if (VecVT != MVT::Other)
2930 RegParmTypes.push_back(VecVT);
2932 // Compute the set of forwarded registers. The rest are scratch.
2933 SmallVectorImpl<ForwardedRegister> &Forwards =
2934 FuncInfo->getForwardedMustTailRegParms();
2935 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2937 // Conservatively forward AL on x86_64, since it might be used for varargs.
2938 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2939 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2940 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2943 // Copy all forwards from physical to virtual registers.
2944 for (ForwardedRegister &F : Forwards) {
2945 // FIXME: Can we use a less constrained schedule?
2946 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2947 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2948 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2952 // Some CCs need callee pop.
2953 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2954 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2955 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2956 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2957 // X86 interrupts must pop the error code if present
2958 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2960 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2961 // If this is an sret function, the return should pop the hidden pointer.
2962 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2963 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2964 argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2965 FuncInfo->setBytesToPopOnReturn(4);
2969 // RegSaveFrameIndex is X86-64 only.
2970 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2971 if (CallConv == CallingConv::X86_FastCall ||
2972 CallConv == CallingConv::X86_ThisCall)
2973 // fastcc functions can't have varargs.
2974 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2977 FuncInfo->setArgumentStackSize(StackSize);
2979 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2980 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2981 if (Personality == EHPersonality::CoreCLR) {
2983 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2984 // that we'd prefer this slot be allocated towards the bottom of the frame
2985 // (i.e. near the stack pointer after allocating the frame). Every
2986 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2987 // offset from the bottom of this and each funclet's frame must be the
2988 // same, so the size of funclets' (mostly empty) frames is dictated by
2989 // how far this slot is from the bottom (since they allocate just enough
2990 // space to accomodate holding this slot at the correct offset).
2991 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2992 EHInfo->PSPSymFrameIdx = PSPSymFI;
3000 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3001 SDValue StackPtr, SDValue Arg,
3002 SDLoc dl, SelectionDAG &DAG,
3003 const CCValAssign &VA,
3004 ISD::ArgFlagsTy Flags) const {
3005 unsigned LocMemOffset = VA.getLocMemOffset();
3006 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3007 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3009 if (Flags.isByVal())
3010 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3012 return DAG.getStore(
3013 Chain, dl, Arg, PtrOff,
3014 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3018 /// Emit a load of return address if tail call
3019 /// optimization is performed and it is required.
3021 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3022 SDValue &OutRetAddr, SDValue Chain,
3023 bool IsTailCall, bool Is64Bit,
3024 int FPDiff, SDLoc dl) const {
3025 // Adjust the Return address stack slot.
3026 EVT VT = getPointerTy(DAG.getDataLayout());
3027 OutRetAddr = getReturnAddressFrameIndex(DAG);
3029 // Load the "old" Return address.
3030 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3031 false, false, false, 0);
3032 return SDValue(OutRetAddr.getNode(), 1);
3035 /// Emit a store of the return address if tail call
3036 /// optimization is performed and it is required (FPDiff!=0).
3037 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3038 SDValue Chain, SDValue RetAddrFrIdx,
3039 EVT PtrVT, unsigned SlotSize,
3040 int FPDiff, SDLoc dl) {
3041 // Store the return address to the appropriate stack slot.
3042 if (!FPDiff) return Chain;
3043 // Calculate the new stack slot for the return address.
3044 int NewReturnAddrFI =
3045 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3047 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3048 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3049 MachinePointerInfo::getFixedStack(
3050 DAG.getMachineFunction(), NewReturnAddrFI),
3055 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3056 /// operation of specified width.
3057 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3059 unsigned NumElems = VT.getVectorNumElements();
3060 SmallVector<int, 8> Mask;
3061 Mask.push_back(NumElems);
3062 for (unsigned i = 1; i != NumElems; ++i)
3064 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3068 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3069 SmallVectorImpl<SDValue> &InVals) const {
3070 SelectionDAG &DAG = CLI.DAG;
3072 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3073 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3074 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3075 SDValue Chain = CLI.Chain;
3076 SDValue Callee = CLI.Callee;
3077 CallingConv::ID CallConv = CLI.CallConv;
3078 bool &isTailCall = CLI.IsTailCall;
3079 bool isVarArg = CLI.IsVarArg;
3081 MachineFunction &MF = DAG.getMachineFunction();
3082 bool Is64Bit = Subtarget->is64Bit();
3083 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3084 StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3085 bool IsSibcall = false;
3086 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3087 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3089 if (CallConv == CallingConv::X86_INTR)
3090 report_fatal_error("X86 interrupts may not be called directly");
3092 if (Attr.getValueAsString() == "true")
3095 if (Subtarget->isPICStyleGOT() &&
3096 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3097 // If we are using a GOT, disable tail calls to external symbols with
3098 // default visibility. Tail calling such a symbol requires using a GOT
3099 // relocation, which forces early binding of the symbol. This breaks code
3100 // that require lazy function symbol resolution. Using musttail or
3101 // GuaranteedTailCallOpt will override this.
3102 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3103 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3104 G->getGlobal()->hasDefaultVisibility()))
3108 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3110 // Force this to be a tail call. The verifier rules are enough to ensure
3111 // that we can lower this successfully without moving the return address
3114 } else if (isTailCall) {
3115 // Check if it's really possible to do a tail call.
3116 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3117 isVarArg, SR != NotStructReturn,
3118 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3119 Outs, OutVals, Ins, DAG);
3121 // Sibcalls are automatically detected tailcalls which do not require
3123 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3130 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3131 "Var args not supported with calling convention fastcc, ghc or hipe");
3133 // Analyze operands of the call, assigning locations to each operand.
3134 SmallVector<CCValAssign, 16> ArgLocs;
3135 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3137 // Allocate shadow area for Win64
3139 CCInfo.AllocateStack(32, 8);
3141 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3143 // Get a count of how many bytes are to be pushed on the stack.
3144 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3146 // This is a sibcall. The memory operands are available in caller's
3147 // own caller's stack.
3149 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3150 canGuaranteeTCO(CallConv))
3151 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3154 if (isTailCall && !IsSibcall && !IsMustTail) {
3155 // Lower arguments at fp - stackoffset + fpdiff.
3156 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3158 FPDiff = NumBytesCallerPushed - NumBytes;
3160 // Set the delta of movement of the returnaddr stackslot.
3161 // But only set if delta is greater than previous delta.
3162 if (FPDiff < X86Info->getTCReturnAddrDelta())
3163 X86Info->setTCReturnAddrDelta(FPDiff);
3166 unsigned NumBytesToPush = NumBytes;
3167 unsigned NumBytesToPop = NumBytes;
3169 // If we have an inalloca argument, all stack space has already been allocated
3170 // for us and be right at the top of the stack. We don't support multiple
3171 // arguments passed in memory when using inalloca.
3172 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3174 if (!ArgLocs.back().isMemLoc())
3175 report_fatal_error("cannot use inalloca attribute on a register "
3177 if (ArgLocs.back().getLocMemOffset() != 0)
3178 report_fatal_error("any parameter with the inalloca attribute must be "
3179 "the only memory argument");
3183 Chain = DAG.getCALLSEQ_START(
3184 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3186 SDValue RetAddrFrIdx;
3187 // Load return address for tail calls.
3188 if (isTailCall && FPDiff)
3189 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3190 Is64Bit, FPDiff, dl);
3192 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3193 SmallVector<SDValue, 8> MemOpChains;
3196 // Walk the register/memloc assignments, inserting copies/loads. In the case
3197 // of tail call optimization arguments are handle later.
3198 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3199 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3200 // Skip inalloca arguments, they have already been written.
3201 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3202 if (Flags.isInAlloca())
3205 CCValAssign &VA = ArgLocs[i];
3206 EVT RegVT = VA.getLocVT();
3207 SDValue Arg = OutVals[i];
3208 bool isByVal = Flags.isByVal();
3210 // Promote the value if needed.
3211 switch (VA.getLocInfo()) {
3212 default: llvm_unreachable("Unknown loc info!");
3213 case CCValAssign::Full: break;
3214 case CCValAssign::SExt:
3215 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3217 case CCValAssign::ZExt:
3218 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3220 case CCValAssign::AExt:
3221 if (Arg.getValueType().isVector() &&
3222 Arg.getValueType().getVectorElementType() == MVT::i1)
3223 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3224 else if (RegVT.is128BitVector()) {
3225 // Special case: passing MMX values in XMM registers.
3226 Arg = DAG.getBitcast(MVT::i64, Arg);
3227 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3228 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3230 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3232 case CCValAssign::BCvt:
3233 Arg = DAG.getBitcast(RegVT, Arg);
3235 case CCValAssign::Indirect: {
3236 // Store the argument.
3237 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3238 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3239 Chain = DAG.getStore(
3240 Chain, dl, Arg, SpillSlot,
3241 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3248 if (VA.isRegLoc()) {
3249 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3250 if (isVarArg && IsWin64) {
3251 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3252 // shadow reg if callee is a varargs function.
3253 unsigned ShadowReg = 0;
3254 switch (VA.getLocReg()) {
3255 case X86::XMM0: ShadowReg = X86::RCX; break;
3256 case X86::XMM1: ShadowReg = X86::RDX; break;
3257 case X86::XMM2: ShadowReg = X86::R8; break;
3258 case X86::XMM3: ShadowReg = X86::R9; break;
3261 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3263 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3264 assert(VA.isMemLoc());
3265 if (!StackPtr.getNode())
3266 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3267 getPointerTy(DAG.getDataLayout()));
3268 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3269 dl, DAG, VA, Flags));
3273 if (!MemOpChains.empty())
3274 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3276 if (Subtarget->isPICStyleGOT()) {
3277 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3280 RegsToPass.push_back(std::make_pair(
3281 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3282 getPointerTy(DAG.getDataLayout()))));
3284 // If we are tail calling and generating PIC/GOT style code load the
3285 // address of the callee into ECX. The value in ecx is used as target of
3286 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3287 // for tail calls on PIC/GOT architectures. Normally we would just put the
3288 // address of GOT into ebx and then call target@PLT. But for tail calls
3289 // ebx would be restored (since ebx is callee saved) before jumping to the
3292 // Note: The actual moving to ECX is done further down.
3293 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3294 if (G && !G->getGlobal()->hasLocalLinkage() &&
3295 G->getGlobal()->hasDefaultVisibility())
3296 Callee = LowerGlobalAddress(Callee, DAG);
3297 else if (isa<ExternalSymbolSDNode>(Callee))
3298 Callee = LowerExternalSymbol(Callee, DAG);
3302 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3303 // From AMD64 ABI document:
3304 // For calls that may call functions that use varargs or stdargs
3305 // (prototype-less calls or calls to functions containing ellipsis (...) in
3306 // the declaration) %al is used as hidden argument to specify the number
3307 // of SSE registers used. The contents of %al do not need to match exactly
3308 // the number of registers, but must be an ubound on the number of SSE
3309 // registers used and is in the range 0 - 8 inclusive.
3311 // Count the number of XMM registers allocated.
3312 static const MCPhysReg XMMArgRegs[] = {
3313 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3314 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3316 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3317 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3318 && "SSE registers cannot be used when SSE is disabled");
3320 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3321 DAG.getConstant(NumXMMRegs, dl,
3325 if (isVarArg && IsMustTail) {
3326 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3327 for (const auto &F : Forwards) {
3328 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3329 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3333 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3334 // don't need this because the eligibility check rejects calls that require
3335 // shuffling arguments passed in memory.
3336 if (!IsSibcall && isTailCall) {
3337 // Force all the incoming stack arguments to be loaded from the stack
3338 // before any new outgoing arguments are stored to the stack, because the
3339 // outgoing stack slots may alias the incoming argument stack slots, and
3340 // the alias isn't otherwise explicit. This is slightly more conservative
3341 // than necessary, because it means that each store effectively depends
3342 // on every argument instead of just those arguments it would clobber.
3343 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3345 SmallVector<SDValue, 8> MemOpChains2;
3348 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3349 CCValAssign &VA = ArgLocs[i];
3352 assert(VA.isMemLoc());
3353 SDValue Arg = OutVals[i];
3354 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3355 // Skip inalloca arguments. They don't require any work.
3356 if (Flags.isInAlloca())
3358 // Create frame index.
3359 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3360 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3361 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3362 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3364 if (Flags.isByVal()) {
3365 // Copy relative to framepointer.
3366 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3367 if (!StackPtr.getNode())
3368 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3369 getPointerTy(DAG.getDataLayout()));
3370 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3373 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3377 // Store relative to framepointer.
3378 MemOpChains2.push_back(DAG.getStore(
3379 ArgChain, dl, Arg, FIN,
3380 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3385 if (!MemOpChains2.empty())
3386 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3388 // Store the return address to the appropriate stack slot.
3389 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3390 getPointerTy(DAG.getDataLayout()),
3391 RegInfo->getSlotSize(), FPDiff, dl);
3394 // Build a sequence of copy-to-reg nodes chained together with token chain
3395 // and flag operands which copy the outgoing args into registers.
3397 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3398 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3399 RegsToPass[i].second, InFlag);
3400 InFlag = Chain.getValue(1);
3403 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3404 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3405 // In the 64-bit large code model, we have to make all calls
3406 // through a register, since the call instruction's 32-bit
3407 // pc-relative offset may not be large enough to hold the whole
3409 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3410 // If the callee is a GlobalAddress node (quite common, every direct call
3411 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3413 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3415 // We should use extra load for direct calls to dllimported functions in
3417 const GlobalValue *GV = G->getGlobal();
3418 if (!GV->hasDLLImportStorageClass()) {
3419 unsigned char OpFlags = 0;
3420 bool ExtraLoad = false;
3421 unsigned WrapperKind = ISD::DELETED_NODE;
3423 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3424 // external symbols most go through the PLT in PIC mode. If the symbol
3425 // has hidden or protected visibility, or if it is static or local, then
3426 // we don't need to use the PLT - we can directly call it.
3427 if (Subtarget->isTargetELF() &&
3428 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3429 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3430 OpFlags = X86II::MO_PLT;
3431 } else if (Subtarget->isPICStyleStubAny() &&
3432 !GV->isStrongDefinitionForLinker() &&
3433 (!Subtarget->getTargetTriple().isMacOSX() ||
3434 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3435 // PC-relative references to external symbols should go through $stub,
3436 // unless we're building with the leopard linker or later, which
3437 // automatically synthesizes these stubs.
3438 OpFlags = X86II::MO_DARWIN_STUB;
3439 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3440 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3441 // If the function is marked as non-lazy, generate an indirect call
3442 // which loads from the GOT directly. This avoids runtime overhead
3443 // at the cost of eager binding (and one extra byte of encoding).
3444 OpFlags = X86II::MO_GOTPCREL;
3445 WrapperKind = X86ISD::WrapperRIP;
3449 Callee = DAG.getTargetGlobalAddress(
3450 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3452 // Add a wrapper if needed.
3453 if (WrapperKind != ISD::DELETED_NODE)
3454 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3455 getPointerTy(DAG.getDataLayout()), Callee);
3456 // Add extra indirection if needed.
3458 Callee = DAG.getLoad(
3459 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3460 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3463 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3464 unsigned char OpFlags = 0;
3466 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3467 // external symbols should go through the PLT.
3468 if (Subtarget->isTargetELF() &&
3469 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3470 OpFlags = X86II::MO_PLT;
3471 } else if (Subtarget->isPICStyleStubAny() &&
3472 (!Subtarget->getTargetTriple().isMacOSX() ||
3473 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3474 // PC-relative references to external symbols should go through $stub,
3475 // unless we're building with the leopard linker or later, which
3476 // automatically synthesizes these stubs.
3477 OpFlags = X86II::MO_DARWIN_STUB;
3480 Callee = DAG.getTargetExternalSymbol(
3481 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3482 } else if (Subtarget->isTarget64BitILP32() &&
3483 Callee->getValueType(0) == MVT::i32) {
3484 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3485 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3488 // Returns a chain & a flag for retval copy to use.
3489 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3490 SmallVector<SDValue, 8> Ops;
3492 if (!IsSibcall && isTailCall) {
3493 Chain = DAG.getCALLSEQ_END(Chain,
3494 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3495 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3496 InFlag = Chain.getValue(1);
3499 Ops.push_back(Chain);
3500 Ops.push_back(Callee);
3503 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3505 // Add argument registers to the end of the list so that they are known live
3507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3508 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3509 RegsToPass[i].second.getValueType()));
3511 // Add a register mask operand representing the call-preserved registers.
3512 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3513 assert(Mask && "Missing call preserved mask for calling convention");
3515 // If this is an invoke in a 32-bit function using a funclet-based
3516 // personality, assume the function clobbers all registers. If an exception
3517 // is thrown, the runtime will not restore CSRs.
3518 // FIXME: Model this more precisely so that we can register allocate across
3519 // the normal edge and spill and fill across the exceptional edge.
3520 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3521 const Function *CallerFn = MF.getFunction();
3522 EHPersonality Pers =
3523 CallerFn->hasPersonalityFn()
3524 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3525 : EHPersonality::Unknown;
3526 if (isFuncletEHPersonality(Pers))
3527 Mask = RegInfo->getNoPreservedMask();
3530 Ops.push_back(DAG.getRegisterMask(Mask));
3532 if (InFlag.getNode())
3533 Ops.push_back(InFlag);
3537 //// If this is the first return lowered for this function, add the regs
3538 //// to the liveout set for the function.
3539 // This isn't right, although it's probably harmless on x86; liveouts
3540 // should be computed from returns not tail calls. Consider a void
3541 // function making a tail call to a function returning int.
3542 MF.getFrameInfo()->setHasTailCall();
3543 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3546 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3547 InFlag = Chain.getValue(1);
3549 // Create the CALLSEQ_END node.
3550 unsigned NumBytesForCalleeToPop;
3551 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3552 DAG.getTarget().Options.GuaranteedTailCallOpt))
3553 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3554 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3555 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3556 SR == StackStructReturn)
3557 // If this is a call to a struct-return function, the callee
3558 // pops the hidden struct pointer, so we have to push it back.
3559 // This is common for Darwin/X86, Linux & Mingw32 targets.
3560 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3561 NumBytesForCalleeToPop = 4;
3563 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3565 // Returns a flag for retval copy to use.
3567 Chain = DAG.getCALLSEQ_END(Chain,
3568 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3569 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3572 InFlag = Chain.getValue(1);
3575 // Handle result values, copying them out of physregs into vregs that we
3577 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3578 Ins, dl, DAG, InVals);
3581 //===----------------------------------------------------------------------===//
3582 // Fast Calling Convention (tail call) implementation
3583 //===----------------------------------------------------------------------===//
3585 // Like std call, callee cleans arguments, convention except that ECX is
3586 // reserved for storing the tail called function address. Only 2 registers are
3587 // free for argument passing (inreg). Tail call optimization is performed
3589 // * tailcallopt is enabled
3590 // * caller/callee are fastcc
3591 // On X86_64 architecture with GOT-style position independent code only local
3592 // (within module) calls are supported at the moment.
3593 // To keep the stack aligned according to platform abi the function
3594 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3595 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3596 // If a tail called function callee has more arguments than the caller the
3597 // caller needs to make sure that there is room to move the RETADDR to. This is
3598 // achieved by reserving an area the size of the argument delta right after the
3599 // original RETADDR, but before the saved framepointer or the spilled registers
3600 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3612 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3615 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3616 SelectionDAG& DAG) const {
3617 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3618 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3619 unsigned StackAlignment = TFI.getStackAlignment();
3620 uint64_t AlignMask = StackAlignment - 1;
3621 int64_t Offset = StackSize;
3622 unsigned SlotSize = RegInfo->getSlotSize();
3623 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3624 // Number smaller than 12 so just add the difference.
3625 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3627 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3628 Offset = ((~AlignMask) & Offset) + StackAlignment +
3629 (StackAlignment-SlotSize);
3634 /// Return true if the given stack call argument is already available in the
3635 /// same position (relatively) of the caller's incoming argument stack.
3637 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3638 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3639 const X86InstrInfo *TII) {
3640 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3642 if (Arg.getOpcode() == ISD::CopyFromReg) {
3643 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3644 if (!TargetRegisterInfo::isVirtualRegister(VR))
3646 MachineInstr *Def = MRI->getVRegDef(VR);
3649 if (!Flags.isByVal()) {
3650 if (!TII->isLoadFromStackSlot(Def, FI))
3653 unsigned Opcode = Def->getOpcode();
3654 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3655 Opcode == X86::LEA64_32r) &&
3656 Def->getOperand(1).isFI()) {
3657 FI = Def->getOperand(1).getIndex();
3658 Bytes = Flags.getByValSize();
3662 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3663 if (Flags.isByVal())
3664 // ByVal argument is passed in as a pointer but it's now being
3665 // dereferenced. e.g.
3666 // define @foo(%struct.X* %A) {
3667 // tail call @bar(%struct.X* byval %A)
3670 SDValue Ptr = Ld->getBasePtr();
3671 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3674 FI = FINode->getIndex();
3675 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3676 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3677 FI = FINode->getIndex();
3678 Bytes = Flags.getByValSize();
3682 assert(FI != INT_MAX);
3683 if (!MFI->isFixedObjectIndex(FI))
3685 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3688 /// Check whether the call is eligible for tail call optimization. Targets
3689 /// that want to do tail call optimization should implement this function.
3690 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3691 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3692 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3693 const SmallVectorImpl<ISD::OutputArg> &Outs,
3694 const SmallVectorImpl<SDValue> &OutVals,
3695 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3696 if (!mayTailCallThisCC(CalleeCC))
3699 // If -tailcallopt is specified, make fastcc functions tail-callable.
3700 MachineFunction &MF = DAG.getMachineFunction();
3701 const Function *CallerF = MF.getFunction();
3703 // If the function return type is x86_fp80 and the callee return type is not,
3704 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3705 // perform a tailcall optimization here.
3706 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3709 CallingConv::ID CallerCC = CallerF->getCallingConv();
3710 bool CCMatch = CallerCC == CalleeCC;
3711 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3712 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3714 // Win64 functions have extra shadow space for argument homing. Don't do the
3715 // sibcall if the caller and callee have mismatched expectations for this
3717 if (IsCalleeWin64 != IsCallerWin64)
3720 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3721 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3726 // Look for obvious safe cases to perform tail call optimization that do not
3727 // require ABI changes. This is what gcc calls sibcall.
3729 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3730 // emit a special epilogue.
3731 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3732 if (RegInfo->needsStackRealignment(MF))
3735 // Also avoid sibcall optimization if either caller or callee uses struct
3736 // return semantics.
3737 if (isCalleeStructRet || isCallerStructRet)
3740 // Do not sibcall optimize vararg calls unless all arguments are passed via
3742 if (isVarArg && !Outs.empty()) {
3743 // Optimizing for varargs on Win64 is unlikely to be safe without
3744 // additional testing.
3745 if (IsCalleeWin64 || IsCallerWin64)
3748 SmallVector<CCValAssign, 16> ArgLocs;
3749 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3752 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3753 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3754 if (!ArgLocs[i].isRegLoc())
3758 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3759 // stack. Therefore, if it's not used by the call it is not safe to optimize
3760 // this into a sibcall.
3761 bool Unused = false;
3762 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3769 SmallVector<CCValAssign, 16> RVLocs;
3770 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3772 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3773 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3774 CCValAssign &VA = RVLocs[i];
3775 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3780 // If the calling conventions do not match, then we'd better make sure the
3781 // results are returned in the same way as what the caller expects.
3783 SmallVector<CCValAssign, 16> RVLocs1;
3784 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3786 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3788 SmallVector<CCValAssign, 16> RVLocs2;
3789 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3791 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3793 if (RVLocs1.size() != RVLocs2.size())
3795 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3796 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3798 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3800 if (RVLocs1[i].isRegLoc()) {
3801 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3804 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3810 unsigned StackArgsSize = 0;
3812 // If the callee takes no arguments then go on to check the results of the
3814 if (!Outs.empty()) {
3815 // Check if stack adjustment is needed. For now, do not do this if any
3816 // argument is passed on the stack.
3817 SmallVector<CCValAssign, 16> ArgLocs;
3818 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3821 // Allocate shadow area for Win64
3823 CCInfo.AllocateStack(32, 8);
3825 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3826 StackArgsSize = CCInfo.getNextStackOffset();
3828 if (CCInfo.getNextStackOffset()) {
3829 // Check if the arguments are already laid out in the right way as
3830 // the caller's fixed stack objects.
3831 MachineFrameInfo *MFI = MF.getFrameInfo();
3832 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3833 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3834 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3835 CCValAssign &VA = ArgLocs[i];
3836 SDValue Arg = OutVals[i];
3837 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3838 if (VA.getLocInfo() == CCValAssign::Indirect)
3840 if (!VA.isRegLoc()) {
3841 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3848 // If the tailcall address may be in a register, then make sure it's
3849 // possible to register allocate for it. In 32-bit, the call address can
3850 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3851 // callee-saved registers are restored. These happen to be the same
3852 // registers used to pass 'inreg' arguments so watch out for those.
3853 if (!Subtarget->is64Bit() &&
3854 ((!isa<GlobalAddressSDNode>(Callee) &&
3855 !isa<ExternalSymbolSDNode>(Callee)) ||
3856 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3857 unsigned NumInRegs = 0;
3858 // In PIC we need an extra register to formulate the address computation
3860 unsigned MaxInRegs =
3861 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3864 CCValAssign &VA = ArgLocs[i];
3867 unsigned Reg = VA.getLocReg();
3870 case X86::EAX: case X86::EDX: case X86::ECX:
3871 if (++NumInRegs == MaxInRegs)
3879 bool CalleeWillPop =
3880 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3881 MF.getTarget().Options.GuaranteedTailCallOpt);
3883 if (unsigned BytesToPop =
3884 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3885 // If we have bytes to pop, the callee must pop them.
3886 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3887 if (!CalleePopMatches)
3889 } else if (CalleeWillPop && StackArgsSize > 0) {
3890 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3898 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3899 const TargetLibraryInfo *libInfo) const {
3900 return X86::createFastISel(funcInfo, libInfo);
3903 //===----------------------------------------------------------------------===//
3904 // Other Lowering Hooks
3905 //===----------------------------------------------------------------------===//
3907 static bool MayFoldLoad(SDValue Op) {
3908 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3911 static bool MayFoldIntoStore(SDValue Op) {
3912 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3915 static bool isTargetShuffle(unsigned Opcode) {
3917 default: return false;
3918 case X86ISD::BLENDI:
3919 case X86ISD::PSHUFB:
3920 case X86ISD::PSHUFD:
3921 case X86ISD::PSHUFHW:
3922 case X86ISD::PSHUFLW:
3924 case X86ISD::INSERTPS:
3925 case X86ISD::PALIGNR:
3926 case X86ISD::MOVLHPS:
3927 case X86ISD::MOVLHPD:
3928 case X86ISD::MOVHLPS:
3929 case X86ISD::MOVLPS:
3930 case X86ISD::MOVLPD:
3931 case X86ISD::MOVSHDUP:
3932 case X86ISD::MOVSLDUP:
3933 case X86ISD::MOVDDUP:
3936 case X86ISD::UNPCKL:
3937 case X86ISD::UNPCKH:
3938 case X86ISD::VPERMILPI:
3939 case X86ISD::VPERM2X128:
3940 case X86ISD::VPERMI:
3941 case X86ISD::VPERMV:
3942 case X86ISD::VPERMV3:
3947 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3948 SDValue V1, unsigned TargetMask,
3949 SelectionDAG &DAG) {
3951 default: llvm_unreachable("Unknown x86 shuffle node");
3952 case X86ISD::PSHUFD:
3953 case X86ISD::PSHUFHW:
3954 case X86ISD::PSHUFLW:
3955 case X86ISD::VPERMILPI:
3956 case X86ISD::VPERMI:
3957 return DAG.getNode(Opc, dl, VT, V1,
3958 DAG.getConstant(TargetMask, dl, MVT::i8));
3962 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3963 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3965 default: llvm_unreachable("Unknown x86 shuffle node");
3966 case X86ISD::MOVLHPS:
3967 case X86ISD::MOVLHPD:
3968 case X86ISD::MOVHLPS:
3969 case X86ISD::MOVLPS:
3970 case X86ISD::MOVLPD:
3973 case X86ISD::UNPCKL:
3974 case X86ISD::UNPCKH:
3975 return DAG.getNode(Opc, dl, VT, V1, V2);
3979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3980 MachineFunction &MF = DAG.getMachineFunction();
3981 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3982 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3983 int ReturnAddrIndex = FuncInfo->getRAIndex();
3985 if (ReturnAddrIndex == 0) {
3986 // Set up a frame object for the return address.
3987 unsigned SlotSize = RegInfo->getSlotSize();
3988 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3991 FuncInfo->setRAIndex(ReturnAddrIndex);
3994 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3997 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3998 bool hasSymbolicDisplacement) {
3999 // Offset should fit into 32 bit immediate field.
4000 if (!isInt<32>(Offset))
4003 // If we don't have a symbolic displacement - we don't have any extra
4005 if (!hasSymbolicDisplacement)
4008 // FIXME: Some tweaks might be needed for medium code model.
4009 if (M != CodeModel::Small && M != CodeModel::Kernel)
4012 // For small code model we assume that latest object is 16MB before end of 31
4013 // bits boundary. We may also accept pretty large negative constants knowing
4014 // that all objects are in the positive half of address space.
4015 if (M == CodeModel::Small && Offset < 16*1024*1024)
4018 // For kernel code model we know that all object resist in the negative half
4019 // of 32bits address space. We may not accept negative offsets, since they may
4020 // be just off and we may accept pretty large positive ones.
4021 if (M == CodeModel::Kernel && Offset >= 0)
4027 /// Determines whether the callee is required to pop its own arguments.
4028 /// Callee pop is necessary to support tail calls.
4029 bool X86::isCalleePop(CallingConv::ID CallingConv,
4030 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4031 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4032 // can guarantee TCO.
4033 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4036 switch (CallingConv) {
4039 case CallingConv::X86_StdCall:
4040 case CallingConv::X86_FastCall:
4041 case CallingConv::X86_ThisCall:
4042 case CallingConv::X86_VectorCall:
4047 /// \brief Return true if the condition is an unsigned comparison operation.
4048 static bool isX86CCUnsigned(unsigned X86CC) {
4050 default: llvm_unreachable("Invalid integer condition!");
4051 case X86::COND_E: return true;
4052 case X86::COND_G: return false;
4053 case X86::COND_GE: return false;
4054 case X86::COND_L: return false;
4055 case X86::COND_LE: return false;
4056 case X86::COND_NE: return true;
4057 case X86::COND_B: return true;
4058 case X86::COND_A: return true;
4059 case X86::COND_BE: return true;
4060 case X86::COND_AE: return true;
4064 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4065 switch (SetCCOpcode) {
4066 default: llvm_unreachable("Invalid integer condition!");
4067 case ISD::SETEQ: return X86::COND_E;
4068 case ISD::SETGT: return X86::COND_G;
4069 case ISD::SETGE: return X86::COND_GE;
4070 case ISD::SETLT: return X86::COND_L;
4071 case ISD::SETLE: return X86::COND_LE;
4072 case ISD::SETNE: return X86::COND_NE;
4073 case ISD::SETULT: return X86::COND_B;
4074 case ISD::SETUGT: return X86::COND_A;
4075 case ISD::SETULE: return X86::COND_BE;
4076 case ISD::SETUGE: return X86::COND_AE;
4080 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4081 /// condition code, returning the condition code and the LHS/RHS of the
4082 /// comparison to make.
4083 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4084 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4086 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4087 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4088 // X > -1 -> X == 0, jump !sign.
4089 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4090 return X86::COND_NS;
4092 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4093 // X < 0 -> X == 0, jump on sign.
4096 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4098 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4099 return X86::COND_LE;
4103 return TranslateIntegerX86CC(SetCCOpcode);
4106 // First determine if it is required or is profitable to flip the operands.
4108 // If LHS is a foldable load, but RHS is not, flip the condition.
4109 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4110 !ISD::isNON_EXTLoad(RHS.getNode())) {
4111 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4112 std::swap(LHS, RHS);
4115 switch (SetCCOpcode) {
4121 std::swap(LHS, RHS);
4125 // On a floating point condition, the flags are set as follows:
4127 // 0 | 0 | 0 | X > Y
4128 // 0 | 0 | 1 | X < Y
4129 // 1 | 0 | 0 | X == Y
4130 // 1 | 1 | 1 | unordered
4131 switch (SetCCOpcode) {
4132 default: llvm_unreachable("Condcode should be pre-legalized away");
4134 case ISD::SETEQ: return X86::COND_E;
4135 case ISD::SETOLT: // flipped
4137 case ISD::SETGT: return X86::COND_A;
4138 case ISD::SETOLE: // flipped
4140 case ISD::SETGE: return X86::COND_AE;
4141 case ISD::SETUGT: // flipped
4143 case ISD::SETLT: return X86::COND_B;
4144 case ISD::SETUGE: // flipped
4146 case ISD::SETLE: return X86::COND_BE;
4148 case ISD::SETNE: return X86::COND_NE;
4149 case ISD::SETUO: return X86::COND_P;
4150 case ISD::SETO: return X86::COND_NP;
4152 case ISD::SETUNE: return X86::COND_INVALID;
4156 /// Is there a floating point cmov for the specific X86 condition code?
4157 /// Current x86 isa includes the following FP cmov instructions:
4158 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4159 static bool hasFPCMov(unsigned X86CC) {
4176 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4178 unsigned Intrinsic) const {
4180 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4184 switch (IntrData->Type) {
4187 Info.opc = ISD::INTRINSIC_W_CHAIN;
4188 Info.memVT = MVT::getVT(I.getType());
4189 Info.ptrVal = I.getArgOperand(0);
4191 Info.align = (IntrData->Type == LOADA ? Info.memVT.getSizeInBits()/8 : 1);
4193 Info.readMem = true;
4194 Info.writeMem = false;
4204 /// Returns true if the target can instruction select the
4205 /// specified FP immediate natively. If false, the legalizer will
4206 /// materialize the FP immediate as a load from a constant pool.
4207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4208 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4209 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4215 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4216 ISD::LoadExtType ExtTy,
4218 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4219 // relocation target a movq or addq instruction: don't let the load shrink.
4220 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4221 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4222 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4223 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4227 /// \brief Returns true if it is beneficial to convert a load of a constant
4228 /// to just the constant itself.
4229 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4231 assert(Ty->isIntegerTy());
4233 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4234 if (BitSize == 0 || BitSize > 64)
4239 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4240 unsigned Index) const {
4241 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4244 return (Index == 0 || Index == ResVT.getVectorNumElements());
4247 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4248 // Speculate cttz only if we can directly use TZCNT.
4249 return Subtarget->hasBMI();
4252 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4253 // Speculate ctlz only if we can directly use LZCNT.
4254 return Subtarget->hasLZCNT();
4257 /// Return true if every element in Mask, beginning
4258 /// from position Pos and ending in Pos+Size is undef.
4259 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4260 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4266 /// Return true if Val is undef or if its value falls within the
4267 /// specified range (L, H].
4268 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4269 return (Val < 0) || (Val >= Low && Val < Hi);
4272 /// Val is either less than zero (undef) or equal to the specified value.
4273 static bool isUndefOrEqual(int Val, int CmpVal) {
4274 return (Val < 0 || Val == CmpVal);
4277 /// Return true if every element in Mask, beginning
4278 /// from position Pos and ending in Pos+Size, falls within the specified
4279 /// sequential range (Low, Low+Size]. or is undef.
4280 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4281 unsigned Pos, unsigned Size, int Low) {
4282 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4283 if (!isUndefOrEqual(Mask[i], Low))
4288 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4289 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4290 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4291 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4292 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4295 // The index should be aligned on a vecWidth-bit boundary.
4297 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4299 MVT VT = N->getSimpleValueType(0);
4300 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4301 bool Result = (Index * ElSize) % vecWidth == 0;
4306 /// Return true if the specified INSERT_SUBVECTOR
4307 /// operand specifies a subvector insert that is suitable for input to
4308 /// insertion of 128 or 256-bit subvectors
4309 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4310 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4311 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4313 // The index should be aligned on a vecWidth-bit boundary.
4315 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4317 MVT VT = N->getSimpleValueType(0);
4318 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4319 bool Result = (Index * ElSize) % vecWidth == 0;
4324 bool X86::isVINSERT128Index(SDNode *N) {
4325 return isVINSERTIndex(N, 128);
4328 bool X86::isVINSERT256Index(SDNode *N) {
4329 return isVINSERTIndex(N, 256);
4332 bool X86::isVEXTRACT128Index(SDNode *N) {
4333 return isVEXTRACTIndex(N, 128);
4336 bool X86::isVEXTRACT256Index(SDNode *N) {
4337 return isVEXTRACTIndex(N, 256);
4340 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4341 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4342 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4343 "Illegal extract subvector for VEXTRACT");
4346 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4348 MVT VecVT = N->getOperand(0).getSimpleValueType();
4349 MVT ElVT = VecVT.getVectorElementType();
4351 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4352 return Index / NumElemsPerChunk;
4355 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4356 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4357 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4358 "Illegal insert subvector for VINSERT");
4361 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4363 MVT VecVT = N->getSimpleValueType(0);
4364 MVT ElVT = VecVT.getVectorElementType();
4366 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4367 return Index / NumElemsPerChunk;
4370 /// Return the appropriate immediate to extract the specified
4371 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4372 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4373 return getExtractVEXTRACTImmediate(N, 128);
4376 /// Return the appropriate immediate to extract the specified
4377 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4378 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4379 return getExtractVEXTRACTImmediate(N, 256);
4382 /// Return the appropriate immediate to insert at the specified
4383 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4384 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4385 return getInsertVINSERTImmediate(N, 128);
4388 /// Return the appropriate immediate to insert at the specified
4389 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4390 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4391 return getInsertVINSERTImmediate(N, 256);
4394 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4395 bool X86::isZeroNode(SDValue Elt) {
4396 return isNullConstant(Elt) || isNullFPConstant(Elt);
4399 // Build a vector of constants
4400 // Use an UNDEF node if MaskElt == -1.
4401 // Spilt 64-bit constants in the 32-bit mode.
4402 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4404 SDLoc dl, bool IsMask = false) {
4406 SmallVector<SDValue, 32> Ops;
4409 MVT ConstVecVT = VT;
4410 unsigned NumElts = VT.getVectorNumElements();
4411 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4412 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4413 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4417 MVT EltVT = ConstVecVT.getVectorElementType();
4418 for (unsigned i = 0; i < NumElts; ++i) {
4419 bool IsUndef = Values[i] < 0 && IsMask;
4420 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4421 DAG.getConstant(Values[i], dl, EltVT);
4422 Ops.push_back(OpNode);
4424 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4425 DAG.getConstant(0, dl, EltVT));
4427 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4429 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4433 /// Returns a vector of specified type with all zero elements.
4434 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4435 SelectionDAG &DAG, SDLoc dl) {
4436 assert(VT.isVector() && "Expected a vector type");
4438 // Always build SSE zero vectors as <4 x i32> bitcasted
4439 // to their dest type. This ensures they get CSE'd.
4441 if (VT.is128BitVector()) { // SSE
4442 if (Subtarget->hasSSE2()) { // SSE2
4443 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4444 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4446 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4447 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4449 } else if (VT.is256BitVector()) { // AVX
4450 if (Subtarget->hasInt256()) { // AVX2
4451 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4452 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4453 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4455 // 256-bit logic and arithmetic instructions in AVX are all
4456 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4457 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4458 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4459 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4461 } else if (VT.is512BitVector()) { // AVX-512
4462 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4463 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4464 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4465 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4466 } else if (VT.getVectorElementType() == MVT::i1) {
4468 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4469 && "Unexpected vector type");
4470 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4471 && "Unexpected vector type");
4472 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4473 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4474 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4476 llvm_unreachable("Unexpected vector type");
4478 return DAG.getBitcast(VT, Vec);
4481 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4482 SelectionDAG &DAG, SDLoc dl,
4483 unsigned vectorWidth) {
4484 assert((vectorWidth == 128 || vectorWidth == 256) &&
4485 "Unsupported vector width");
4486 EVT VT = Vec.getValueType();
4487 EVT ElVT = VT.getVectorElementType();
4488 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4489 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4490 VT.getVectorNumElements()/Factor);
4492 // Extract from UNDEF is UNDEF.
4493 if (Vec.getOpcode() == ISD::UNDEF)
4494 return DAG.getUNDEF(ResultVT);
4496 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4497 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4498 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4500 // This is the index of the first element of the vectorWidth-bit chunk
4501 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4502 IdxVal &= ~(ElemsPerChunk - 1);
4504 // If the input is a buildvector just emit a smaller one.
4505 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4506 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4507 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4509 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4510 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4513 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4514 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4515 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4516 /// instructions or a simple subregister reference. Idx is an index in the
4517 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4518 /// lowering EXTRACT_VECTOR_ELT operations easier.
4519 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4520 SelectionDAG &DAG, SDLoc dl) {
4521 assert((Vec.getValueType().is256BitVector() ||
4522 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4523 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4526 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4527 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4528 SelectionDAG &DAG, SDLoc dl) {
4529 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4530 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4533 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4534 unsigned IdxVal, SelectionDAG &DAG,
4535 SDLoc dl, unsigned vectorWidth) {
4536 assert((vectorWidth == 128 || vectorWidth == 256) &&
4537 "Unsupported vector width");
4538 // Inserting UNDEF is Result
4539 if (Vec.getOpcode() == ISD::UNDEF)
4541 EVT VT = Vec.getValueType();
4542 EVT ElVT = VT.getVectorElementType();
4543 EVT ResultVT = Result.getValueType();
4545 // Insert the relevant vectorWidth bits.
4546 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4547 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4549 // This is the index of the first element of the vectorWidth-bit chunk
4550 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4551 IdxVal &= ~(ElemsPerChunk - 1);
4553 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4554 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4557 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4558 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4559 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4560 /// simple superregister reference. Idx is an index in the 128 bits
4561 /// we want. It need not be aligned to a 128-bit boundary. That makes
4562 /// lowering INSERT_VECTOR_ELT operations easier.
4563 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4564 SelectionDAG &DAG, SDLoc dl) {
4565 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4567 // For insertion into the zero index (low half) of a 256-bit vector, it is
4568 // more efficient to generate a blend with immediate instead of an insert*128.
4569 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4570 // extend the subvector to the size of the result vector. Make sure that
4571 // we are not recursing on that node by checking for undef here.
4572 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4573 Result.getOpcode() != ISD::UNDEF) {
4574 EVT ResultVT = Result.getValueType();
4575 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4576 SDValue Undef = DAG.getUNDEF(ResultVT);
4577 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4580 // The blend instruction, and therefore its mask, depend on the data type.
4581 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4582 if (ScalarType.isFloatingPoint()) {
4583 // Choose either vblendps (float) or vblendpd (double).
4584 unsigned ScalarSize = ScalarType.getSizeInBits();
4585 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4586 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4587 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4588 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4591 const X86Subtarget &Subtarget =
4592 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4594 // AVX2 is needed for 256-bit integer blend support.
4595 // Integers must be cast to 32-bit because there is only vpblendd;
4596 // vpblendw can't be used for this because it has a handicapped mask.
4598 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4599 // is still more efficient than using the wrong domain vinsertf128 that
4600 // will be created by InsertSubVector().
4601 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4603 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4604 Result = DAG.getBitcast(CastVT, Result);
4605 Vec256 = DAG.getBitcast(CastVT, Vec256);
4606 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4607 return DAG.getBitcast(ResultVT, Vec256);
4610 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4613 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4614 SelectionDAG &DAG, SDLoc dl) {
4615 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4616 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4619 /// Insert i1-subvector to i1-vector.
4620 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4623 SDValue Vec = Op.getOperand(0);
4624 SDValue SubVec = Op.getOperand(1);
4625 SDValue Idx = Op.getOperand(2);
4627 if (!isa<ConstantSDNode>(Idx))
4630 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4631 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4634 MVT OpVT = Op.getSimpleValueType();
4635 MVT SubVecVT = SubVec.getSimpleValueType();
4636 unsigned NumElems = OpVT.getVectorNumElements();
4637 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4639 assert(IdxVal + SubVecNumElems <= NumElems &&
4640 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4641 "Unexpected index value in INSERT_SUBVECTOR");
4643 // There are 3 possible cases:
4644 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4645 // 2. Subvector should be inserted in the upper part
4646 // (IdxVal + SubVecNumElems == NumElems)
4647 // 3. Subvector should be inserted in the middle (for example v2i1
4648 // to v16i1, index 2)
4650 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4651 SDValue Undef = DAG.getUNDEF(OpVT);
4652 SDValue WideSubVec =
4653 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4655 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4656 DAG.getConstant(IdxVal, dl, MVT::i8));
4658 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4659 unsigned ShiftLeft = NumElems - SubVecNumElems;
4660 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4661 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4662 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4663 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4664 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4668 // Zero lower bits of the Vec
4669 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4670 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4671 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4672 // Merge them together
4673 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4676 // Simple case when we put subvector in the upper part
4677 if (IdxVal + SubVecNumElems == NumElems) {
4678 // Zero upper bits of the Vec
4679 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4680 DAG.getConstant(IdxVal, dl, MVT::i8));
4681 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4682 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4683 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4684 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4686 // Subvector should be inserted in the middle - use shuffle
4687 SmallVector<int, 64> Mask;
4688 for (unsigned i = 0; i < NumElems; ++i)
4689 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4691 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4694 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4695 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4696 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4697 /// large BUILD_VECTORS.
4698 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4699 unsigned NumElems, SelectionDAG &DAG,
4701 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4702 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4705 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4706 unsigned NumElems, SelectionDAG &DAG,
4708 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4709 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4712 /// Returns a vector of specified type with all bits set.
4713 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4714 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4715 /// Then bitcast to their original type, ensuring they get CSE'd.
4716 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4717 SelectionDAG &DAG, SDLoc dl) {
4718 assert(VT.isVector() && "Expected a vector type");
4720 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4722 if (VT.is512BitVector()) {
4723 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4724 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4725 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4726 } else if (VT.is256BitVector()) {
4727 if (Subtarget->hasInt256()) { // AVX2
4728 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4729 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4731 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4732 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4734 } else if (VT.is128BitVector()) {
4735 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4737 llvm_unreachable("Unexpected vector type");
4739 return DAG.getBitcast(VT, Vec);
4742 /// Returns a vector_shuffle node for an unpackl operation.
4743 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4745 unsigned NumElems = VT.getVectorNumElements();
4746 SmallVector<int, 8> Mask;
4747 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4749 Mask.push_back(i + NumElems);
4751 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4754 /// Returns a vector_shuffle node for an unpackh operation.
4755 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4757 unsigned NumElems = VT.getVectorNumElements();
4758 SmallVector<int, 8> Mask;
4759 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4760 Mask.push_back(i + Half);
4761 Mask.push_back(i + NumElems + Half);
4763 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4766 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4767 /// This produces a shuffle where the low element of V2 is swizzled into the
4768 /// zero/undef vector, landing at element Idx.
4769 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4770 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4772 const X86Subtarget *Subtarget,
4773 SelectionDAG &DAG) {
4774 MVT VT = V2.getSimpleValueType();
4776 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4777 unsigned NumElems = VT.getVectorNumElements();
4778 SmallVector<int, 16> MaskVec;
4779 for (unsigned i = 0; i != NumElems; ++i)
4780 // If this is the insertion idx, put the low elt of V2 here.
4781 MaskVec.push_back(i == Idx ? NumElems : i);
4782 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4785 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4786 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4787 /// uses one source. Note that this will set IsUnary for shuffles which use a
4788 /// single input multiple times, and in those cases it will
4789 /// adjust the mask to only have indices within that single input.
4790 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4791 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4792 unsigned NumElems = VT.getVectorNumElements();
4796 bool IsFakeUnary = false;
4797 switch(N->getOpcode()) {
4798 case X86ISD::BLENDI:
4799 ImmN = N->getOperand(N->getNumOperands()-1);
4800 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4803 ImmN = N->getOperand(N->getNumOperands()-1);
4804 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4805 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4807 case X86ISD::INSERTPS:
4808 ImmN = N->getOperand(N->getNumOperands()-1);
4809 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4810 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4812 case X86ISD::UNPCKH:
4813 DecodeUNPCKHMask(VT, Mask);
4814 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4816 case X86ISD::UNPCKL:
4817 DecodeUNPCKLMask(VT, Mask);
4818 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4820 case X86ISD::MOVHLPS:
4821 DecodeMOVHLPSMask(NumElems, Mask);
4822 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4824 case X86ISD::MOVLHPS:
4825 DecodeMOVLHPSMask(NumElems, Mask);
4826 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4828 case X86ISD::PALIGNR:
4829 ImmN = N->getOperand(N->getNumOperands()-1);
4830 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4832 case X86ISD::PSHUFD:
4833 case X86ISD::VPERMILPI:
4834 ImmN = N->getOperand(N->getNumOperands()-1);
4835 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4838 case X86ISD::PSHUFHW:
4839 ImmN = N->getOperand(N->getNumOperands()-1);
4840 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4843 case X86ISD::PSHUFLW:
4844 ImmN = N->getOperand(N->getNumOperands()-1);
4845 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4848 case X86ISD::PSHUFB: {
4850 SDValue MaskNode = N->getOperand(1);
4851 while (MaskNode->getOpcode() == ISD::BITCAST)
4852 MaskNode = MaskNode->getOperand(0);
4854 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4855 // If we have a build-vector, then things are easy.
4856 MVT VT = MaskNode.getSimpleValueType();
4857 assert(VT.isVector() &&
4858 "Can't produce a non-vector with a build_vector!");
4859 if (!VT.isInteger())
4862 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4864 SmallVector<uint64_t, 32> RawMask;
4865 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4866 SDValue Op = MaskNode->getOperand(i);
4867 if (Op->getOpcode() == ISD::UNDEF) {
4868 RawMask.push_back((uint64_t)SM_SentinelUndef);
4871 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4874 APInt MaskElement = CN->getAPIntValue();
4876 // We now have to decode the element which could be any integer size and
4877 // extract each byte of it.
4878 for (int j = 0; j < NumBytesPerElement; ++j) {
4879 // Note that this is x86 and so always little endian: the low byte is
4880 // the first byte of the mask.
4881 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4882 MaskElement = MaskElement.lshr(8);
4885 DecodePSHUFBMask(RawMask, Mask);
4889 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4893 SDValue Ptr = MaskLoad->getBasePtr();
4894 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4895 Ptr->getOpcode() == X86ISD::WrapperRIP)
4896 Ptr = Ptr->getOperand(0);
4898 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4899 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4902 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4903 DecodePSHUFBMask(C, Mask);
4909 case X86ISD::VPERMI:
4910 ImmN = N->getOperand(N->getNumOperands()-1);
4911 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4916 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4918 case X86ISD::VPERM2X128:
4919 ImmN = N->getOperand(N->getNumOperands()-1);
4920 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4921 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4923 case X86ISD::MOVSLDUP:
4924 DecodeMOVSLDUPMask(VT, Mask);
4927 case X86ISD::MOVSHDUP:
4928 DecodeMOVSHDUPMask(VT, Mask);
4931 case X86ISD::MOVDDUP:
4932 DecodeMOVDDUPMask(VT, Mask);
4935 case X86ISD::MOVLHPD:
4936 case X86ISD::MOVLPD:
4937 case X86ISD::MOVLPS:
4938 // Not yet implemented
4940 case X86ISD::VPERMV: {
4942 SDValue MaskNode = N->getOperand(0);
4943 while (MaskNode->getOpcode() == ISD::BITCAST)
4944 MaskNode = MaskNode->getOperand(0);
4946 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4947 SmallVector<uint64_t, 32> RawMask;
4948 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4949 // If we have a build-vector, then things are easy.
4950 assert(MaskNode.getSimpleValueType().isInteger() &&
4951 MaskNode.getSimpleValueType().getVectorNumElements() ==
4952 VT.getVectorNumElements());
4954 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4955 SDValue Op = MaskNode->getOperand(i);
4956 if (Op->getOpcode() == ISD::UNDEF)
4957 RawMask.push_back((uint64_t)SM_SentinelUndef);
4958 else if (isa<ConstantSDNode>(Op)) {
4959 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4960 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4964 DecodeVPERMVMask(RawMask, Mask);
4967 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4968 unsigned NumEltsInMask = MaskNode->getNumOperands();
4969 MaskNode = MaskNode->getOperand(0);
4970 if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4971 APInt MaskEltValue = CN->getAPIntValue();
4972 for (unsigned i = 0; i < NumEltsInMask; ++i)
4973 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4974 DecodeVPERMVMask(RawMask, Mask);
4977 // It may be a scalar load
4980 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4984 SDValue Ptr = MaskLoad->getBasePtr();
4985 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4986 Ptr->getOpcode() == X86ISD::WrapperRIP)
4987 Ptr = Ptr->getOperand(0);
4989 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4990 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4993 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4994 DecodeVPERMVMask(C, VT, Mask);
4999 case X86ISD::VPERMV3: {
5001 SDValue MaskNode = N->getOperand(1);
5002 while (MaskNode->getOpcode() == ISD::BITCAST)
5003 MaskNode = MaskNode->getOperand(1);
5005 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5006 // If we have a build-vector, then things are easy.
5007 assert(MaskNode.getSimpleValueType().isInteger() &&
5008 MaskNode.getSimpleValueType().getVectorNumElements() ==
5009 VT.getVectorNumElements());
5011 SmallVector<uint64_t, 32> RawMask;
5012 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
5014 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
5015 SDValue Op = MaskNode->getOperand(i);
5016 if (Op->getOpcode() == ISD::UNDEF)
5017 RawMask.push_back((uint64_t)SM_SentinelUndef);
5019 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5022 APInt MaskElement = CN->getAPIntValue();
5023 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
5026 DecodeVPERMV3Mask(RawMask, Mask);
5030 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5034 SDValue Ptr = MaskLoad->getBasePtr();
5035 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5036 Ptr->getOpcode() == X86ISD::WrapperRIP)
5037 Ptr = Ptr->getOperand(0);
5039 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5040 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5043 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5044 DecodeVPERMV3Mask(C, VT, Mask);
5049 default: llvm_unreachable("unknown target shuffle node");
5052 // Empty mask indicates the decode failed.
5056 // Check if we're getting a shuffle mask with zero'd elements.
5057 if (!AllowSentinelZero)
5058 if (std::any_of(Mask.begin(), Mask.end(),
5059 [](int M){ return M == SM_SentinelZero; }))
5062 // If we have a fake unary shuffle, the shuffle mask is spread across two
5063 // inputs that are actually the same node. Re-map the mask to always point
5064 // into the first input.
5067 if (M >= (int)Mask.size())
5073 /// Returns the scalar element that will make up the ith
5074 /// element of the result of the vector shuffle.
5075 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5078 return SDValue(); // Limit search depth.
5080 SDValue V = SDValue(N, 0);
5081 EVT VT = V.getValueType();
5082 unsigned Opcode = V.getOpcode();
5084 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5085 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5086 int Elt = SV->getMaskElt(Index);
5089 return DAG.getUNDEF(VT.getVectorElementType());
5091 unsigned NumElems = VT.getVectorNumElements();
5092 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5093 : SV->getOperand(1);
5094 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5097 // Recurse into target specific vector shuffles to find scalars.
5098 if (isTargetShuffle(Opcode)) {
5099 MVT ShufVT = V.getSimpleValueType();
5100 int NumElems = (int)ShufVT.getVectorNumElements();
5101 SmallVector<int, 16> ShuffleMask;
5104 if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5107 int Elt = ShuffleMask[Index];
5108 if (Elt == SM_SentinelUndef)
5109 return DAG.getUNDEF(ShufVT.getVectorElementType());
5111 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5112 SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5113 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5117 // Actual nodes that may contain scalar elements
5118 if (Opcode == ISD::BITCAST) {
5119 V = V.getOperand(0);
5120 EVT SrcVT = V.getValueType();
5121 unsigned NumElems = VT.getVectorNumElements();
5123 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5127 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5128 return (Index == 0) ? V.getOperand(0)
5129 : DAG.getUNDEF(VT.getVectorElementType());
5131 if (V.getOpcode() == ISD::BUILD_VECTOR)
5132 return V.getOperand(Index);
5137 /// Custom lower build_vector of v16i8.
5138 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5139 unsigned NumNonZero, unsigned NumZero,
5141 const X86Subtarget* Subtarget,
5142 const TargetLowering &TLI) {
5150 // SSE4.1 - use PINSRB to insert each byte directly.
5151 if (Subtarget->hasSSE41()) {
5152 for (unsigned i = 0; i < 16; ++i) {
5153 bool isNonZero = (NonZeros & (1 << i)) != 0;
5157 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5159 V = DAG.getUNDEF(MVT::v16i8);
5162 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5163 MVT::v16i8, V, Op.getOperand(i),
5164 DAG.getIntPtrConstant(i, dl));
5171 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5172 for (unsigned i = 0; i < 16; ++i) {
5173 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174 if (ThisIsNonZero && First) {
5176 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5178 V = DAG.getUNDEF(MVT::v8i16);
5183 SDValue ThisElt, LastElt;
5184 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185 if (LastIsNonZero) {
5186 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187 MVT::i16, Op.getOperand(i-1));
5189 if (ThisIsNonZero) {
5190 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5194 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5198 if (ThisElt.getNode())
5199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200 DAG.getIntPtrConstant(i/2, dl));
5204 return DAG.getBitcast(MVT::v16i8, V);
5207 /// Custom lower build_vector of v8i16.
5208 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5209 unsigned NumNonZero, unsigned NumZero,
5211 const X86Subtarget* Subtarget,
5212 const TargetLowering &TLI) {
5219 for (unsigned i = 0; i < 8; ++i) {
5220 bool isNonZero = (NonZeros & (1 << i)) != 0;
5224 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5226 V = DAG.getUNDEF(MVT::v8i16);
5229 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5230 MVT::v8i16, V, Op.getOperand(i),
5231 DAG.getIntPtrConstant(i, dl));
5238 /// Custom lower build_vector of v4i32 or v4f32.
5239 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5240 const X86Subtarget *Subtarget,
5241 const TargetLowering &TLI) {
5242 // Find all zeroable elements.
5243 std::bitset<4> Zeroable;
5244 for (int i=0; i < 4; ++i) {
5245 SDValue Elt = Op->getOperand(i);
5246 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5248 assert(Zeroable.size() - Zeroable.count() > 1 &&
5249 "We expect at least two non-zero elements!");
5251 // We only know how to deal with build_vector nodes where elements are either
5252 // zeroable or extract_vector_elt with constant index.
5253 SDValue FirstNonZero;
5254 unsigned FirstNonZeroIdx;
5255 for (unsigned i=0; i < 4; ++i) {
5258 SDValue Elt = Op->getOperand(i);
5259 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5260 !isa<ConstantSDNode>(Elt.getOperand(1)))
5262 // Make sure that this node is extracting from a 128-bit vector.
5263 MVT VT = Elt.getOperand(0).getSimpleValueType();
5264 if (!VT.is128BitVector())
5266 if (!FirstNonZero.getNode()) {
5268 FirstNonZeroIdx = i;
5272 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5273 SDValue V1 = FirstNonZero.getOperand(0);
5274 MVT VT = V1.getSimpleValueType();
5276 // See if this build_vector can be lowered as a blend with zero.
5278 unsigned EltMaskIdx, EltIdx;
5280 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5281 if (Zeroable[EltIdx]) {
5282 // The zero vector will be on the right hand side.
5283 Mask[EltIdx] = EltIdx+4;
5287 Elt = Op->getOperand(EltIdx);
5288 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5289 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5290 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5292 Mask[EltIdx] = EltIdx;
5296 // Let the shuffle legalizer deal with blend operations.
5297 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5298 if (V1.getSimpleValueType() != VT)
5299 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5300 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5303 // See if we can lower this build_vector to a INSERTPS.
5304 if (!Subtarget->hasSSE41())
5307 SDValue V2 = Elt.getOperand(0);
5308 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5311 bool CanFold = true;
5312 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5316 SDValue Current = Op->getOperand(i);
5317 SDValue SrcVector = Current->getOperand(0);
5320 CanFold = SrcVector == V1 &&
5321 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5327 assert(V1.getNode() && "Expected at least two non-zero elements!");
5328 if (V1.getSimpleValueType() != MVT::v4f32)
5329 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5330 if (V2.getSimpleValueType() != MVT::v4f32)
5331 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5333 // Ok, we can emit an INSERTPS instruction.
5334 unsigned ZMask = Zeroable.to_ulong();
5336 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5337 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5339 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5340 DAG.getIntPtrConstant(InsertPSMask, DL));
5341 return DAG.getBitcast(VT, Result);
5344 /// Return a vector logical shift node.
5345 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5346 unsigned NumBits, SelectionDAG &DAG,
5347 const TargetLowering &TLI, SDLoc dl) {
5348 assert(VT.is128BitVector() && "Unknown type for VShift");
5349 MVT ShVT = MVT::v2i64;
5350 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5351 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5352 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5353 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5354 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5355 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5359 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5361 // Check if the scalar load can be widened into a vector load. And if
5362 // the address is "base + cst" see if the cst can be "absorbed" into
5363 // the shuffle mask.
5364 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5365 SDValue Ptr = LD->getBasePtr();
5366 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5368 EVT PVT = LD->getValueType(0);
5369 if (PVT != MVT::i32 && PVT != MVT::f32)
5374 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5375 FI = FINode->getIndex();
5377 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5378 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5379 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5380 Offset = Ptr.getConstantOperandVal(1);
5381 Ptr = Ptr.getOperand(0);
5386 // FIXME: 256-bit vector instructions don't require a strict alignment,
5387 // improve this code to support it better.
5388 unsigned RequiredAlign = VT.getSizeInBits()/8;
5389 SDValue Chain = LD->getChain();
5390 // Make sure the stack object alignment is at least 16 or 32.
5391 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5392 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5393 if (MFI->isFixedObjectIndex(FI)) {
5394 // Can't change the alignment. FIXME: It's possible to compute
5395 // the exact stack offset and reference FI + adjust offset instead.
5396 // If someone *really* cares about this. That's the way to implement it.
5399 MFI->setObjectAlignment(FI, RequiredAlign);
5403 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5404 // Ptr + (Offset & ~15).
5407 if ((Offset % RequiredAlign) & 3)
5409 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5412 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5413 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5416 int EltNo = (Offset - StartOffset) >> 2;
5417 unsigned NumElems = VT.getVectorNumElements();
5419 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5420 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5421 LD->getPointerInfo().getWithOffset(StartOffset),
5422 false, false, false, 0);
5424 SmallVector<int, 8> Mask(NumElems, EltNo);
5426 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5432 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5433 /// elements can be replaced by a single large load which has the same value as
5434 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5436 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5438 /// FIXME: we'd also like to handle the case where the last elements are zero
5439 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5440 /// There's even a handy isZeroNode for that purpose.
5441 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5442 SDLoc &DL, SelectionDAG &DAG,
5443 bool isAfterLegalize) {
5444 unsigned NumElems = Elts.size();
5446 LoadSDNode *LDBase = nullptr;
5447 unsigned LastLoadedElt = -1U;
5449 // For each element in the initializer, see if we've found a load or an undef.
5450 // If we don't find an initial load element, or later load elements are
5451 // non-consecutive, bail out.
5452 for (unsigned i = 0; i < NumElems; ++i) {
5453 SDValue Elt = Elts[i];
5454 // Look through a bitcast.
5455 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5456 Elt = Elt.getOperand(0);
5457 if (!Elt.getNode() ||
5458 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5461 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5463 LDBase = cast<LoadSDNode>(Elt.getNode());
5467 if (Elt.getOpcode() == ISD::UNDEF)
5470 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5471 EVT LdVT = Elt.getValueType();
5472 // Each loaded element must be the correct fractional portion of the
5473 // requested vector load.
5474 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5476 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5481 // If we have found an entire vector of loads and undefs, then return a large
5482 // load of the entire vector width starting at the base pointer. If we found
5483 // consecutive loads for the low half, generate a vzext_load node.
5484 if (LastLoadedElt == NumElems - 1) {
5485 assert(LDBase && "Did not find base load for merging consecutive loads");
5486 EVT EltVT = LDBase->getValueType(0);
5487 // Ensure that the input vector size for the merged loads matches the
5488 // cumulative size of the input elements.
5489 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5492 if (isAfterLegalize &&
5493 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5496 SDValue NewLd = SDValue();
5498 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5499 LDBase->getPointerInfo(), LDBase->isVolatile(),
5500 LDBase->isNonTemporal(), LDBase->isInvariant(),
5501 LDBase->getAlignment());
5503 if (LDBase->hasAnyUseOfValue(1)) {
5504 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5506 SDValue(NewLd.getNode(), 1));
5507 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5508 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5509 SDValue(NewLd.getNode(), 1));
5515 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5516 //of a v4i32 / v4f32. It's probably worth generalizing.
5517 EVT EltVT = VT.getVectorElementType();
5518 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5519 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5520 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5521 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5523 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5524 LDBase->getPointerInfo(),
5525 LDBase->getAlignment(),
5526 false/*isVolatile*/, true/*ReadMem*/,
5529 // Make sure the newly-created LOAD is in the same position as LDBase in
5530 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5531 // update uses of LDBase's output chain to use the TokenFactor.
5532 if (LDBase->hasAnyUseOfValue(1)) {
5533 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5534 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5535 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5536 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5537 SDValue(ResNode.getNode(), 1));
5540 return DAG.getBitcast(VT, ResNode);
5545 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5546 /// to generate a splat value for the following cases:
5547 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5548 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5549 /// a scalar load, or a constant.
5550 /// The VBROADCAST node is returned when a pattern is found,
5551 /// or SDValue() otherwise.
5552 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5553 SelectionDAG &DAG) {
5554 // VBROADCAST requires AVX.
5555 // TODO: Splats could be generated for non-AVX CPUs using SSE
5556 // instructions, but there's less potential gain for only 128-bit vectors.
5557 if (!Subtarget->hasAVX())
5560 MVT VT = Op.getSimpleValueType();
5563 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5564 "Unsupported vector type for broadcast.");
5569 switch (Op.getOpcode()) {
5571 // Unknown pattern found.
5574 case ISD::BUILD_VECTOR: {
5575 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5576 BitVector UndefElements;
5577 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5579 // We need a splat of a single value to use broadcast, and it doesn't
5580 // make any sense if the value is only in one element of the vector.
5581 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5585 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5586 Ld.getOpcode() == ISD::ConstantFP);
5588 // Make sure that all of the users of a non-constant load are from the
5589 // BUILD_VECTOR node.
5590 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5595 case ISD::VECTOR_SHUFFLE: {
5596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5598 // Shuffles must have a splat mask where the first element is
5600 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5603 SDValue Sc = Op.getOperand(0);
5604 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5605 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5607 if (!Subtarget->hasInt256())
5610 // Use the register form of the broadcast instruction available on AVX2.
5611 if (VT.getSizeInBits() >= 256)
5612 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5613 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5616 Ld = Sc.getOperand(0);
5617 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5618 Ld.getOpcode() == ISD::ConstantFP);
5620 // The scalar_to_vector node and the suspected
5621 // load node must have exactly one user.
5622 // Constants may have multiple users.
5624 // AVX-512 has register version of the broadcast
5625 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5626 Ld.getValueType().getSizeInBits() >= 32;
5627 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5634 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5635 bool IsGE256 = (VT.getSizeInBits() >= 256);
5637 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5638 // instruction to save 8 or more bytes of constant pool data.
5639 // TODO: If multiple splats are generated to load the same constant,
5640 // it may be detrimental to overall size. There needs to be a way to detect
5641 // that condition to know if this is truly a size win.
5642 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5644 // Handle broadcasting a single constant scalar from the constant pool
5646 // On Sandybridge (no AVX2), it is still better to load a constant vector
5647 // from the constant pool and not to broadcast it from a scalar.
5648 // But override that restriction when optimizing for size.
5649 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5650 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5651 EVT CVT = Ld.getValueType();
5652 assert(!CVT.isVector() && "Must not broadcast a vector type");
5654 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5655 // For size optimization, also splat v2f64 and v2i64, and for size opt
5656 // with AVX2, also splat i8 and i16.
5657 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5658 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5659 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5660 const Constant *C = nullptr;
5661 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5662 C = CI->getConstantIntValue();
5663 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5664 C = CF->getConstantFPValue();
5666 assert(C && "Invalid constant type");
5668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5670 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5671 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5673 CVT, dl, DAG.getEntryNode(), CP,
5674 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5675 false, false, Alignment);
5677 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5681 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5683 // Handle AVX2 in-register broadcasts.
5684 if (!IsLoad && Subtarget->hasInt256() &&
5685 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5686 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5688 // The scalar source must be a normal load.
5692 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5693 (Subtarget->hasVLX() && ScalarSize == 64))
5694 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5696 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5697 // double since there is no vbroadcastsd xmm
5698 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5699 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5700 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5703 // Unsupported broadcast.
5707 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5708 /// underlying vector and index.
5710 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5712 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5714 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5715 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5718 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5720 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5722 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5723 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5726 // In this case the vector is the extract_subvector expression and the index
5727 // is 2, as specified by the shuffle.
5728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5729 SDValue ShuffleVec = SVOp->getOperand(0);
5730 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5731 assert(ShuffleVecVT.getVectorElementType() ==
5732 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5734 int ShuffleIdx = SVOp->getMaskElt(Idx);
5735 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5736 ExtractedFromVec = ShuffleVec;
5742 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5743 MVT VT = Op.getSimpleValueType();
5745 // Skip if insert_vec_elt is not supported.
5746 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5747 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5751 unsigned NumElems = Op.getNumOperands();
5755 SmallVector<unsigned, 4> InsertIndices;
5756 SmallVector<int, 8> Mask(NumElems, -1);
5758 for (unsigned i = 0; i != NumElems; ++i) {
5759 unsigned Opc = Op.getOperand(i).getOpcode();
5761 if (Opc == ISD::UNDEF)
5764 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5765 // Quit if more than 1 elements need inserting.
5766 if (InsertIndices.size() > 1)
5769 InsertIndices.push_back(i);
5773 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5774 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5775 // Quit if non-constant index.
5776 if (!isa<ConstantSDNode>(ExtIdx))
5778 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5780 // Quit if extracted from vector of different type.
5781 if (ExtractedFromVec.getValueType() != VT)
5784 if (!VecIn1.getNode())
5785 VecIn1 = ExtractedFromVec;
5786 else if (VecIn1 != ExtractedFromVec) {
5787 if (!VecIn2.getNode())
5788 VecIn2 = ExtractedFromVec;
5789 else if (VecIn2 != ExtractedFromVec)
5790 // Quit if more than 2 vectors to shuffle
5794 if (ExtractedFromVec == VecIn1)
5796 else if (ExtractedFromVec == VecIn2)
5797 Mask[i] = Idx + NumElems;
5800 if (!VecIn1.getNode())
5803 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5804 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5805 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5806 unsigned Idx = InsertIndices[i];
5807 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5808 DAG.getIntPtrConstant(Idx, DL));
5814 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5815 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5816 Op.getScalarValueSizeInBits() == 1 &&
5817 "Can not convert non-constant vector");
5818 uint64_t Immediate = 0;
5819 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5820 SDValue In = Op.getOperand(idx);
5821 if (In.getOpcode() != ISD::UNDEF)
5822 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5826 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5827 return DAG.getConstant(Immediate, dl, VT);
5829 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5831 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5833 MVT VT = Op.getSimpleValueType();
5834 assert((VT.getVectorElementType() == MVT::i1) &&
5835 "Unexpected type in LowerBUILD_VECTORvXi1!");
5838 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5839 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5840 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5841 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5844 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5845 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5846 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5847 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5850 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5851 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5852 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5853 return DAG.getBitcast(VT, Imm);
5854 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5855 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5856 DAG.getIntPtrConstant(0, dl));
5859 // Vector has one or more non-const elements
5860 uint64_t Immediate = 0;
5861 SmallVector<unsigned, 16> NonConstIdx;
5862 bool IsSplat = true;
5863 bool HasConstElts = false;
5865 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5866 SDValue In = Op.getOperand(idx);
5867 if (In.getOpcode() == ISD::UNDEF)
5869 if (!isa<ConstantSDNode>(In))
5870 NonConstIdx.push_back(idx);
5872 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5873 HasConstElts = true;
5877 else if (In != Op.getOperand(SplatIdx))
5881 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5883 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5884 DAG.getConstant(1, dl, VT),
5885 DAG.getConstant(0, dl, VT));
5887 // insert elements one by one
5891 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5892 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5894 else if (HasConstElts)
5895 Imm = DAG.getConstant(0, dl, VT);
5897 Imm = DAG.getUNDEF(VT);
5898 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5899 DstVec = DAG.getBitcast(VT, Imm);
5901 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5902 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5903 DAG.getIntPtrConstant(0, dl));
5906 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5907 unsigned InsertIdx = NonConstIdx[i];
5908 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5909 Op.getOperand(InsertIdx),
5910 DAG.getIntPtrConstant(InsertIdx, dl));
5915 /// \brief Return true if \p N implements a horizontal binop and return the
5916 /// operands for the horizontal binop into V0 and V1.
5918 /// This is a helper function of LowerToHorizontalOp().
5919 /// This function checks that the build_vector \p N in input implements a
5920 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5921 /// operation to match.
5922 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5923 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5924 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5927 /// This function only analyzes elements of \p N whose indices are
5928 /// in range [BaseIdx, LastIdx).
5929 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5931 unsigned BaseIdx, unsigned LastIdx,
5932 SDValue &V0, SDValue &V1) {
5933 EVT VT = N->getValueType(0);
5935 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5936 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5937 "Invalid Vector in input!");
5939 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5940 bool CanFold = true;
5941 unsigned ExpectedVExtractIdx = BaseIdx;
5942 unsigned NumElts = LastIdx - BaseIdx;
5943 V0 = DAG.getUNDEF(VT);
5944 V1 = DAG.getUNDEF(VT);
5946 // Check if N implements a horizontal binop.
5947 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5948 SDValue Op = N->getOperand(i + BaseIdx);
5951 if (Op->getOpcode() == ISD::UNDEF) {
5952 // Update the expected vector extract index.
5953 if (i * 2 == NumElts)
5954 ExpectedVExtractIdx = BaseIdx;
5955 ExpectedVExtractIdx += 2;
5959 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5964 SDValue Op0 = Op.getOperand(0);
5965 SDValue Op1 = Op.getOperand(1);
5967 // Try to match the following pattern:
5968 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5969 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5970 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5971 Op0.getOperand(0) == Op1.getOperand(0) &&
5972 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5973 isa<ConstantSDNode>(Op1.getOperand(1)));
5977 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5978 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5980 if (i * 2 < NumElts) {
5981 if (V0.getOpcode() == ISD::UNDEF) {
5982 V0 = Op0.getOperand(0);
5983 if (V0.getValueType() != VT)
5987 if (V1.getOpcode() == ISD::UNDEF) {
5988 V1 = Op0.getOperand(0);
5989 if (V1.getValueType() != VT)
5992 if (i * 2 == NumElts)
5993 ExpectedVExtractIdx = BaseIdx;
5996 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5997 if (I0 == ExpectedVExtractIdx)
5998 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5999 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6000 // Try to match the following dag sequence:
6001 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6002 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6006 ExpectedVExtractIdx += 2;
6012 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6013 /// a concat_vector.
6015 /// This is a helper function of LowerToHorizontalOp().
6016 /// This function expects two 256-bit vectors called V0 and V1.
6017 /// At first, each vector is split into two separate 128-bit vectors.
6018 /// Then, the resulting 128-bit vectors are used to implement two
6019 /// horizontal binary operations.
6021 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6023 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6024 /// the two new horizontal binop.
6025 /// When Mode is set, the first horizontal binop dag node would take as input
6026 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6027 /// horizontal binop dag node would take as input the lower 128-bit of V1
6028 /// and the upper 128-bit of V1.
6030 /// HADD V0_LO, V0_HI
6031 /// HADD V1_LO, V1_HI
6033 /// Otherwise, the first horizontal binop dag node takes as input the lower
6034 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6035 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6037 /// HADD V0_LO, V1_LO
6038 /// HADD V0_HI, V1_HI
6040 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6041 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6042 /// the upper 128-bits of the result.
6043 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6044 SDLoc DL, SelectionDAG &DAG,
6045 unsigned X86Opcode, bool Mode,
6046 bool isUndefLO, bool isUndefHI) {
6047 EVT VT = V0.getValueType();
6048 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6049 "Invalid nodes in input!");
6051 unsigned NumElts = VT.getVectorNumElements();
6052 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6053 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6054 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6055 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6056 EVT NewVT = V0_LO.getValueType();
6058 SDValue LO = DAG.getUNDEF(NewVT);
6059 SDValue HI = DAG.getUNDEF(NewVT);
6062 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6063 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6064 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6065 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6066 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6068 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6069 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6070 V1_LO->getOpcode() != ISD::UNDEF))
6071 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6073 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6074 V1_HI->getOpcode() != ISD::UNDEF))
6075 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6078 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6081 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6083 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6084 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6085 MVT VT = BV->getSimpleValueType(0);
6086 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6087 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6091 unsigned NumElts = VT.getVectorNumElements();
6092 SDValue InVec0 = DAG.getUNDEF(VT);
6093 SDValue InVec1 = DAG.getUNDEF(VT);
6095 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6096 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6098 // Odd-numbered elements in the input build vector are obtained from
6099 // adding two integer/float elements.
6100 // Even-numbered elements in the input build vector are obtained from
6101 // subtracting two integer/float elements.
6102 unsigned ExpectedOpcode = ISD::FSUB;
6103 unsigned NextExpectedOpcode = ISD::FADD;
6104 bool AddFound = false;
6105 bool SubFound = false;
6107 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6108 SDValue Op = BV->getOperand(i);
6110 // Skip 'undef' values.
6111 unsigned Opcode = Op.getOpcode();
6112 if (Opcode == ISD::UNDEF) {
6113 std::swap(ExpectedOpcode, NextExpectedOpcode);
6117 // Early exit if we found an unexpected opcode.
6118 if (Opcode != ExpectedOpcode)
6121 SDValue Op0 = Op.getOperand(0);
6122 SDValue Op1 = Op.getOperand(1);
6124 // Try to match the following pattern:
6125 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6126 // Early exit if we cannot match that sequence.
6127 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6128 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6129 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6130 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6131 Op0.getOperand(1) != Op1.getOperand(1))
6134 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6138 // We found a valid add/sub node. Update the information accordingly.
6144 // Update InVec0 and InVec1.
6145 if (InVec0.getOpcode() == ISD::UNDEF) {
6146 InVec0 = Op0.getOperand(0);
6147 if (InVec0.getSimpleValueType() != VT)
6150 if (InVec1.getOpcode() == ISD::UNDEF) {
6151 InVec1 = Op1.getOperand(0);
6152 if (InVec1.getSimpleValueType() != VT)
6156 // Make sure that operands in input to each add/sub node always
6157 // come from a same pair of vectors.
6158 if (InVec0 != Op0.getOperand(0)) {
6159 if (ExpectedOpcode == ISD::FSUB)
6162 // FADD is commutable. Try to commute the operands
6163 // and then test again.
6164 std::swap(Op0, Op1);
6165 if (InVec0 != Op0.getOperand(0))
6169 if (InVec1 != Op1.getOperand(0))
6172 // Update the pair of expected opcodes.
6173 std::swap(ExpectedOpcode, NextExpectedOpcode);
6176 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6177 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6178 InVec1.getOpcode() != ISD::UNDEF)
6179 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6184 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6185 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6186 const X86Subtarget *Subtarget,
6187 SelectionDAG &DAG) {
6188 MVT VT = BV->getSimpleValueType(0);
6189 unsigned NumElts = VT.getVectorNumElements();
6190 unsigned NumUndefsLO = 0;
6191 unsigned NumUndefsHI = 0;
6192 unsigned Half = NumElts/2;
6194 // Count the number of UNDEF operands in the build_vector in input.
6195 for (unsigned i = 0, e = Half; i != e; ++i)
6196 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6199 for (unsigned i = Half, e = NumElts; i != e; ++i)
6200 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6203 // Early exit if this is either a build_vector of all UNDEFs or all the
6204 // operands but one are UNDEF.
6205 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6209 SDValue InVec0, InVec1;
6210 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6211 // Try to match an SSE3 float HADD/HSUB.
6212 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6213 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6215 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6216 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6217 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6218 // Try to match an SSSE3 integer HADD/HSUB.
6219 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6220 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6222 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6223 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6226 if (!Subtarget->hasAVX())
6229 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6230 // Try to match an AVX horizontal add/sub of packed single/double
6231 // precision floating point values from 256-bit vectors.
6232 SDValue InVec2, InVec3;
6233 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6234 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6235 ((InVec0.getOpcode() == ISD::UNDEF ||
6236 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6237 ((InVec1.getOpcode() == ISD::UNDEF ||
6238 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6239 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6241 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6242 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6243 ((InVec0.getOpcode() == ISD::UNDEF ||
6244 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6245 ((InVec1.getOpcode() == ISD::UNDEF ||
6246 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6247 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6248 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6249 // Try to match an AVX2 horizontal add/sub of signed integers.
6250 SDValue InVec2, InVec3;
6252 bool CanFold = true;
6254 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6255 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6256 ((InVec0.getOpcode() == ISD::UNDEF ||
6257 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6258 ((InVec1.getOpcode() == ISD::UNDEF ||
6259 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6260 X86Opcode = X86ISD::HADD;
6261 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6262 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6263 ((InVec0.getOpcode() == ISD::UNDEF ||
6264 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6265 ((InVec1.getOpcode() == ISD::UNDEF ||
6266 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6267 X86Opcode = X86ISD::HSUB;
6272 // Fold this build_vector into a single horizontal add/sub.
6273 // Do this only if the target has AVX2.
6274 if (Subtarget->hasAVX2())
6275 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6277 // Do not try to expand this build_vector into a pair of horizontal
6278 // add/sub if we can emit a pair of scalar add/sub.
6279 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6282 // Convert this build_vector into a pair of horizontal binop followed by
6284 bool isUndefLO = NumUndefsLO == Half;
6285 bool isUndefHI = NumUndefsHI == Half;
6286 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6287 isUndefLO, isUndefHI);
6291 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6292 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6294 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6295 X86Opcode = X86ISD::HADD;
6296 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6297 X86Opcode = X86ISD::HSUB;
6298 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6299 X86Opcode = X86ISD::FHADD;
6300 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6301 X86Opcode = X86ISD::FHSUB;
6305 // Don't try to expand this build_vector into a pair of horizontal add/sub
6306 // if we can simply emit a pair of scalar add/sub.
6307 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6310 // Convert this build_vector into two horizontal add/sub followed by
6312 bool isUndefLO = NumUndefsLO == Half;
6313 bool isUndefHI = NumUndefsHI == Half;
6314 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6315 isUndefLO, isUndefHI);
6322 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6325 MVT VT = Op.getSimpleValueType();
6326 MVT ExtVT = VT.getVectorElementType();
6327 unsigned NumElems = Op.getNumOperands();
6329 // Generate vectors for predicate vectors.
6330 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6331 return LowerBUILD_VECTORvXi1(Op, DAG);
6333 // Vectors containing all zeros can be matched by pxor and xorps later
6334 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6335 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6336 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6337 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6340 return getZeroVector(VT, Subtarget, DAG, dl);
6343 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6344 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6345 // vpcmpeqd on 256-bit vectors.
6346 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6347 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6350 if (!VT.is512BitVector())
6351 return getOnesVector(VT, Subtarget, DAG, dl);
6354 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6355 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6357 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6358 return HorizontalOp;
6359 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6362 unsigned EVTBits = ExtVT.getSizeInBits();
6364 unsigned NumZero = 0;
6365 unsigned NumNonZero = 0;
6366 uint64_t NonZeros = 0;
6367 bool IsAllConstants = true;
6368 SmallSet<SDValue, 8> Values;
6369 for (unsigned i = 0; i < NumElems; ++i) {
6370 SDValue Elt = Op.getOperand(i);
6371 if (Elt.getOpcode() == ISD::UNDEF)
6374 if (Elt.getOpcode() != ISD::Constant &&
6375 Elt.getOpcode() != ISD::ConstantFP)
6376 IsAllConstants = false;
6377 if (X86::isZeroNode(Elt))
6380 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6381 NonZeros |= ((uint64_t)1 << i);
6386 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6387 if (NumNonZero == 0)
6388 return DAG.getUNDEF(VT);
6390 // Special case for single non-zero, non-undef, element.
6391 if (NumNonZero == 1) {
6392 unsigned Idx = countTrailingZeros(NonZeros);
6393 SDValue Item = Op.getOperand(Idx);
6395 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6396 // the value are obviously zero, truncate the value to i32 and do the
6397 // insertion that way. Only do this if the value is non-constant or if the
6398 // value is a constant being inserted into element 0. It is cheaper to do
6399 // a constant pool load than it is to do a movd + shuffle.
6400 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6401 (!IsAllConstants || Idx == 0)) {
6402 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6404 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6405 MVT VecVT = MVT::v4i32;
6407 // Truncate the value (which may itself be a constant) to i32, and
6408 // convert it to a vector with movd (S2V+shuffle to zero extend).
6409 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6410 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6411 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6412 Item, Idx * 2, true, Subtarget, DAG));
6416 // If we have a constant or non-constant insertion into the low element of
6417 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6418 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6419 // depending on what the source datatype is.
6422 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6424 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6425 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6426 if (VT.is512BitVector()) {
6427 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6428 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6429 Item, DAG.getIntPtrConstant(0, dl));
6431 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6432 "Expected an SSE value type!");
6433 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6434 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6435 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6438 // We can't directly insert an i8 or i16 into a vector, so zero extend
6440 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6441 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6442 if (VT.is256BitVector()) {
6443 if (Subtarget->hasAVX()) {
6444 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6445 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6447 // Without AVX, we need to extend to a 128-bit vector and then
6448 // insert into the 256-bit vector.
6449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6450 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6451 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6454 assert(VT.is128BitVector() && "Expected an SSE value type!");
6455 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6456 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6458 return DAG.getBitcast(VT, Item);
6462 // Is it a vector logical left shift?
6463 if (NumElems == 2 && Idx == 1 &&
6464 X86::isZeroNode(Op.getOperand(0)) &&
6465 !X86::isZeroNode(Op.getOperand(1))) {
6466 unsigned NumBits = VT.getSizeInBits();
6467 return getVShift(true, VT,
6468 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6469 VT, Op.getOperand(1)),
6470 NumBits/2, DAG, *this, dl);
6473 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6476 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6477 // is a non-constant being inserted into an element other than the low one,
6478 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6479 // movd/movss) to move this into the low element, then shuffle it into
6481 if (EVTBits == 32) {
6482 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6483 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6487 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6488 if (Values.size() == 1) {
6489 if (EVTBits == 32) {
6490 // Instead of a shuffle like this:
6491 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6492 // Check if it's possible to issue this instead.
6493 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6494 unsigned Idx = countTrailingZeros(NonZeros);
6495 SDValue Item = Op.getOperand(Idx);
6496 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6497 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6502 // A vector full of immediates; various special cases are already
6503 // handled, so this is best done with a single constant-pool load.
6507 // For AVX-length vectors, see if we can use a vector load to get all of the
6508 // elements, otherwise build the individual 128-bit pieces and use
6509 // shuffles to put them in place.
6510 if (VT.is256BitVector() || VT.is512BitVector()) {
6511 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6513 // Check for a build vector of consecutive loads.
6514 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6517 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6519 // Build both the lower and upper subvector.
6520 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6521 makeArrayRef(&V[0], NumElems/2));
6522 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6523 makeArrayRef(&V[NumElems / 2], NumElems/2));
6525 // Recreate the wider vector with the lower and upper part.
6526 if (VT.is256BitVector())
6527 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6528 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6531 // Let legalizer expand 2-wide build_vectors.
6532 if (EVTBits == 64) {
6533 if (NumNonZero == 1) {
6534 // One half is zero or undef.
6535 unsigned Idx = countTrailingZeros(NonZeros);
6536 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6537 Op.getOperand(Idx));
6538 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6543 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6544 if (EVTBits == 8 && NumElems == 16)
6545 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6546 DAG, Subtarget, *this))
6549 if (EVTBits == 16 && NumElems == 8)
6550 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6551 DAG, Subtarget, *this))
6554 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6555 if (EVTBits == 32 && NumElems == 4)
6556 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6559 // If element VT is == 32 bits, turn it into a number of shuffles.
6560 SmallVector<SDValue, 8> V(NumElems);
6561 if (NumElems == 4 && NumZero > 0) {
6562 for (unsigned i = 0; i < 4; ++i) {
6563 bool isZero = !(NonZeros & (1ULL << i));
6565 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6567 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6570 for (unsigned i = 0; i < 2; ++i) {
6571 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6574 V[i] = V[i*2]; // Must be a zero vector.
6577 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6580 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6583 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6588 bool Reverse1 = (NonZeros & 0x3) == 2;
6589 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6593 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6594 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6596 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6599 if (Values.size() > 1 && VT.is128BitVector()) {
6600 // Check for a build vector of consecutive loads.
6601 for (unsigned i = 0; i < NumElems; ++i)
6602 V[i] = Op.getOperand(i);
6604 // Check for elements which are consecutive loads.
6605 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6608 // Check for a build vector from mostly shuffle plus few inserting.
6609 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6612 // For SSE 4.1, use insertps to put the high elements into the low element.
6613 if (Subtarget->hasSSE41()) {
6615 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6616 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6618 Result = DAG.getUNDEF(VT);
6620 for (unsigned i = 1; i < NumElems; ++i) {
6621 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6622 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6623 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6628 // Otherwise, expand into a number of unpckl*, start by extending each of
6629 // our (non-undef) elements to the full vector width with the element in the
6630 // bottom slot of the vector (which generates no code for SSE).
6631 for (unsigned i = 0; i < NumElems; ++i) {
6632 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6633 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6635 V[i] = DAG.getUNDEF(VT);
6638 // Next, we iteratively mix elements, e.g. for v4f32:
6639 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6640 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6641 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6642 unsigned EltStride = NumElems >> 1;
6643 while (EltStride != 0) {
6644 for (unsigned i = 0; i < EltStride; ++i) {
6645 // If V[i+EltStride] is undef and this is the first round of mixing,
6646 // then it is safe to just drop this shuffle: V[i] is already in the
6647 // right place, the one element (since it's the first round) being
6648 // inserted as undef can be dropped. This isn't safe for successive
6649 // rounds because they will permute elements within both vectors.
6650 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6651 EltStride == NumElems/2)
6654 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6663 // 256-bit AVX can use the vinsertf128 instruction
6664 // to create 256-bit vectors from two other 128-bit ones.
6665 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6667 MVT ResVT = Op.getSimpleValueType();
6669 assert((ResVT.is256BitVector() ||
6670 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6672 SDValue V1 = Op.getOperand(0);
6673 SDValue V2 = Op.getOperand(1);
6674 unsigned NumElems = ResVT.getVectorNumElements();
6675 if (ResVT.is256BitVector())
6676 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6678 if (Op.getNumOperands() == 4) {
6679 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6680 ResVT.getVectorNumElements()/2);
6681 SDValue V3 = Op.getOperand(2);
6682 SDValue V4 = Op.getOperand(3);
6683 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6684 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6686 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6689 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6690 const X86Subtarget *Subtarget,
6691 SelectionDAG & DAG) {
6693 MVT ResVT = Op.getSimpleValueType();
6694 unsigned NumOfOperands = Op.getNumOperands();
6696 assert(isPowerOf2_32(NumOfOperands) &&
6697 "Unexpected number of operands in CONCAT_VECTORS");
6699 SDValue Undef = DAG.getUNDEF(ResVT);
6700 if (NumOfOperands > 2) {
6701 // Specialize the cases when all, or all but one, of the operands are undef.
6702 unsigned NumOfDefinedOps = 0;
6704 for (unsigned i = 0; i < NumOfOperands; i++)
6705 if (!Op.getOperand(i).isUndef()) {
6709 if (NumOfDefinedOps == 0)
6711 if (NumOfDefinedOps == 1) {
6712 unsigned SubVecNumElts =
6713 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6714 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6715 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6716 Op.getOperand(OpIdx), IdxVal);
6719 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6720 ResVT.getVectorNumElements()/2);
6721 SmallVector<SDValue, 2> Ops;
6722 for (unsigned i = 0; i < NumOfOperands/2; i++)
6723 Ops.push_back(Op.getOperand(i));
6724 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6726 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6727 Ops.push_back(Op.getOperand(i));
6728 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6729 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6733 SDValue V1 = Op.getOperand(0);
6734 SDValue V2 = Op.getOperand(1);
6735 unsigned NumElems = ResVT.getVectorNumElements();
6736 assert(V1.getValueType() == V2.getValueType() &&
6737 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6738 "Unexpected operands in CONCAT_VECTORS");
6740 if (ResVT.getSizeInBits() >= 16)
6741 return Op; // The operation is legal with KUNPCK
6743 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6744 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6745 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6746 if (IsZeroV1 && IsZeroV2)
6749 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6751 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6753 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6755 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6757 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6760 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6762 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6763 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6766 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6767 const X86Subtarget *Subtarget,
6768 SelectionDAG &DAG) {
6769 MVT VT = Op.getSimpleValueType();
6770 if (VT.getVectorElementType() == MVT::i1)
6771 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6773 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6774 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6775 Op.getNumOperands() == 4)));
6777 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6778 // from two other 128-bit ones.
6780 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6781 return LowerAVXCONCAT_VECTORS(Op, DAG);
6784 //===----------------------------------------------------------------------===//
6785 // Vector shuffle lowering
6787 // This is an experimental code path for lowering vector shuffles on x86. It is
6788 // designed to handle arbitrary vector shuffles and blends, gracefully
6789 // degrading performance as necessary. It works hard to recognize idiomatic
6790 // shuffles and lower them to optimal instruction patterns without leaving
6791 // a framework that allows reasonably efficient handling of all vector shuffle
6793 //===----------------------------------------------------------------------===//
6795 /// \brief Tiny helper function to identify a no-op mask.
6797 /// This is a somewhat boring predicate function. It checks whether the mask
6798 /// array input, which is assumed to be a single-input shuffle mask of the kind
6799 /// used by the X86 shuffle instructions (not a fully general
6800 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6801 /// in-place shuffle are 'no-op's.
6802 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6803 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6804 if (Mask[i] != -1 && Mask[i] != i)
6809 /// \brief Helper function to classify a mask as a single-input mask.
6811 /// This isn't a generic single-input test because in the vector shuffle
6812 /// lowering we canonicalize single inputs to be the first input operand. This
6813 /// means we can more quickly test for a single input by only checking whether
6814 /// an input from the second operand exists. We also assume that the size of
6815 /// mask corresponds to the size of the input vectors which isn't true in the
6816 /// fully general case.
6817 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6819 if (M >= (int)Mask.size())
6824 /// \brief Test whether there are elements crossing 128-bit lanes in this
6827 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6828 /// and we routinely test for these.
6829 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6830 int LaneSize = 128 / VT.getScalarSizeInBits();
6831 int Size = Mask.size();
6832 for (int i = 0; i < Size; ++i)
6833 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6838 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6840 /// This checks a shuffle mask to see if it is performing the same
6841 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6842 /// that it is also not lane-crossing. It may however involve a blend from the
6843 /// same lane of a second vector.
6845 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6846 /// non-trivial to compute in the face of undef lanes. The representation is
6847 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6848 /// entries from both V1 and V2 inputs to the wider mask.
6850 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6851 SmallVectorImpl<int> &RepeatedMask) {
6852 int LaneSize = 128 / VT.getScalarSizeInBits();
6853 RepeatedMask.resize(LaneSize, -1);
6854 int Size = Mask.size();
6855 for (int i = 0; i < Size; ++i) {
6858 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6859 // This entry crosses lanes, so there is no way to model this shuffle.
6862 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6863 if (RepeatedMask[i % LaneSize] == -1)
6864 // This is the first non-undef entry in this slot of a 128-bit lane.
6865 RepeatedMask[i % LaneSize] =
6866 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6867 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6868 // Found a mismatch with the repeated mask.
6874 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6877 /// This is a fast way to test a shuffle mask against a fixed pattern:
6879 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6881 /// It returns true if the mask is exactly as wide as the argument list, and
6882 /// each element of the mask is either -1 (signifying undef) or the value given
6883 /// in the argument.
6884 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6885 ArrayRef<int> ExpectedMask) {
6886 if (Mask.size() != ExpectedMask.size())
6889 int Size = Mask.size();
6891 // If the values are build vectors, we can look through them to find
6892 // equivalent inputs that make the shuffles equivalent.
6893 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6894 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6896 for (int i = 0; i < Size; ++i)
6897 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6898 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6899 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6900 if (!MaskBV || !ExpectedBV ||
6901 MaskBV->getOperand(Mask[i] % Size) !=
6902 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6909 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6911 /// This helper function produces an 8-bit shuffle immediate corresponding to
6912 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6913 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6916 /// NB: We rely heavily on "undef" masks preserving the input lane.
6917 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6918 SelectionDAG &DAG) {
6919 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6920 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6921 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6922 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6923 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6926 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6927 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6928 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6929 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6930 return DAG.getConstant(Imm, DL, MVT::i8);
6933 /// \brief Compute whether each element of a shuffle is zeroable.
6935 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6936 /// Either it is an undef element in the shuffle mask, the element of the input
6937 /// referenced is undef, or the element of the input referenced is known to be
6938 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6939 /// as many lanes with this technique as possible to simplify the remaining
6941 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6942 SDValue V1, SDValue V2) {
6943 SmallBitVector Zeroable(Mask.size(), false);
6945 while (V1.getOpcode() == ISD::BITCAST)
6946 V1 = V1->getOperand(0);
6947 while (V2.getOpcode() == ISD::BITCAST)
6948 V2 = V2->getOperand(0);
6950 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6951 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6953 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6955 // Handle the easy cases.
6956 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6961 // If this is an index into a build_vector node (which has the same number
6962 // of elements), dig out the input value and use it.
6963 SDValue V = M < Size ? V1 : V2;
6964 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6967 SDValue Input = V.getOperand(M % Size);
6968 // The UNDEF opcode check really should be dead code here, but not quite
6969 // worth asserting on (it isn't invalid, just unexpected).
6970 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6977 // X86 has dedicated unpack instructions that can handle specific blend
6978 // operations: UNPCKH and UNPCKL.
6979 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6980 SDValue V1, SDValue V2,
6981 SelectionDAG &DAG) {
6982 int NumElts = VT.getVectorNumElements();
6983 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6984 SmallVector<int, 8> Unpckl;
6985 SmallVector<int, 8> Unpckh;
6987 for (int i = 0; i < NumElts; ++i) {
6988 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6989 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6990 int HiPos = LoPos + NumEltsInLane / 2;
6991 Unpckl.push_back(LoPos);
6992 Unpckh.push_back(HiPos);
6995 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6996 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6997 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6998 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
7000 // Commute and try again.
7001 ShuffleVectorSDNode::commuteMask(Unpckl);
7002 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7003 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7005 ShuffleVectorSDNode::commuteMask(Unpckh);
7006 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7007 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7012 /// \brief Try to emit a bitmask instruction for a shuffle.
7014 /// This handles cases where we can model a blend exactly as a bitmask due to
7015 /// one of the inputs being zeroable.
7016 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7017 SDValue V2, ArrayRef<int> Mask,
7018 SelectionDAG &DAG) {
7019 MVT EltVT = VT.getVectorElementType();
7020 int NumEltBits = EltVT.getSizeInBits();
7021 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7022 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7023 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7025 if (EltVT.isFloatingPoint()) {
7026 Zero = DAG.getBitcast(EltVT, Zero);
7027 AllOnes = DAG.getBitcast(EltVT, AllOnes);
7029 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7030 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7032 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7035 if (Mask[i] % Size != i)
7036 return SDValue(); // Not a blend.
7038 V = Mask[i] < Size ? V1 : V2;
7039 else if (V != (Mask[i] < Size ? V1 : V2))
7040 return SDValue(); // Can only let one input through the mask.
7042 VMaskOps[i] = AllOnes;
7045 return SDValue(); // No non-zeroable elements!
7047 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7048 V = DAG.getNode(VT.isFloatingPoint()
7049 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7054 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7056 /// This is used as a fallback approach when first class blend instructions are
7057 /// unavailable. Currently it is only suitable for integer vectors, but could
7058 /// be generalized for floating point vectors if desirable.
7059 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7060 SDValue V2, ArrayRef<int> Mask,
7061 SelectionDAG &DAG) {
7062 assert(VT.isInteger() && "Only supports integer vector types!");
7063 MVT EltVT = VT.getVectorElementType();
7064 int NumEltBits = EltVT.getSizeInBits();
7065 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7066 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7068 SmallVector<SDValue, 16> MaskOps;
7069 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7070 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7071 return SDValue(); // Shuffled input!
7072 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7075 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7076 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7077 // We have to cast V2 around.
7078 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7079 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7080 DAG.getBitcast(MaskVT, V1Mask),
7081 DAG.getBitcast(MaskVT, V2)));
7082 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7085 /// \brief Try to emit a blend instruction for a shuffle.
7087 /// This doesn't do any checks for the availability of instructions for blending
7088 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7089 /// be matched in the backend with the type given. What it does check for is
7090 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7091 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7092 SDValue V2, ArrayRef<int> Original,
7093 const X86Subtarget *Subtarget,
7094 SelectionDAG &DAG) {
7095 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7096 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7097 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7098 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7099 bool ForceV1Zero = false, ForceV2Zero = false;
7101 // Attempt to generate the binary blend mask. If an input is zero then
7102 // we can use any lane.
7103 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7104 unsigned BlendMask = 0;
7105 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7111 if (M == i + Size) {
7112 BlendMask |= 1u << i;
7123 BlendMask |= 1u << i;
7128 return SDValue(); // Shuffled input!
7131 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7133 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7135 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7137 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7138 unsigned ScaledMask = 0;
7139 for (int i = 0; i != Size; ++i)
7140 if (BlendMask & (1u << i))
7141 for (int j = 0; j != Scale; ++j)
7142 ScaledMask |= 1u << (i * Scale + j);
7146 switch (VT.SimpleTy) {
7151 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7152 DAG.getConstant(BlendMask, DL, MVT::i8));
7156 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7160 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7161 // that instruction.
7162 if (Subtarget->hasAVX2()) {
7163 // Scale the blend by the number of 32-bit dwords per element.
7164 int Scale = VT.getScalarSizeInBits() / 32;
7165 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7166 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7167 V1 = DAG.getBitcast(BlendVT, V1);
7168 V2 = DAG.getBitcast(BlendVT, V2);
7169 return DAG.getBitcast(
7170 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7171 DAG.getConstant(BlendMask, DL, MVT::i8)));
7175 // For integer shuffles we need to expand the mask and cast the inputs to
7176 // v8i16s prior to blending.
7177 int Scale = 8 / VT.getVectorNumElements();
7178 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7179 V1 = DAG.getBitcast(MVT::v8i16, V1);
7180 V2 = DAG.getBitcast(MVT::v8i16, V2);
7181 return DAG.getBitcast(VT,
7182 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7183 DAG.getConstant(BlendMask, DL, MVT::i8)));
7187 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7188 SmallVector<int, 8> RepeatedMask;
7189 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7190 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7191 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7193 for (int i = 0; i < 8; ++i)
7194 if (RepeatedMask[i] >= 16)
7195 BlendMask |= 1u << i;
7196 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7197 DAG.getConstant(BlendMask, DL, MVT::i8));
7203 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7204 "256-bit byte-blends require AVX2 support!");
7206 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7207 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7210 // Scale the blend by the number of bytes per element.
7211 int Scale = VT.getScalarSizeInBits() / 8;
7213 // This form of blend is always done on bytes. Compute the byte vector
7215 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7217 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7218 // mix of LLVM's code generator and the x86 backend. We tell the code
7219 // generator that boolean values in the elements of an x86 vector register
7220 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7221 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7222 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7223 // of the element (the remaining are ignored) and 0 in that high bit would
7224 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7225 // the LLVM model for boolean values in vector elements gets the relevant
7226 // bit set, it is set backwards and over constrained relative to x86's
7228 SmallVector<SDValue, 32> VSELECTMask;
7229 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7230 for (int j = 0; j < Scale; ++j)
7231 VSELECTMask.push_back(
7232 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7233 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7236 V1 = DAG.getBitcast(BlendVT, V1);
7237 V2 = DAG.getBitcast(BlendVT, V2);
7238 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7239 DAG.getNode(ISD::BUILD_VECTOR, DL,
7240 BlendVT, VSELECTMask),
7245 llvm_unreachable("Not a supported integer vector type!");
7249 /// \brief Try to lower as a blend of elements from two inputs followed by
7250 /// a single-input permutation.
7252 /// This matches the pattern where we can blend elements from two inputs and
7253 /// then reduce the shuffle to a single-input permutation.
7254 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7257 SelectionDAG &DAG) {
7258 // We build up the blend mask while checking whether a blend is a viable way
7259 // to reduce the shuffle.
7260 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7261 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7263 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7267 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7269 if (BlendMask[Mask[i] % Size] == -1)
7270 BlendMask[Mask[i] % Size] = Mask[i];
7271 else if (BlendMask[Mask[i] % Size] != Mask[i])
7272 return SDValue(); // Can't blend in the needed input!
7274 PermuteMask[i] = Mask[i] % Size;
7277 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7278 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7281 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7282 /// blends and permutes.
7284 /// This matches the extremely common pattern for handling combined
7285 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7286 /// operations. It will try to pick the best arrangement of shuffles and
7288 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7292 SelectionDAG &DAG) {
7293 // Shuffle the input elements into the desired positions in V1 and V2 and
7294 // blend them together.
7295 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7296 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7297 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7298 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7299 if (Mask[i] >= 0 && Mask[i] < Size) {
7300 V1Mask[i] = Mask[i];
7302 } else if (Mask[i] >= Size) {
7303 V2Mask[i] = Mask[i] - Size;
7304 BlendMask[i] = i + Size;
7307 // Try to lower with the simpler initial blend strategy unless one of the
7308 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7309 // shuffle may be able to fold with a load or other benefit. However, when
7310 // we'll have to do 2x as many shuffles in order to achieve this, blending
7311 // first is a better strategy.
7312 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7313 if (SDValue BlendPerm =
7314 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7317 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7318 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7319 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7322 /// \brief Try to lower a vector shuffle as a byte rotation.
7324 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7325 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7326 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7327 /// try to generically lower a vector shuffle through such an pattern. It
7328 /// does not check for the profitability of lowering either as PALIGNR or
7329 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7330 /// This matches shuffle vectors that look like:
7332 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7334 /// Essentially it concatenates V1 and V2, shifts right by some number of
7335 /// elements, and takes the low elements as the result. Note that while this is
7336 /// specified as a *right shift* because x86 is little-endian, it is a *left
7337 /// rotate* of the vector lanes.
7338 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7341 const X86Subtarget *Subtarget,
7342 SelectionDAG &DAG) {
7343 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7345 int NumElts = Mask.size();
7346 int NumLanes = VT.getSizeInBits() / 128;
7347 int NumLaneElts = NumElts / NumLanes;
7349 // We need to detect various ways of spelling a rotation:
7350 // [11, 12, 13, 14, 15, 0, 1, 2]
7351 // [-1, 12, 13, 14, -1, -1, 1, -1]
7352 // [-1, -1, -1, -1, -1, -1, 1, 2]
7353 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7354 // [-1, 4, 5, 6, -1, -1, 9, -1]
7355 // [-1, 4, 5, 6, -1, -1, -1, -1]
7358 for (int l = 0; l < NumElts; l += NumLaneElts) {
7359 for (int i = 0; i < NumLaneElts; ++i) {
7360 if (Mask[l + i] == -1)
7362 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7364 // Get the mod-Size index and lane correct it.
7365 int LaneIdx = (Mask[l + i] % NumElts) - l;
7366 // Make sure it was in this lane.
7367 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7370 // Determine where a rotated vector would have started.
7371 int StartIdx = i - LaneIdx;
7373 // The identity rotation isn't interesting, stop.
7376 // If we found the tail of a vector the rotation must be the missing
7377 // front. If we found the head of a vector, it must be how much of the
7379 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7382 Rotation = CandidateRotation;
7383 else if (Rotation != CandidateRotation)
7384 // The rotations don't match, so we can't match this mask.
7387 // Compute which value this mask is pointing at.
7388 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7390 // Compute which of the two target values this index should be assigned
7391 // to. This reflects whether the high elements are remaining or the low
7392 // elements are remaining.
7393 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7395 // Either set up this value if we've not encountered it before, or check
7396 // that it remains consistent.
7399 else if (TargetV != MaskV)
7400 // This may be a rotation, but it pulls from the inputs in some
7401 // unsupported interleaving.
7406 // Check that we successfully analyzed the mask, and normalize the results.
7407 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7408 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7414 // The actual rotate instruction rotates bytes, so we need to scale the
7415 // rotation based on how many bytes are in the vector lane.
7416 int Scale = 16 / NumLaneElts;
7418 // SSSE3 targets can use the palignr instruction.
7419 if (Subtarget->hasSSSE3()) {
7420 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7421 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7422 Lo = DAG.getBitcast(AlignVT, Lo);
7423 Hi = DAG.getBitcast(AlignVT, Hi);
7425 return DAG.getBitcast(
7426 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7427 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7430 assert(VT.is128BitVector() &&
7431 "Rotate-based lowering only supports 128-bit lowering!");
7432 assert(Mask.size() <= 16 &&
7433 "Can shuffle at most 16 bytes in a 128-bit vector!");
7435 // Default SSE2 implementation
7436 int LoByteShift = 16 - Rotation * Scale;
7437 int HiByteShift = Rotation * Scale;
7439 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7440 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7441 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7443 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7444 DAG.getConstant(LoByteShift, DL, MVT::i8));
7445 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7446 DAG.getConstant(HiByteShift, DL, MVT::i8));
7447 return DAG.getBitcast(VT,
7448 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7451 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7453 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7454 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7455 /// matches elements from one of the input vectors shuffled to the left or
7456 /// right with zeroable elements 'shifted in'. It handles both the strictly
7457 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7460 /// PSHL : (little-endian) left bit shift.
7461 /// [ zz, 0, zz, 2 ]
7462 /// [ -1, 4, zz, -1 ]
7463 /// PSRL : (little-endian) right bit shift.
7465 /// [ -1, -1, 7, zz]
7466 /// PSLLDQ : (little-endian) left byte shift
7467 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7468 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7469 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7470 /// PSRLDQ : (little-endian) right byte shift
7471 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7472 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7473 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7474 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7475 SDValue V2, ArrayRef<int> Mask,
7476 SelectionDAG &DAG) {
7477 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7479 int Size = Mask.size();
7480 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7482 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7483 for (int i = 0; i < Size; i += Scale)
7484 for (int j = 0; j < Shift; ++j)
7485 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7491 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7492 for (int i = 0; i != Size; i += Scale) {
7493 unsigned Pos = Left ? i + Shift : i;
7494 unsigned Low = Left ? i : i + Shift;
7495 unsigned Len = Scale - Shift;
7496 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7497 Low + (V == V1 ? 0 : Size)))
7501 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7502 bool ByteShift = ShiftEltBits > 64;
7503 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7504 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7505 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7507 // Normalize the scale for byte shifts to still produce an i64 element
7509 Scale = ByteShift ? Scale / 2 : Scale;
7511 // We need to round trip through the appropriate type for the shift.
7512 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7513 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7514 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7515 "Illegal integer vector type");
7516 V = DAG.getBitcast(ShiftVT, V);
7518 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7519 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7520 return DAG.getBitcast(VT, V);
7523 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7524 // keep doubling the size of the integer elements up to that. We can
7525 // then shift the elements of the integer vector by whole multiples of
7526 // their width within the elements of the larger integer vector. Test each
7527 // multiple to see if we can find a match with the moved element indices
7528 // and that the shifted in elements are all zeroable.
7529 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7530 for (int Shift = 1; Shift != Scale; ++Shift)
7531 for (bool Left : {true, false})
7532 if (CheckZeros(Shift, Scale, Left))
7533 for (SDValue V : {V1, V2})
7534 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7541 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7542 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7543 SDValue V2, ArrayRef<int> Mask,
7544 SelectionDAG &DAG) {
7545 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7546 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7548 int Size = Mask.size();
7549 int HalfSize = Size / 2;
7550 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7552 // Upper half must be undefined.
7553 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7556 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7557 // Remainder of lower half result is zero and upper half is all undef.
7558 auto LowerAsEXTRQ = [&]() {
7559 // Determine the extraction length from the part of the
7560 // lower half that isn't zeroable.
7562 for (; Len > 0; --Len)
7563 if (!Zeroable[Len - 1])
7565 assert(Len > 0 && "Zeroable shuffle mask");
7567 // Attempt to match first Len sequential elements from the lower half.
7570 for (int i = 0; i != Len; ++i) {
7574 SDValue &V = (M < Size ? V1 : V2);
7577 // The extracted elements must start at a valid index and all mask
7578 // elements must be in the lower half.
7579 if (i > M || M >= HalfSize)
7582 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7593 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7594 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7595 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7596 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7597 DAG.getConstant(BitLen, DL, MVT::i8),
7598 DAG.getConstant(BitIdx, DL, MVT::i8));
7601 if (SDValue ExtrQ = LowerAsEXTRQ())
7604 // INSERTQ: Extract lowest Len elements from lower half of second source and
7605 // insert over first source, starting at Idx.
7606 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7607 auto LowerAsInsertQ = [&]() {
7608 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7611 // Attempt to match first source from mask before insertion point.
7612 if (isUndefInRange(Mask, 0, Idx)) {
7614 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7616 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7622 // Extend the extraction length looking to match both the insertion of
7623 // the second source and the remaining elements of the first.
7624 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7629 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7631 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7637 // Match the remaining elements of the lower half.
7638 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7640 } else if ((!Base || (Base == V1)) &&
7641 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7643 } else if ((!Base || (Base == V2)) &&
7644 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7651 // We may not have a base (first source) - this can safely be undefined.
7653 Base = DAG.getUNDEF(VT);
7655 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7656 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7657 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7658 DAG.getConstant(BitLen, DL, MVT::i8),
7659 DAG.getConstant(BitIdx, DL, MVT::i8));
7666 if (SDValue InsertQ = LowerAsInsertQ())
7672 /// \brief Lower a vector shuffle as a zero or any extension.
7674 /// Given a specific number of elements, element bit width, and extension
7675 /// stride, produce either a zero or any extension based on the available
7676 /// features of the subtarget. The extended elements are consecutive and
7677 /// begin and can start from an offseted element index in the input; to
7678 /// avoid excess shuffling the offset must either being in the bottom lane
7679 /// or at the start of a higher lane. All extended elements must be from
7681 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7682 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7683 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7684 assert(Scale > 1 && "Need a scale to extend.");
7685 int EltBits = VT.getScalarSizeInBits();
7686 int NumElements = VT.getVectorNumElements();
7687 int NumEltsPerLane = 128 / EltBits;
7688 int OffsetLane = Offset / NumEltsPerLane;
7689 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7690 "Only 8, 16, and 32 bit elements can be extended.");
7691 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7692 assert(0 <= Offset && "Extension offset must be positive.");
7693 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7694 "Extension offset must be in the first lane or start an upper lane.");
7696 // Check that an index is in same lane as the base offset.
7697 auto SafeOffset = [&](int Idx) {
7698 return OffsetLane == (Idx / NumEltsPerLane);
7701 // Shift along an input so that the offset base moves to the first element.
7702 auto ShuffleOffset = [&](SDValue V) {
7706 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7707 for (int i = 0; i * Scale < NumElements; ++i) {
7708 int SrcIdx = i + Offset;
7709 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7711 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7714 // Found a valid zext mask! Try various lowering strategies based on the
7715 // input type and available ISA extensions.
7716 if (Subtarget->hasSSE41()) {
7717 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7718 // PUNPCK will catch this in a later shuffle match.
7719 if (Offset && Scale == 2 && VT.is128BitVector())
7721 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7722 NumElements / Scale);
7723 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7724 return DAG.getBitcast(VT, InputV);
7727 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7729 // For any extends we can cheat for larger element sizes and use shuffle
7730 // instructions that can fold with a load and/or copy.
7731 if (AnyExt && EltBits == 32) {
7732 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7734 return DAG.getBitcast(
7735 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7736 DAG.getBitcast(MVT::v4i32, InputV),
7737 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7739 if (AnyExt && EltBits == 16 && Scale > 2) {
7740 int PSHUFDMask[4] = {Offset / 2, -1,
7741 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7742 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7743 DAG.getBitcast(MVT::v4i32, InputV),
7744 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7745 int PSHUFWMask[4] = {1, -1, -1, -1};
7746 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7747 return DAG.getBitcast(
7748 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7749 DAG.getBitcast(MVT::v8i16, InputV),
7750 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7753 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7755 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7756 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7757 assert(VT.is128BitVector() && "Unexpected vector width!");
7759 int LoIdx = Offset * EltBits;
7760 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7761 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7762 DAG.getConstant(EltBits, DL, MVT::i8),
7763 DAG.getConstant(LoIdx, DL, MVT::i8)));
7765 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7766 !SafeOffset(Offset + 1))
7767 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7769 int HiIdx = (Offset + 1) * EltBits;
7770 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7771 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7772 DAG.getConstant(EltBits, DL, MVT::i8),
7773 DAG.getConstant(HiIdx, DL, MVT::i8)));
7774 return DAG.getNode(ISD::BITCAST, DL, VT,
7775 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7778 // If this would require more than 2 unpack instructions to expand, use
7779 // pshufb when available. We can only use more than 2 unpack instructions
7780 // when zero extending i8 elements which also makes it easier to use pshufb.
7781 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7782 assert(NumElements == 16 && "Unexpected byte vector width!");
7783 SDValue PSHUFBMask[16];
7784 for (int i = 0; i < 16; ++i) {
7785 int Idx = Offset + (i / Scale);
7786 PSHUFBMask[i] = DAG.getConstant(
7787 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7789 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7790 return DAG.getBitcast(VT,
7791 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7792 DAG.getNode(ISD::BUILD_VECTOR, DL,
7793 MVT::v16i8, PSHUFBMask)));
7796 // If we are extending from an offset, ensure we start on a boundary that
7797 // we can unpack from.
7798 int AlignToUnpack = Offset % (NumElements / Scale);
7799 if (AlignToUnpack) {
7800 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7801 for (int i = AlignToUnpack; i < NumElements; ++i)
7802 ShMask[i - AlignToUnpack] = i;
7803 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7804 Offset -= AlignToUnpack;
7807 // Otherwise emit a sequence of unpacks.
7809 unsigned UnpackLoHi = X86ISD::UNPCKL;
7810 if (Offset >= (NumElements / 2)) {
7811 UnpackLoHi = X86ISD::UNPCKH;
7812 Offset -= (NumElements / 2);
7815 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7816 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7817 : getZeroVector(InputVT, Subtarget, DAG, DL);
7818 InputV = DAG.getBitcast(InputVT, InputV);
7819 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7823 } while (Scale > 1);
7824 return DAG.getBitcast(VT, InputV);
7827 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7829 /// This routine will try to do everything in its power to cleverly lower
7830 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7831 /// check for the profitability of this lowering, it tries to aggressively
7832 /// match this pattern. It will use all of the micro-architectural details it
7833 /// can to emit an efficient lowering. It handles both blends with all-zero
7834 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7835 /// masking out later).
7837 /// The reason we have dedicated lowering for zext-style shuffles is that they
7838 /// are both incredibly common and often quite performance sensitive.
7839 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7840 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7841 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7842 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7844 int Bits = VT.getSizeInBits();
7845 int NumLanes = Bits / 128;
7846 int NumElements = VT.getVectorNumElements();
7847 int NumEltsPerLane = NumElements / NumLanes;
7848 assert(VT.getScalarSizeInBits() <= 32 &&
7849 "Exceeds 32-bit integer zero extension limit");
7850 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7852 // Define a helper function to check a particular ext-scale and lower to it if
7854 auto Lower = [&](int Scale) -> SDValue {
7859 for (int i = 0; i < NumElements; ++i) {
7862 continue; // Valid anywhere but doesn't tell us anything.
7863 if (i % Scale != 0) {
7864 // Each of the extended elements need to be zeroable.
7868 // We no longer are in the anyext case.
7873 // Each of the base elements needs to be consecutive indices into the
7874 // same input vector.
7875 SDValue V = M < NumElements ? V1 : V2;
7876 M = M % NumElements;
7879 Offset = M - (i / Scale);
7880 } else if (InputV != V)
7881 return SDValue(); // Flip-flopping inputs.
7883 // Offset must start in the lowest 128-bit lane or at the start of an
7885 // FIXME: Is it ever worth allowing a negative base offset?
7886 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7887 (Offset % NumEltsPerLane) == 0))
7890 // If we are offsetting, all referenced entries must come from the same
7892 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7895 if ((M % NumElements) != (Offset + (i / Scale)))
7896 return SDValue(); // Non-consecutive strided elements.
7900 // If we fail to find an input, we have a zero-shuffle which should always
7901 // have already been handled.
7902 // FIXME: Maybe handle this here in case during blending we end up with one?
7906 // If we are offsetting, don't extend if we only match a single input, we
7907 // can always do better by using a basic PSHUF or PUNPCK.
7908 if (Offset != 0 && Matches < 2)
7911 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7912 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7915 // The widest scale possible for extending is to a 64-bit integer.
7916 assert(Bits % 64 == 0 &&
7917 "The number of bits in a vector must be divisible by 64 on x86!");
7918 int NumExtElements = Bits / 64;
7920 // Each iteration, try extending the elements half as much, but into twice as
7922 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7923 assert(NumElements % NumExtElements == 0 &&
7924 "The input vector size must be divisible by the extended size.");
7925 if (SDValue V = Lower(NumElements / NumExtElements))
7929 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7933 // Returns one of the source operands if the shuffle can be reduced to a
7934 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7935 auto CanZExtLowHalf = [&]() {
7936 for (int i = NumElements / 2; i != NumElements; ++i)
7939 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7941 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7946 if (SDValue V = CanZExtLowHalf()) {
7947 V = DAG.getBitcast(MVT::v2i64, V);
7948 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7949 return DAG.getBitcast(VT, V);
7952 // No viable ext lowering found.
7956 /// \brief Try to get a scalar value for a specific element of a vector.
7958 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7959 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7960 SelectionDAG &DAG) {
7961 MVT VT = V.getSimpleValueType();
7962 MVT EltVT = VT.getVectorElementType();
7963 while (V.getOpcode() == ISD::BITCAST)
7964 V = V.getOperand(0);
7965 // If the bitcasts shift the element size, we can't extract an equivalent
7967 MVT NewVT = V.getSimpleValueType();
7968 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7971 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7972 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7973 // Ensure the scalar operand is the same size as the destination.
7974 // FIXME: Add support for scalar truncation where possible.
7975 SDValue S = V.getOperand(Idx);
7976 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7977 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7983 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7985 /// This is particularly important because the set of instructions varies
7986 /// significantly based on whether the operand is a load or not.
7987 static bool isShuffleFoldableLoad(SDValue V) {
7988 while (V.getOpcode() == ISD::BITCAST)
7989 V = V.getOperand(0);
7991 return ISD::isNON_EXTLoad(V.getNode());
7994 /// \brief Try to lower insertion of a single element into a zero vector.
7996 /// This is a common pattern that we have especially efficient patterns to lower
7997 /// across all subtarget feature sets.
7998 static SDValue lowerVectorShuffleAsElementInsertion(
7999 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8000 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8001 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8003 MVT EltVT = VT.getVectorElementType();
8005 int V2Index = std::find_if(Mask.begin(), Mask.end(),
8006 [&Mask](int M) { return M >= (int)Mask.size(); }) -
8008 bool IsV1Zeroable = true;
8009 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8010 if (i != V2Index && !Zeroable[i]) {
8011 IsV1Zeroable = false;
8015 // Check for a single input from a SCALAR_TO_VECTOR node.
8016 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8017 // all the smarts here sunk into that routine. However, the current
8018 // lowering of BUILD_VECTOR makes that nearly impossible until the old
8019 // vector shuffle lowering is dead.
8020 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8022 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8023 // We need to zext the scalar if it is smaller than an i32.
8024 V2S = DAG.getBitcast(EltVT, V2S);
8025 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8026 // Using zext to expand a narrow element won't work for non-zero
8031 // Zero-extend directly to i32.
8033 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8035 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8036 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8037 EltVT == MVT::i16) {
8038 // Either not inserting from the low element of the input or the input
8039 // element size is too small to use VZEXT_MOVL to clear the high bits.
8043 if (!IsV1Zeroable) {
8044 // If V1 can't be treated as a zero vector we have fewer options to lower
8045 // this. We can't support integer vectors or non-zero targets cheaply, and
8046 // the V1 elements can't be permuted in any way.
8047 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8048 if (!VT.isFloatingPoint() || V2Index != 0)
8050 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8051 V1Mask[V2Index] = -1;
8052 if (!isNoopShuffleMask(V1Mask))
8054 // This is essentially a special case blend operation, but if we have
8055 // general purpose blend operations, they are always faster. Bail and let
8056 // the rest of the lowering handle these as blends.
8057 if (Subtarget->hasSSE41())
8060 // Otherwise, use MOVSD or MOVSS.
8061 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8062 "Only two types of floating point element types to handle!");
8063 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8067 // This lowering only works for the low element with floating point vectors.
8068 if (VT.isFloatingPoint() && V2Index != 0)
8071 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8073 V2 = DAG.getBitcast(VT, V2);
8076 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8077 // the desired position. Otherwise it is more efficient to do a vector
8078 // shift left. We know that we can do a vector shift left because all
8079 // the inputs are zero.
8080 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8081 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8082 V2Shuffle[V2Index] = 0;
8083 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8085 V2 = DAG.getBitcast(MVT::v2i64, V2);
8087 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8088 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8089 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8090 DAG.getDataLayout(), VT)));
8091 V2 = DAG.getBitcast(VT, V2);
8097 /// \brief Try to lower broadcast of a single - truncated - integer element,
8098 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8100 /// This assumes we have AVX2.
8101 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8103 const X86Subtarget *Subtarget,
8104 SelectionDAG &DAG) {
8105 assert(Subtarget->hasAVX2() &&
8106 "We can only lower integer broadcasts with AVX2!");
8108 EVT EltVT = VT.getVectorElementType();
8109 EVT V0VT = V0.getValueType();
8111 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8112 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8114 EVT V0EltVT = V0VT.getVectorElementType();
8115 if (!V0EltVT.isInteger())
8118 const unsigned EltSize = EltVT.getSizeInBits();
8119 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8121 // This is only a truncation if the original element type is larger.
8122 if (V0EltSize <= EltSize)
8125 assert(((V0EltSize % EltSize) == 0) &&
8126 "Scalar type sizes must all be powers of 2 on x86!");
8128 const unsigned V0Opc = V0.getOpcode();
8129 const unsigned Scale = V0EltSize / EltSize;
8130 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8132 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8133 V0Opc != ISD::BUILD_VECTOR)
8136 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8138 // If we're extracting non-least-significant bits, shift so we can truncate.
8139 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8140 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8141 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8142 if (const int OffsetIdx = BroadcastIdx % Scale)
8143 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8144 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8146 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8147 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8150 /// \brief Try to lower broadcast of a single element.
8152 /// For convenience, this code also bundles all of the subtarget feature set
8153 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8154 /// a convenient way to factor it out.
8155 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8156 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8158 const X86Subtarget *Subtarget,
8159 SelectionDAG &DAG) {
8160 if (!Subtarget->hasAVX())
8162 if (VT.isInteger() && !Subtarget->hasAVX2())
8165 // Check that the mask is a broadcast.
8166 int BroadcastIdx = -1;
8168 if (M >= 0 && BroadcastIdx == -1)
8170 else if (M >= 0 && M != BroadcastIdx)
8173 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8174 "a sorted mask where the broadcast "
8177 // Go up the chain of (vector) values to find a scalar load that we can
8178 // combine with the broadcast.
8180 switch (V.getOpcode()) {
8181 case ISD::CONCAT_VECTORS: {
8182 int OperandSize = Mask.size() / V.getNumOperands();
8183 V = V.getOperand(BroadcastIdx / OperandSize);
8184 BroadcastIdx %= OperandSize;
8188 case ISD::INSERT_SUBVECTOR: {
8189 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8190 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8194 int BeginIdx = (int)ConstantIdx->getZExtValue();
8196 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8197 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8198 BroadcastIdx -= BeginIdx;
8209 // Check if this is a broadcast of a scalar. We special case lowering
8210 // for scalars so that we can more effectively fold with loads.
8211 // First, look through bitcast: if the original value has a larger element
8212 // type than the shuffle, the broadcast element is in essence truncated.
8213 // Make that explicit to ease folding.
8214 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8215 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8216 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8217 return TruncBroadcast;
8219 MVT BroadcastVT = VT;
8221 // Peek through any bitcast (only useful for loads).
8223 while (BC.getOpcode() == ISD::BITCAST)
8224 BC = BC.getOperand(0);
8226 // Also check the simpler case, where we can directly reuse the scalar.
8227 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8228 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8229 V = V.getOperand(BroadcastIdx);
8231 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8232 // Only AVX2 has register broadcasts.
8233 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8235 } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8236 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8237 if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8238 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8240 // If we are broadcasting a load that is only used by the shuffle
8241 // then we can reduce the vector load to the broadcasted scalar load.
8242 LoadSDNode *Ld = cast<LoadSDNode>(BC);
8243 SDValue BaseAddr = Ld->getOperand(1);
8244 EVT AddrVT = BaseAddr.getValueType();
8245 EVT SVT = BroadcastVT.getScalarType();
8246 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8247 SDValue NewAddr = DAG.getNode(
8248 ISD::ADD, DL, AddrVT, BaseAddr,
8249 DAG.getConstant(Offset, DL, AddrVT));
8250 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8251 DAG.getMachineFunction().getMachineMemOperand(
8252 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8253 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8254 // We can't broadcast from a vector register without AVX2, and we can only
8255 // broadcast from the zero-element of a vector register.
8259 V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8260 return DAG.getBitcast(VT, V);
8263 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8264 // INSERTPS when the V1 elements are already in the correct locations
8265 // because otherwise we can just always use two SHUFPS instructions which
8266 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8267 // perform INSERTPS if a single V1 element is out of place and all V2
8268 // elements are zeroable.
8269 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8271 SelectionDAG &DAG) {
8272 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8273 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8274 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8275 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8277 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8280 int V1DstIndex = -1;
8281 int V2DstIndex = -1;
8282 bool V1UsedInPlace = false;
8284 for (int i = 0; i < 4; ++i) {
8285 // Synthesize a zero mask from the zeroable elements (includes undefs).
8291 // Flag if we use any V1 inputs in place.
8293 V1UsedInPlace = true;
8297 // We can only insert a single non-zeroable element.
8298 if (V1DstIndex != -1 || V2DstIndex != -1)
8302 // V1 input out of place for insertion.
8305 // V2 input for insertion.
8310 // Don't bother if we have no (non-zeroable) element for insertion.
8311 if (V1DstIndex == -1 && V2DstIndex == -1)
8314 // Determine element insertion src/dst indices. The src index is from the
8315 // start of the inserted vector, not the start of the concatenated vector.
8316 unsigned V2SrcIndex = 0;
8317 if (V1DstIndex != -1) {
8318 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8319 // and don't use the original V2 at all.
8320 V2SrcIndex = Mask[V1DstIndex];
8321 V2DstIndex = V1DstIndex;
8324 V2SrcIndex = Mask[V2DstIndex] - 4;
8327 // If no V1 inputs are used in place, then the result is created only from
8328 // the zero mask and the V2 insertion - so remove V1 dependency.
8330 V1 = DAG.getUNDEF(MVT::v4f32);
8332 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8333 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8335 // Insert the V2 element into the desired position.
8337 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8338 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8341 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8342 /// UNPCK instruction.
8344 /// This specifically targets cases where we end up with alternating between
8345 /// the two inputs, and so can permute them into something that feeds a single
8346 /// UNPCK instruction. Note that this routine only targets integer vectors
8347 /// because for floating point vectors we have a generalized SHUFPS lowering
8348 /// strategy that handles everything that doesn't *exactly* match an unpack,
8349 /// making this clever lowering unnecessary.
8350 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8351 SDValue V1, SDValue V2,
8353 SelectionDAG &DAG) {
8354 assert(!VT.isFloatingPoint() &&
8355 "This routine only supports integer vectors.");
8356 assert(!isSingleInputShuffleMask(Mask) &&
8357 "This routine should only be used when blending two inputs.");
8358 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8360 int Size = Mask.size();
8362 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8363 return M >= 0 && M % Size < Size / 2;
8365 int NumHiInputs = std::count_if(
8366 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8368 bool UnpackLo = NumLoInputs >= NumHiInputs;
8370 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8371 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8372 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8374 for (int i = 0; i < Size; ++i) {
8378 // Each element of the unpack contains Scale elements from this mask.
8379 int UnpackIdx = i / Scale;
8381 // We only handle the case where V1 feeds the first slots of the unpack.
8382 // We rely on canonicalization to ensure this is the case.
8383 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8386 // Setup the mask for this input. The indexing is tricky as we have to
8387 // handle the unpack stride.
8388 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8389 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8393 // If we will have to shuffle both inputs to use the unpack, check whether
8394 // we can just unpack first and shuffle the result. If so, skip this unpack.
8395 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8396 !isNoopShuffleMask(V2Mask))
8399 // Shuffle the inputs into place.
8400 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8401 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8403 // Cast the inputs to the type we will use to unpack them.
8404 V1 = DAG.getBitcast(UnpackVT, V1);
8405 V2 = DAG.getBitcast(UnpackVT, V2);
8407 // Unpack the inputs and cast the result back to the desired type.
8408 return DAG.getBitcast(
8409 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8413 // We try each unpack from the largest to the smallest to try and find one
8414 // that fits this mask.
8415 int OrigNumElements = VT.getVectorNumElements();
8416 int OrigScalarSize = VT.getScalarSizeInBits();
8417 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8418 int Scale = ScalarSize / OrigScalarSize;
8419 int NumElements = OrigNumElements / Scale;
8420 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8421 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8425 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8427 if (NumLoInputs == 0 || NumHiInputs == 0) {
8428 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8429 "We have to have *some* inputs!");
8430 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8432 // FIXME: We could consider the total complexity of the permute of each
8433 // possible unpacking. Or at the least we should consider how many
8434 // half-crossings are created.
8435 // FIXME: We could consider commuting the unpacks.
8437 SmallVector<int, 32> PermMask;
8438 PermMask.assign(Size, -1);
8439 for (int i = 0; i < Size; ++i) {
8443 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8446 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8448 return DAG.getVectorShuffle(
8449 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8451 DAG.getUNDEF(VT), PermMask);
8457 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8459 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8460 /// support for floating point shuffles but not integer shuffles. These
8461 /// instructions will incur a domain crossing penalty on some chips though so
8462 /// it is better to avoid lowering through this for integer vectors where
8464 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8465 const X86Subtarget *Subtarget,
8466 SelectionDAG &DAG) {
8468 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8469 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8470 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8471 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8472 ArrayRef<int> Mask = SVOp->getMask();
8473 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8475 if (isSingleInputShuffleMask(Mask)) {
8476 // Use low duplicate instructions for masks that match their pattern.
8477 if (Subtarget->hasSSE3())
8478 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8479 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8481 // Straight shuffle of a single input vector. Simulate this by using the
8482 // single input as both of the "inputs" to this instruction..
8483 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8485 if (Subtarget->hasAVX()) {
8486 // If we have AVX, we can use VPERMILPS which will allow folding a load
8487 // into the shuffle.
8488 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8489 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8492 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8493 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8495 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8496 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8498 // If we have a single input, insert that into V1 if we can do so cheaply.
8499 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8500 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8501 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8503 // Try inverting the insertion since for v2 masks it is easy to do and we
8504 // can't reliably sort the mask one way or the other.
8505 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8506 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8507 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8508 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8512 // Try to use one of the special instruction patterns to handle two common
8513 // blend patterns if a zero-blend above didn't work.
8514 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8515 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8516 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8517 // We can either use a special instruction to load over the low double or
8518 // to move just the low double.
8520 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8522 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8524 if (Subtarget->hasSSE41())
8525 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8529 // Use dedicated unpack instructions for masks that match their pattern.
8531 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8534 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8535 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8536 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8539 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8541 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8542 /// the integer unit to minimize domain crossing penalties. However, for blends
8543 /// it falls back to the floating point shuffle operation with appropriate bit
8545 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8546 const X86Subtarget *Subtarget,
8547 SelectionDAG &DAG) {
8549 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8550 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8551 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8552 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8553 ArrayRef<int> Mask = SVOp->getMask();
8554 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8556 if (isSingleInputShuffleMask(Mask)) {
8557 // Check for being able to broadcast a single element.
8558 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8559 Mask, Subtarget, DAG))
8562 // Straight shuffle of a single input vector. For everything from SSE2
8563 // onward this has a single fast instruction with no scary immediates.
8564 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8565 V1 = DAG.getBitcast(MVT::v4i32, V1);
8566 int WidenedMask[4] = {
8567 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8568 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8569 return DAG.getBitcast(
8571 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8572 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8574 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8575 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8576 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8577 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8579 // If we have a blend of two PACKUS operations an the blend aligns with the
8580 // low and half halves, we can just merge the PACKUS operations. This is
8581 // particularly important as it lets us merge shuffles that this routine itself
8583 auto GetPackNode = [](SDValue V) {
8584 while (V.getOpcode() == ISD::BITCAST)
8585 V = V.getOperand(0);
8587 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8589 if (SDValue V1Pack = GetPackNode(V1))
8590 if (SDValue V2Pack = GetPackNode(V2))
8591 return DAG.getBitcast(MVT::v2i64,
8592 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8593 Mask[0] == 0 ? V1Pack.getOperand(0)
8594 : V1Pack.getOperand(1),
8595 Mask[1] == 2 ? V2Pack.getOperand(0)
8596 : V2Pack.getOperand(1)));
8598 // Try to use shift instructions.
8600 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8603 // When loading a scalar and then shuffling it into a vector we can often do
8604 // the insertion cheaply.
8605 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8606 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8608 // Try inverting the insertion since for v2 masks it is easy to do and we
8609 // can't reliably sort the mask one way or the other.
8610 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8611 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8612 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8615 // We have different paths for blend lowering, but they all must use the
8616 // *exact* same predicate.
8617 bool IsBlendSupported = Subtarget->hasSSE41();
8618 if (IsBlendSupported)
8619 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8623 // Use dedicated unpack instructions for masks that match their pattern.
8625 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8628 // Try to use byte rotation instructions.
8629 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8630 if (Subtarget->hasSSSE3())
8631 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8632 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8635 // If we have direct support for blends, we should lower by decomposing into
8636 // a permute. That will be faster than the domain cross.
8637 if (IsBlendSupported)
8638 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8641 // We implement this with SHUFPD which is pretty lame because it will likely
8642 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8643 // However, all the alternatives are still more cycles and newer chips don't
8644 // have this problem. It would be really nice if x86 had better shuffles here.
8645 V1 = DAG.getBitcast(MVT::v2f64, V1);
8646 V2 = DAG.getBitcast(MVT::v2f64, V2);
8647 return DAG.getBitcast(MVT::v2i64,
8648 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8651 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8653 /// This is used to disable more specialized lowerings when the shufps lowering
8654 /// will happen to be efficient.
8655 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8656 // This routine only handles 128-bit shufps.
8657 assert(Mask.size() == 4 && "Unsupported mask size!");
8659 // To lower with a single SHUFPS we need to have the low half and high half
8660 // each requiring a single input.
8661 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8663 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8669 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8671 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8672 /// It makes no assumptions about whether this is the *best* lowering, it simply
8674 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8675 ArrayRef<int> Mask, SDValue V1,
8676 SDValue V2, SelectionDAG &DAG) {
8677 SDValue LowV = V1, HighV = V2;
8678 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8681 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8683 if (NumV2Elements == 1) {
8685 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8688 // Compute the index adjacent to V2Index and in the same half by toggling
8690 int V2AdjIndex = V2Index ^ 1;
8692 if (Mask[V2AdjIndex] == -1) {
8693 // Handles all the cases where we have a single V2 element and an undef.
8694 // This will only ever happen in the high lanes because we commute the
8695 // vector otherwise.
8697 std::swap(LowV, HighV);
8698 NewMask[V2Index] -= 4;
8700 // Handle the case where the V2 element ends up adjacent to a V1 element.
8701 // To make this work, blend them together as the first step.
8702 int V1Index = V2AdjIndex;
8703 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8704 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8705 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8707 // Now proceed to reconstruct the final blend as we have the necessary
8708 // high or low half formed.
8715 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8716 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8718 } else if (NumV2Elements == 2) {
8719 if (Mask[0] < 4 && Mask[1] < 4) {
8720 // Handle the easy case where we have V1 in the low lanes and V2 in the
8724 } else if (Mask[2] < 4 && Mask[3] < 4) {
8725 // We also handle the reversed case because this utility may get called
8726 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8727 // arrange things in the right direction.
8733 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8734 // trying to place elements directly, just blend them and set up the final
8735 // shuffle to place them.
8737 // The first two blend mask elements are for V1, the second two are for
8739 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8740 Mask[2] < 4 ? Mask[2] : Mask[3],
8741 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8742 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8743 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8744 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8746 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8749 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8750 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8751 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8752 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8755 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8756 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8759 /// \brief Lower 4-lane 32-bit floating point shuffles.
8761 /// Uses instructions exclusively from the floating point unit to minimize
8762 /// domain crossing penalties, as these are sufficient to implement all v4f32
8764 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8765 const X86Subtarget *Subtarget,
8766 SelectionDAG &DAG) {
8768 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8769 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8770 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8772 ArrayRef<int> Mask = SVOp->getMask();
8773 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8776 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8778 if (NumV2Elements == 0) {
8779 // Check for being able to broadcast a single element.
8780 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8781 Mask, Subtarget, DAG))
8784 // Use even/odd duplicate instructions for masks that match their pattern.
8785 if (Subtarget->hasSSE3()) {
8786 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8787 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8788 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8789 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8792 if (Subtarget->hasAVX()) {
8793 // If we have AVX, we can use VPERMILPS which will allow folding a load
8794 // into the shuffle.
8795 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8796 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8799 // Otherwise, use a straight shuffle of a single input vector. We pass the
8800 // input vector to both operands to simulate this with a SHUFPS.
8801 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8802 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8805 // There are special ways we can lower some single-element blends. However, we
8806 // have custom ways we can lower more complex single-element blends below that
8807 // we defer to if both this and BLENDPS fail to match, so restrict this to
8808 // when the V2 input is targeting element 0 of the mask -- that is the fast
8810 if (NumV2Elements == 1 && Mask[0] >= 4)
8811 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8812 Mask, Subtarget, DAG))
8815 if (Subtarget->hasSSE41()) {
8816 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8820 // Use INSERTPS if we can complete the shuffle efficiently.
8821 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8824 if (!isSingleSHUFPSMask(Mask))
8825 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8826 DL, MVT::v4f32, V1, V2, Mask, DAG))
8830 // Use dedicated unpack instructions for masks that match their pattern.
8832 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8835 // Otherwise fall back to a SHUFPS lowering strategy.
8836 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8839 /// \brief Lower 4-lane i32 vector shuffles.
8841 /// We try to handle these with integer-domain shuffles where we can, but for
8842 /// blends we use the floating point domain blend instructions.
8843 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8844 const X86Subtarget *Subtarget,
8845 SelectionDAG &DAG) {
8847 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8848 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8849 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8850 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8851 ArrayRef<int> Mask = SVOp->getMask();
8852 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8854 // Whenever we can lower this as a zext, that instruction is strictly faster
8855 // than any alternative. It also allows us to fold memory operands into the
8856 // shuffle in many cases.
8857 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8858 Mask, Subtarget, DAG))
8862 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8864 if (NumV2Elements == 0) {
8865 // Check for being able to broadcast a single element.
8866 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8867 Mask, Subtarget, DAG))
8870 // Straight shuffle of a single input vector. For everything from SSE2
8871 // onward this has a single fast instruction with no scary immediates.
8872 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8873 // but we aren't actually going to use the UNPCK instruction because doing
8874 // so prevents folding a load into this instruction or making a copy.
8875 const int UnpackLoMask[] = {0, 0, 1, 1};
8876 const int UnpackHiMask[] = {2, 2, 3, 3};
8877 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8878 Mask = UnpackLoMask;
8879 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8880 Mask = UnpackHiMask;
8882 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8883 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8886 // Try to use shift instructions.
8888 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8891 // There are special ways we can lower some single-element blends.
8892 if (NumV2Elements == 1)
8893 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8894 Mask, Subtarget, DAG))
8897 // We have different paths for blend lowering, but they all must use the
8898 // *exact* same predicate.
8899 bool IsBlendSupported = Subtarget->hasSSE41();
8900 if (IsBlendSupported)
8901 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8905 if (SDValue Masked =
8906 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8909 // Use dedicated unpack instructions for masks that match their pattern.
8911 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8914 // Try to use byte rotation instructions.
8915 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8916 if (Subtarget->hasSSSE3())
8917 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8918 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8921 // If we have direct support for blends, we should lower by decomposing into
8922 // a permute. That will be faster than the domain cross.
8923 if (IsBlendSupported)
8924 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8927 // Try to lower by permuting the inputs into an unpack instruction.
8928 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8932 // We implement this with SHUFPS because it can blend from two vectors.
8933 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8934 // up the inputs, bypassing domain shift penalties that we would encur if we
8935 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8937 return DAG.getBitcast(
8939 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8940 DAG.getBitcast(MVT::v4f32, V2), Mask));
8943 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8944 /// shuffle lowering, and the most complex part.
8946 /// The lowering strategy is to try to form pairs of input lanes which are
8947 /// targeted at the same half of the final vector, and then use a dword shuffle
8948 /// to place them onto the right half, and finally unpack the paired lanes into
8949 /// their final position.
8951 /// The exact breakdown of how to form these dword pairs and align them on the
8952 /// correct sides is really tricky. See the comments within the function for
8953 /// more of the details.
8955 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8956 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8957 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8958 /// vector, form the analogous 128-bit 8-element Mask.
8959 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8960 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8961 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8962 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8963 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8965 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8966 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8967 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8969 SmallVector<int, 4> LoInputs;
8970 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8971 [](int M) { return M >= 0; });
8972 std::sort(LoInputs.begin(), LoInputs.end());
8973 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8974 SmallVector<int, 4> HiInputs;
8975 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8976 [](int M) { return M >= 0; });
8977 std::sort(HiInputs.begin(), HiInputs.end());
8978 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8980 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8981 int NumHToL = LoInputs.size() - NumLToL;
8983 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8984 int NumHToH = HiInputs.size() - NumLToH;
8985 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8986 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8987 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8988 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8990 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8991 // such inputs we can swap two of the dwords across the half mark and end up
8992 // with <=2 inputs to each half in each half. Once there, we can fall through
8993 // to the generic code below. For example:
8995 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8996 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8998 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8999 // and an existing 2-into-2 on the other half. In this case we may have to
9000 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9001 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9002 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9003 // because any other situation (including a 3-into-1 or 1-into-3 in the other
9004 // half than the one we target for fixing) will be fixed when we re-enter this
9005 // path. We will also combine away any sequence of PSHUFD instructions that
9006 // result into a single instruction. Here is an example of the tricky case:
9008 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9009 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9011 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9013 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9014 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9016 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9017 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9019 // The result is fine to be handled by the generic logic.
9020 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9021 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9022 int AOffset, int BOffset) {
9023 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9024 "Must call this with A having 3 or 1 inputs from the A half.");
9025 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9026 "Must call this with B having 1 or 3 inputs from the B half.");
9027 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9028 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9030 bool ThreeAInputs = AToAInputs.size() == 3;
9032 // Compute the index of dword with only one word among the three inputs in
9033 // a half by taking the sum of the half with three inputs and subtracting
9034 // the sum of the actual three inputs. The difference is the remaining
9037 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9038 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9039 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9040 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9041 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9042 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9043 int TripleNonInputIdx =
9044 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9045 TripleDWord = TripleNonInputIdx / 2;
9047 // We use xor with one to compute the adjacent DWord to whichever one the
9049 OneInputDWord = (OneInput / 2) ^ 1;
9051 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9052 // and BToA inputs. If there is also such a problem with the BToB and AToB
9053 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9054 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9055 // is essential that we don't *create* a 3<-1 as then we might oscillate.
9056 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9057 // Compute how many inputs will be flipped by swapping these DWords. We
9059 // to balance this to ensure we don't form a 3-1 shuffle in the other
9061 int NumFlippedAToBInputs =
9062 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9063 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9064 int NumFlippedBToBInputs =
9065 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9066 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9067 if ((NumFlippedAToBInputs == 1 &&
9068 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9069 (NumFlippedBToBInputs == 1 &&
9070 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9071 // We choose whether to fix the A half or B half based on whether that
9072 // half has zero flipped inputs. At zero, we may not be able to fix it
9073 // with that half. We also bias towards fixing the B half because that
9074 // will more commonly be the high half, and we have to bias one way.
9075 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9076 ArrayRef<int> Inputs) {
9077 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9078 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9079 PinnedIdx ^ 1) != Inputs.end();
9080 // Determine whether the free index is in the flipped dword or the
9081 // unflipped dword based on where the pinned index is. We use this bit
9082 // in an xor to conditionally select the adjacent dword.
9083 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9084 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9085 FixFreeIdx) != Inputs.end();
9086 if (IsFixIdxInput == IsFixFreeIdxInput)
9088 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9089 FixFreeIdx) != Inputs.end();
9090 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9091 "We need to be changing the number of flipped inputs!");
9092 int PSHUFHalfMask[] = {0, 1, 2, 3};
9093 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9094 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9096 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9099 if (M != -1 && M == FixIdx)
9101 else if (M != -1 && M == FixFreeIdx)
9104 if (NumFlippedBToBInputs != 0) {
9106 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9107 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9109 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9110 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9111 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9116 int PSHUFDMask[] = {0, 1, 2, 3};
9117 PSHUFDMask[ADWord] = BDWord;
9118 PSHUFDMask[BDWord] = ADWord;
9121 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9122 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9124 // Adjust the mask to match the new locations of A and B.
9126 if (M != -1 && M/2 == ADWord)
9127 M = 2 * BDWord + M % 2;
9128 else if (M != -1 && M/2 == BDWord)
9129 M = 2 * ADWord + M % 2;
9131 // Recurse back into this routine to re-compute state now that this isn't
9132 // a 3 and 1 problem.
9133 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9136 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9137 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9138 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9139 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9141 // At this point there are at most two inputs to the low and high halves from
9142 // each half. That means the inputs can always be grouped into dwords and
9143 // those dwords can then be moved to the correct half with a dword shuffle.
9144 // We use at most one low and one high word shuffle to collect these paired
9145 // inputs into dwords, and finally a dword shuffle to place them.
9146 int PSHUFLMask[4] = {-1, -1, -1, -1};
9147 int PSHUFHMask[4] = {-1, -1, -1, -1};
9148 int PSHUFDMask[4] = {-1, -1, -1, -1};
9150 // First fix the masks for all the inputs that are staying in their
9151 // original halves. This will then dictate the targets of the cross-half
9153 auto fixInPlaceInputs =
9154 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9155 MutableArrayRef<int> SourceHalfMask,
9156 MutableArrayRef<int> HalfMask, int HalfOffset) {
9157 if (InPlaceInputs.empty())
9159 if (InPlaceInputs.size() == 1) {
9160 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9161 InPlaceInputs[0] - HalfOffset;
9162 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9165 if (IncomingInputs.empty()) {
9166 // Just fix all of the in place inputs.
9167 for (int Input : InPlaceInputs) {
9168 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9169 PSHUFDMask[Input / 2] = Input / 2;
9174 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9175 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9176 InPlaceInputs[0] - HalfOffset;
9177 // Put the second input next to the first so that they are packed into
9178 // a dword. We find the adjacent index by toggling the low bit.
9179 int AdjIndex = InPlaceInputs[0] ^ 1;
9180 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9181 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9182 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9184 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9185 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9187 // Now gather the cross-half inputs and place them into a free dword of
9188 // their target half.
9189 // FIXME: This operation could almost certainly be simplified dramatically to
9190 // look more like the 3-1 fixing operation.
9191 auto moveInputsToRightHalf = [&PSHUFDMask](
9192 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9193 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9194 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9196 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9197 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9199 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9201 int LowWord = Word & ~1;
9202 int HighWord = Word | 1;
9203 return isWordClobbered(SourceHalfMask, LowWord) ||
9204 isWordClobbered(SourceHalfMask, HighWord);
9207 if (IncomingInputs.empty())
9210 if (ExistingInputs.empty()) {
9211 // Map any dwords with inputs from them into the right half.
9212 for (int Input : IncomingInputs) {
9213 // If the source half mask maps over the inputs, turn those into
9214 // swaps and use the swapped lane.
9215 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9216 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9217 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9218 Input - SourceOffset;
9219 // We have to swap the uses in our half mask in one sweep.
9220 for (int &M : HalfMask)
9221 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9223 else if (M == Input)
9224 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9226 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9227 Input - SourceOffset &&
9228 "Previous placement doesn't match!");
9230 // Note that this correctly re-maps both when we do a swap and when
9231 // we observe the other side of the swap above. We rely on that to
9232 // avoid swapping the members of the input list directly.
9233 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9236 // Map the input's dword into the correct half.
9237 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9238 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9240 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9242 "Previous placement doesn't match!");
9245 // And just directly shift any other-half mask elements to be same-half
9246 // as we will have mirrored the dword containing the element into the
9247 // same position within that half.
9248 for (int &M : HalfMask)
9249 if (M >= SourceOffset && M < SourceOffset + 4) {
9250 M = M - SourceOffset + DestOffset;
9251 assert(M >= 0 && "This should never wrap below zero!");
9256 // Ensure we have the input in a viable dword of its current half. This
9257 // is particularly tricky because the original position may be clobbered
9258 // by inputs being moved and *staying* in that half.
9259 if (IncomingInputs.size() == 1) {
9260 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9261 int InputFixed = std::find(std::begin(SourceHalfMask),
9262 std::end(SourceHalfMask), -1) -
9263 std::begin(SourceHalfMask) + SourceOffset;
9264 SourceHalfMask[InputFixed - SourceOffset] =
9265 IncomingInputs[0] - SourceOffset;
9266 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9268 IncomingInputs[0] = InputFixed;
9270 } else if (IncomingInputs.size() == 2) {
9271 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9272 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9273 // We have two non-adjacent or clobbered inputs we need to extract from
9274 // the source half. To do this, we need to map them into some adjacent
9275 // dword slot in the source mask.
9276 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9277 IncomingInputs[1] - SourceOffset};
9279 // If there is a free slot in the source half mask adjacent to one of
9280 // the inputs, place the other input in it. We use (Index XOR 1) to
9281 // compute an adjacent index.
9282 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9283 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9284 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9285 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9286 InputsFixed[1] = InputsFixed[0] ^ 1;
9287 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9288 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9289 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9290 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9291 InputsFixed[0] = InputsFixed[1] ^ 1;
9292 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9293 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9294 // The two inputs are in the same DWord but it is clobbered and the
9295 // adjacent DWord isn't used at all. Move both inputs to the free
9297 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9298 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9299 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9300 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9302 // The only way we hit this point is if there is no clobbering
9303 // (because there are no off-half inputs to this half) and there is no
9304 // free slot adjacent to one of the inputs. In this case, we have to
9305 // swap an input with a non-input.
9306 for (int i = 0; i < 4; ++i)
9307 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9308 "We can't handle any clobbers here!");
9309 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9310 "Cannot have adjacent inputs here!");
9312 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9313 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9315 // We also have to update the final source mask in this case because
9316 // it may need to undo the above swap.
9317 for (int &M : FinalSourceHalfMask)
9318 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9319 M = InputsFixed[1] + SourceOffset;
9320 else if (M == InputsFixed[1] + SourceOffset)
9321 M = (InputsFixed[0] ^ 1) + SourceOffset;
9323 InputsFixed[1] = InputsFixed[0] ^ 1;
9326 // Point everything at the fixed inputs.
9327 for (int &M : HalfMask)
9328 if (M == IncomingInputs[0])
9329 M = InputsFixed[0] + SourceOffset;
9330 else if (M == IncomingInputs[1])
9331 M = InputsFixed[1] + SourceOffset;
9333 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9334 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9337 llvm_unreachable("Unhandled input size!");
9340 // Now hoist the DWord down to the right half.
9341 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9342 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9343 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9344 for (int &M : HalfMask)
9345 for (int Input : IncomingInputs)
9347 M = FreeDWord * 2 + Input % 2;
9349 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9350 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9351 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9352 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9354 // Now enact all the shuffles we've computed to move the inputs into their
9356 if (!isNoopShuffleMask(PSHUFLMask))
9357 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9358 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9359 if (!isNoopShuffleMask(PSHUFHMask))
9360 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9361 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9362 if (!isNoopShuffleMask(PSHUFDMask))
9365 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9366 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9368 // At this point, each half should contain all its inputs, and we can then
9369 // just shuffle them into their final position.
9370 assert(std::count_if(LoMask.begin(), LoMask.end(),
9371 [](int M) { return M >= 4; }) == 0 &&
9372 "Failed to lift all the high half inputs to the low mask!");
9373 assert(std::count_if(HiMask.begin(), HiMask.end(),
9374 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9375 "Failed to lift all the low half inputs to the high mask!");
9377 // Do a half shuffle for the low mask.
9378 if (!isNoopShuffleMask(LoMask))
9379 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9380 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9382 // Do a half shuffle with the high mask after shifting its values down.
9383 for (int &M : HiMask)
9386 if (!isNoopShuffleMask(HiMask))
9387 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9388 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9393 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9394 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9395 SDValue V2, ArrayRef<int> Mask,
9396 SelectionDAG &DAG, bool &V1InUse,
9398 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9404 int Size = Mask.size();
9405 int Scale = 16 / Size;
9406 for (int i = 0; i < 16; ++i) {
9407 if (Mask[i / Scale] == -1) {
9408 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9410 const int ZeroMask = 0x80;
9411 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9413 int V2Idx = Mask[i / Scale] < Size
9415 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9416 if (Zeroable[i / Scale])
9417 V1Idx = V2Idx = ZeroMask;
9418 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9419 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9420 V1InUse |= (ZeroMask != V1Idx);
9421 V2InUse |= (ZeroMask != V2Idx);
9426 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9427 DAG.getBitcast(MVT::v16i8, V1),
9428 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9430 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9431 DAG.getBitcast(MVT::v16i8, V2),
9432 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9434 // If we need shuffled inputs from both, blend the two.
9436 if (V1InUse && V2InUse)
9437 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9439 V = V1InUse ? V1 : V2;
9441 // Cast the result back to the correct type.
9442 return DAG.getBitcast(VT, V);
9445 /// \brief Generic lowering of 8-lane i16 shuffles.
9447 /// This handles both single-input shuffles and combined shuffle/blends with
9448 /// two inputs. The single input shuffles are immediately delegated to
9449 /// a dedicated lowering routine.
9451 /// The blends are lowered in one of three fundamental ways. If there are few
9452 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9453 /// of the input is significantly cheaper when lowered as an interleaving of
9454 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9455 /// halves of the inputs separately (making them have relatively few inputs)
9456 /// and then concatenate them.
9457 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9458 const X86Subtarget *Subtarget,
9459 SelectionDAG &DAG) {
9461 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9462 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9463 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9464 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9465 ArrayRef<int> OrigMask = SVOp->getMask();
9466 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9467 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9468 MutableArrayRef<int> Mask(MaskStorage);
9470 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9472 // Whenever we can lower this as a zext, that instruction is strictly faster
9473 // than any alternative.
9474 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9475 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9478 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9480 auto isV2 = [](int M) { return M >= 8; };
9482 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9484 if (NumV2Inputs == 0) {
9485 // Check for being able to broadcast a single element.
9486 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9487 Mask, Subtarget, DAG))
9490 // Try to use shift instructions.
9492 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9495 // Use dedicated unpack instructions for masks that match their pattern.
9497 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9500 // Try to use byte rotation instructions.
9501 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9502 Mask, Subtarget, DAG))
9505 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9509 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9510 "All single-input shuffles should be canonicalized to be V1-input "
9513 // Try to use shift instructions.
9515 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9518 // See if we can use SSE4A Extraction / Insertion.
9519 if (Subtarget->hasSSE4A())
9520 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9523 // There are special ways we can lower some single-element blends.
9524 if (NumV2Inputs == 1)
9525 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9526 Mask, Subtarget, DAG))
9529 // We have different paths for blend lowering, but they all must use the
9530 // *exact* same predicate.
9531 bool IsBlendSupported = Subtarget->hasSSE41();
9532 if (IsBlendSupported)
9533 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9537 if (SDValue Masked =
9538 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9541 // Use dedicated unpack instructions for masks that match their pattern.
9543 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9546 // Try to use byte rotation instructions.
9547 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9548 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9551 if (SDValue BitBlend =
9552 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9555 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9559 // If we can't directly blend but can use PSHUFB, that will be better as it
9560 // can both shuffle and set up the inefficient blend.
9561 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9562 bool V1InUse, V2InUse;
9563 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9567 // We can always bit-blend if we have to so the fallback strategy is to
9568 // decompose into single-input permutes and blends.
9569 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9573 /// \brief Check whether a compaction lowering can be done by dropping even
9574 /// elements and compute how many times even elements must be dropped.
9576 /// This handles shuffles which take every Nth element where N is a power of
9577 /// two. Example shuffle masks:
9579 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9580 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9581 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9582 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9583 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9584 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9586 /// Any of these lanes can of course be undef.
9588 /// This routine only supports N <= 3.
9589 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9592 /// \returns N above, or the number of times even elements must be dropped if
9593 /// there is such a number. Otherwise returns zero.
9594 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9595 // Figure out whether we're looping over two inputs or just one.
9596 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9598 // The modulus for the shuffle vector entries is based on whether this is
9599 // a single input or not.
9600 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9601 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9602 "We should only be called with masks with a power-of-2 size!");
9604 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9606 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9607 // and 2^3 simultaneously. This is because we may have ambiguity with
9608 // partially undef inputs.
9609 bool ViableForN[3] = {true, true, true};
9611 for (int i = 0, e = Mask.size(); i < e; ++i) {
9612 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9617 bool IsAnyViable = false;
9618 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9619 if (ViableForN[j]) {
9622 // The shuffle mask must be equal to (i * 2^N) % M.
9623 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9626 ViableForN[j] = false;
9628 // Early exit if we exhaust the possible powers of two.
9633 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9637 // Return 0 as there is no viable power of two.
9641 /// \brief Generic lowering of v16i8 shuffles.
9643 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9644 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9645 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9646 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9648 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9649 const X86Subtarget *Subtarget,
9650 SelectionDAG &DAG) {
9652 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9653 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9654 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9656 ArrayRef<int> Mask = SVOp->getMask();
9657 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9659 // Try to use shift instructions.
9661 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9664 // Try to use byte rotation instructions.
9665 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9666 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9669 // Try to use a zext lowering.
9670 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9671 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9674 // See if we can use SSE4A Extraction / Insertion.
9675 if (Subtarget->hasSSE4A())
9676 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9680 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9682 // For single-input shuffles, there are some nicer lowering tricks we can use.
9683 if (NumV2Elements == 0) {
9684 // Check for being able to broadcast a single element.
9685 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9686 Mask, Subtarget, DAG))
9689 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9690 // Notably, this handles splat and partial-splat shuffles more efficiently.
9691 // However, it only makes sense if the pre-duplication shuffle simplifies
9692 // things significantly. Currently, this means we need to be able to
9693 // express the pre-duplication shuffle as an i16 shuffle.
9695 // FIXME: We should check for other patterns which can be widened into an
9696 // i16 shuffle as well.
9697 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9698 for (int i = 0; i < 16; i += 2)
9699 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9704 auto tryToWidenViaDuplication = [&]() -> SDValue {
9705 if (!canWidenViaDuplication(Mask))
9707 SmallVector<int, 4> LoInputs;
9708 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9709 [](int M) { return M >= 0 && M < 8; });
9710 std::sort(LoInputs.begin(), LoInputs.end());
9711 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9713 SmallVector<int, 4> HiInputs;
9714 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9715 [](int M) { return M >= 8; });
9716 std::sort(HiInputs.begin(), HiInputs.end());
9717 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9720 bool TargetLo = LoInputs.size() >= HiInputs.size();
9721 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9722 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9724 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9725 SmallDenseMap<int, int, 8> LaneMap;
9726 for (int I : InPlaceInputs) {
9727 PreDupI16Shuffle[I/2] = I/2;
9730 int j = TargetLo ? 0 : 4, je = j + 4;
9731 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9732 // Check if j is already a shuffle of this input. This happens when
9733 // there are two adjacent bytes after we move the low one.
9734 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9735 // If we haven't yet mapped the input, search for a slot into which
9737 while (j < je && PreDupI16Shuffle[j] != -1)
9741 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9744 // Map this input with the i16 shuffle.
9745 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9748 // Update the lane map based on the mapping we ended up with.
9749 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9751 V1 = DAG.getBitcast(
9753 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9754 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9756 // Unpack the bytes to form the i16s that will be shuffled into place.
9757 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9758 MVT::v16i8, V1, V1);
9760 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9761 for (int i = 0; i < 16; ++i)
9762 if (Mask[i] != -1) {
9763 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9764 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9765 if (PostDupI16Shuffle[i / 2] == -1)
9766 PostDupI16Shuffle[i / 2] = MappedMask;
9768 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9769 "Conflicting entrties in the original shuffle!");
9771 return DAG.getBitcast(
9773 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9774 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9776 if (SDValue V = tryToWidenViaDuplication())
9780 if (SDValue Masked =
9781 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9784 // Use dedicated unpack instructions for masks that match their pattern.
9786 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9789 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9790 // with PSHUFB. It is important to do this before we attempt to generate any
9791 // blends but after all of the single-input lowerings. If the single input
9792 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9793 // want to preserve that and we can DAG combine any longer sequences into
9794 // a PSHUFB in the end. But once we start blending from multiple inputs,
9795 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9796 // and there are *very* few patterns that would actually be faster than the
9797 // PSHUFB approach because of its ability to zero lanes.
9799 // FIXME: The only exceptions to the above are blends which are exact
9800 // interleavings with direct instructions supporting them. We currently don't
9801 // handle those well here.
9802 if (Subtarget->hasSSSE3()) {
9803 bool V1InUse = false;
9804 bool V2InUse = false;
9806 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9807 DAG, V1InUse, V2InUse);
9809 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9810 // do so. This avoids using them to handle blends-with-zero which is
9811 // important as a single pshufb is significantly faster for that.
9812 if (V1InUse && V2InUse) {
9813 if (Subtarget->hasSSE41())
9814 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9815 Mask, Subtarget, DAG))
9818 // We can use an unpack to do the blending rather than an or in some
9819 // cases. Even though the or may be (very minorly) more efficient, we
9820 // preference this lowering because there are common cases where part of
9821 // the complexity of the shuffles goes away when we do the final blend as
9823 // FIXME: It might be worth trying to detect if the unpack-feeding
9824 // shuffles will both be pshufb, in which case we shouldn't bother with
9826 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9827 DL, MVT::v16i8, V1, V2, Mask, DAG))
9834 // There are special ways we can lower some single-element blends.
9835 if (NumV2Elements == 1)
9836 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9837 Mask, Subtarget, DAG))
9840 if (SDValue BitBlend =
9841 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9844 // Check whether a compaction lowering can be done. This handles shuffles
9845 // which take every Nth element for some even N. See the helper function for
9848 // We special case these as they can be particularly efficiently handled with
9849 // the PACKUSB instruction on x86 and they show up in common patterns of
9850 // rearranging bytes to truncate wide elements.
9851 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9852 // NumEvenDrops is the power of two stride of the elements. Another way of
9853 // thinking about it is that we need to drop the even elements this many
9854 // times to get the original input.
9855 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9857 // First we need to zero all the dropped bytes.
9858 assert(NumEvenDrops <= 3 &&
9859 "No support for dropping even elements more than 3 times.");
9860 // We use the mask type to pick which bytes are preserved based on how many
9861 // elements are dropped.
9862 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9863 SDValue ByteClearMask = DAG.getBitcast(
9864 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9865 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9867 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9869 // Now pack things back together.
9870 V1 = DAG.getBitcast(MVT::v8i16, V1);
9871 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9872 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9873 for (int i = 1; i < NumEvenDrops; ++i) {
9874 Result = DAG.getBitcast(MVT::v8i16, Result);
9875 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9881 // Handle multi-input cases by blending single-input shuffles.
9882 if (NumV2Elements > 0)
9883 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9886 // The fallback path for single-input shuffles widens this into two v8i16
9887 // vectors with unpacks, shuffles those, and then pulls them back together
9891 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9892 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9893 for (int i = 0; i < 16; ++i)
9895 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9897 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9899 SDValue VLoHalf, VHiHalf;
9900 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9901 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9903 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9904 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9905 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9906 [](int M) { return M >= 0 && M % 2 == 1; })) {
9907 // Use a mask to drop the high bytes.
9908 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9909 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9910 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9912 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9913 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9915 // Squash the masks to point directly into VLoHalf.
9916 for (int &M : LoBlendMask)
9919 for (int &M : HiBlendMask)
9923 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9924 // VHiHalf so that we can blend them as i16s.
9925 VLoHalf = DAG.getBitcast(
9926 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9927 VHiHalf = DAG.getBitcast(
9928 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9931 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9932 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9934 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9937 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9939 /// This routine breaks down the specific type of 128-bit shuffle and
9940 /// dispatches to the lowering routines accordingly.
9941 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9942 MVT VT, const X86Subtarget *Subtarget,
9943 SelectionDAG &DAG) {
9944 switch (VT.SimpleTy) {
9946 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9948 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9950 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9952 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9954 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9956 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9959 llvm_unreachable("Unimplemented!");
9963 /// \brief Helper function to test whether a shuffle mask could be
9964 /// simplified by widening the elements being shuffled.
9966 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9967 /// leaves it in an unspecified state.
9969 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9970 /// shuffle masks. The latter have the special property of a '-2' representing
9971 /// a zero-ed lane of a vector.
9972 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9973 SmallVectorImpl<int> &WidenedMask) {
9974 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9975 // If both elements are undef, its trivial.
9976 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9977 WidenedMask.push_back(SM_SentinelUndef);
9981 // Check for an undef mask and a mask value properly aligned to fit with
9982 // a pair of values. If we find such a case, use the non-undef mask's value.
9983 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9984 WidenedMask.push_back(Mask[i + 1] / 2);
9987 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9988 WidenedMask.push_back(Mask[i] / 2);
9992 // When zeroing, we need to spread the zeroing across both lanes to widen.
9993 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9994 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9995 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9996 WidenedMask.push_back(SM_SentinelZero);
10002 // Finally check if the two mask values are adjacent and aligned with
10004 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10005 WidenedMask.push_back(Mask[i] / 2);
10009 // Otherwise we can't safely widen the elements used in this shuffle.
10012 assert(WidenedMask.size() == Mask.size() / 2 &&
10013 "Incorrect size of mask after widening the elements!");
10018 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10020 /// This routine just extracts two subvectors, shuffles them independently, and
10021 /// then concatenates them back together. This should work effectively with all
10022 /// AVX vector shuffle types.
10023 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10024 SDValue V2, ArrayRef<int> Mask,
10025 SelectionDAG &DAG) {
10026 assert(VT.getSizeInBits() >= 256 &&
10027 "Only for 256-bit or wider vector shuffles!");
10028 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10029 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10031 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10032 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10034 int NumElements = VT.getVectorNumElements();
10035 int SplitNumElements = NumElements / 2;
10036 MVT ScalarVT = VT.getVectorElementType();
10037 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10039 // Rather than splitting build-vectors, just build two narrower build
10040 // vectors. This helps shuffling with splats and zeros.
10041 auto SplitVector = [&](SDValue V) {
10042 while (V.getOpcode() == ISD::BITCAST)
10043 V = V->getOperand(0);
10045 MVT OrigVT = V.getSimpleValueType();
10046 int OrigNumElements = OrigVT.getVectorNumElements();
10047 int OrigSplitNumElements = OrigNumElements / 2;
10048 MVT OrigScalarVT = OrigVT.getVectorElementType();
10049 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10053 auto *BV = dyn_cast<BuildVectorSDNode>(V);
10055 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10056 DAG.getIntPtrConstant(0, DL));
10057 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10058 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10061 SmallVector<SDValue, 16> LoOps, HiOps;
10062 for (int i = 0; i < OrigSplitNumElements; ++i) {
10063 LoOps.push_back(BV->getOperand(i));
10064 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10066 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10067 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10069 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10070 DAG.getBitcast(SplitVT, HiV));
10073 SDValue LoV1, HiV1, LoV2, HiV2;
10074 std::tie(LoV1, HiV1) = SplitVector(V1);
10075 std::tie(LoV2, HiV2) = SplitVector(V2);
10077 // Now create two 4-way blends of these half-width vectors.
10078 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10079 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10080 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10081 for (int i = 0; i < SplitNumElements; ++i) {
10082 int M = HalfMask[i];
10083 if (M >= NumElements) {
10084 if (M >= NumElements + SplitNumElements)
10088 V2BlendMask.push_back(M - NumElements);
10089 V1BlendMask.push_back(-1);
10090 BlendMask.push_back(SplitNumElements + i);
10091 } else if (M >= 0) {
10092 if (M >= SplitNumElements)
10096 V2BlendMask.push_back(-1);
10097 V1BlendMask.push_back(M);
10098 BlendMask.push_back(i);
10100 V2BlendMask.push_back(-1);
10101 V1BlendMask.push_back(-1);
10102 BlendMask.push_back(-1);
10106 // Because the lowering happens after all combining takes place, we need to
10107 // manually combine these blend masks as much as possible so that we create
10108 // a minimal number of high-level vector shuffle nodes.
10110 // First try just blending the halves of V1 or V2.
10111 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10112 return DAG.getUNDEF(SplitVT);
10113 if (!UseLoV2 && !UseHiV2)
10114 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10115 if (!UseLoV1 && !UseHiV1)
10116 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10118 SDValue V1Blend, V2Blend;
10119 if (UseLoV1 && UseHiV1) {
10121 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10123 // We only use half of V1 so map the usage down into the final blend mask.
10124 V1Blend = UseLoV1 ? LoV1 : HiV1;
10125 for (int i = 0; i < SplitNumElements; ++i)
10126 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10127 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10129 if (UseLoV2 && UseHiV2) {
10131 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10133 // We only use half of V2 so map the usage down into the final blend mask.
10134 V2Blend = UseLoV2 ? LoV2 : HiV2;
10135 for (int i = 0; i < SplitNumElements; ++i)
10136 if (BlendMask[i] >= SplitNumElements)
10137 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10139 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10141 SDValue Lo = HalfBlend(LoMask);
10142 SDValue Hi = HalfBlend(HiMask);
10143 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10146 /// \brief Either split a vector in halves or decompose the shuffles and the
10149 /// This is provided as a good fallback for many lowerings of non-single-input
10150 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10151 /// between splitting the shuffle into 128-bit components and stitching those
10152 /// back together vs. extracting the single-input shuffles and blending those
10154 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10155 SDValue V2, ArrayRef<int> Mask,
10156 SelectionDAG &DAG) {
10157 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10158 "lower single-input shuffles as it "
10159 "could then recurse on itself.");
10160 int Size = Mask.size();
10162 // If this can be modeled as a broadcast of two elements followed by a blend,
10163 // prefer that lowering. This is especially important because broadcasts can
10164 // often fold with memory operands.
10165 auto DoBothBroadcast = [&] {
10166 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10169 if (V2BroadcastIdx == -1)
10170 V2BroadcastIdx = M - Size;
10171 else if (M - Size != V2BroadcastIdx)
10173 } else if (M >= 0) {
10174 if (V1BroadcastIdx == -1)
10175 V1BroadcastIdx = M;
10176 else if (M != V1BroadcastIdx)
10181 if (DoBothBroadcast())
10182 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10185 // If the inputs all stem from a single 128-bit lane of each input, then we
10186 // split them rather than blending because the split will decompose to
10187 // unusually few instructions.
10188 int LaneCount = VT.getSizeInBits() / 128;
10189 int LaneSize = Size / LaneCount;
10190 SmallBitVector LaneInputs[2];
10191 LaneInputs[0].resize(LaneCount, false);
10192 LaneInputs[1].resize(LaneCount, false);
10193 for (int i = 0; i < Size; ++i)
10195 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10196 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10197 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10199 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10200 // that the decomposed single-input shuffles don't end up here.
10201 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10204 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10205 /// a permutation and blend of those lanes.
10207 /// This essentially blends the out-of-lane inputs to each lane into the lane
10208 /// from a permuted copy of the vector. This lowering strategy results in four
10209 /// instructions in the worst case for a single-input cross lane shuffle which
10210 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10211 /// of. Special cases for each particular shuffle pattern should be handled
10212 /// prior to trying this lowering.
10213 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10214 SDValue V1, SDValue V2,
10215 ArrayRef<int> Mask,
10216 SelectionDAG &DAG) {
10217 // FIXME: This should probably be generalized for 512-bit vectors as well.
10218 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10219 int LaneSize = Mask.size() / 2;
10221 // If there are only inputs from one 128-bit lane, splitting will in fact be
10222 // less expensive. The flags track whether the given lane contains an element
10223 // that crosses to another lane.
10224 bool LaneCrossing[2] = {false, false};
10225 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10226 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10227 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10228 if (!LaneCrossing[0] || !LaneCrossing[1])
10229 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10231 if (isSingleInputShuffleMask(Mask)) {
10232 SmallVector<int, 32> FlippedBlendMask;
10233 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10234 FlippedBlendMask.push_back(
10235 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10237 : Mask[i] % LaneSize +
10238 (i / LaneSize) * LaneSize + Size));
10240 // Flip the vector, and blend the results which should now be in-lane. The
10241 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10242 // 5 for the high source. The value 3 selects the high half of source 2 and
10243 // the value 2 selects the low half of source 2. We only use source 2 to
10244 // allow folding it into a memory operand.
10245 unsigned PERMMask = 3 | 2 << 4;
10246 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10247 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10248 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10251 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10252 // will be handled by the above logic and a blend of the results, much like
10253 // other patterns in AVX.
10254 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10257 /// \brief Handle lowering 2-lane 128-bit shuffles.
10258 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10259 SDValue V2, ArrayRef<int> Mask,
10260 const X86Subtarget *Subtarget,
10261 SelectionDAG &DAG) {
10262 // TODO: If minimizing size and one of the inputs is a zero vector and the
10263 // the zero vector has only one use, we could use a VPERM2X128 to save the
10264 // instruction bytes needed to explicitly generate the zero vector.
10266 // Blends are faster and handle all the non-lane-crossing cases.
10267 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10271 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10272 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10274 // If either input operand is a zero vector, use VPERM2X128 because its mask
10275 // allows us to replace the zero input with an implicit zero.
10276 if (!IsV1Zero && !IsV2Zero) {
10277 // Check for patterns which can be matched with a single insert of a 128-bit
10279 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10280 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10281 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10282 VT.getVectorNumElements() / 2);
10283 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10284 DAG.getIntPtrConstant(0, DL));
10285 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10286 OnlyUsesV1 ? V1 : V2,
10287 DAG.getIntPtrConstant(0, DL));
10288 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10292 // Otherwise form a 128-bit permutation. After accounting for undefs,
10293 // convert the 64-bit shuffle mask selection values into 128-bit
10294 // selection bits by dividing the indexes by 2 and shifting into positions
10295 // defined by a vperm2*128 instruction's immediate control byte.
10297 // The immediate permute control byte looks like this:
10298 // [1:0] - select 128 bits from sources for low half of destination
10300 // [3] - zero low half of destination
10301 // [5:4] - select 128 bits from sources for high half of destination
10303 // [7] - zero high half of destination
10305 int MaskLO = Mask[0];
10306 if (MaskLO == SM_SentinelUndef)
10307 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10309 int MaskHI = Mask[2];
10310 if (MaskHI == SM_SentinelUndef)
10311 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10313 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10315 // If either input is a zero vector, replace it with an undef input.
10316 // Shuffle mask values < 4 are selecting elements of V1.
10317 // Shuffle mask values >= 4 are selecting elements of V2.
10318 // Adjust each half of the permute mask by clearing the half that was
10319 // selecting the zero vector and setting the zero mask bit.
10321 V1 = DAG.getUNDEF(VT);
10323 PermMask = (PermMask & 0xf0) | 0x08;
10325 PermMask = (PermMask & 0x0f) | 0x80;
10328 V2 = DAG.getUNDEF(VT);
10330 PermMask = (PermMask & 0xf0) | 0x08;
10332 PermMask = (PermMask & 0x0f) | 0x80;
10335 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10336 DAG.getConstant(PermMask, DL, MVT::i8));
10339 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10340 /// shuffling each lane.
10342 /// This will only succeed when the result of fixing the 128-bit lanes results
10343 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10344 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10345 /// the lane crosses early and then use simpler shuffles within each lane.
10347 /// FIXME: It might be worthwhile at some point to support this without
10348 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10349 /// in x86 only floating point has interesting non-repeating shuffles, and even
10350 /// those are still *marginally* more expensive.
10351 static SDValue lowerVectorShuffleByMerging128BitLanes(
10352 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10353 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10354 assert(!isSingleInputShuffleMask(Mask) &&
10355 "This is only useful with multiple inputs.");
10357 int Size = Mask.size();
10358 int LaneSize = 128 / VT.getScalarSizeInBits();
10359 int NumLanes = Size / LaneSize;
10360 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10362 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10363 // check whether the in-128-bit lane shuffles share a repeating pattern.
10364 SmallVector<int, 4> Lanes;
10365 Lanes.resize(NumLanes, -1);
10366 SmallVector<int, 4> InLaneMask;
10367 InLaneMask.resize(LaneSize, -1);
10368 for (int i = 0; i < Size; ++i) {
10372 int j = i / LaneSize;
10374 if (Lanes[j] < 0) {
10375 // First entry we've seen for this lane.
10376 Lanes[j] = Mask[i] / LaneSize;
10377 } else if (Lanes[j] != Mask[i] / LaneSize) {
10378 // This doesn't match the lane selected previously!
10382 // Check that within each lane we have a consistent shuffle mask.
10383 int k = i % LaneSize;
10384 if (InLaneMask[k] < 0) {
10385 InLaneMask[k] = Mask[i] % LaneSize;
10386 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10387 // This doesn't fit a repeating in-lane mask.
10392 // First shuffle the lanes into place.
10393 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10394 VT.getSizeInBits() / 64);
10395 SmallVector<int, 8> LaneMask;
10396 LaneMask.resize(NumLanes * 2, -1);
10397 for (int i = 0; i < NumLanes; ++i)
10398 if (Lanes[i] >= 0) {
10399 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10400 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10403 V1 = DAG.getBitcast(LaneVT, V1);
10404 V2 = DAG.getBitcast(LaneVT, V2);
10405 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10407 // Cast it back to the type we actually want.
10408 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10410 // Now do a simple shuffle that isn't lane crossing.
10411 SmallVector<int, 8> NewMask;
10412 NewMask.resize(Size, -1);
10413 for (int i = 0; i < Size; ++i)
10415 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10416 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10417 "Must not introduce lane crosses at this point!");
10419 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10422 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10423 /// This allows for fast cases such as subvector extraction/insertion
10424 /// or shuffling smaller vector types which can lower more efficiently.
10425 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10426 SDValue V2, ArrayRef<int> Mask,
10427 const X86Subtarget *Subtarget,
10428 SelectionDAG &DAG) {
10429 assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10431 unsigned NumElts = VT.getVectorNumElements();
10432 unsigned HalfNumElts = NumElts / 2;
10433 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10435 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10436 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10437 if (!UndefLower && !UndefUpper)
10440 // Upper half is undef and lower half is whole upper subvector.
10441 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10443 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10444 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10445 DAG.getIntPtrConstant(HalfNumElts, DL));
10446 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10447 DAG.getIntPtrConstant(0, DL));
10450 // Lower half is undef and upper half is whole lower subvector.
10451 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10453 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10454 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10455 DAG.getIntPtrConstant(0, DL));
10456 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10457 DAG.getIntPtrConstant(HalfNumElts, DL));
10460 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10461 if (UndefLower && Subtarget->hasAVX2() &&
10462 (VT == MVT::v4f64 || VT == MVT::v4i64))
10465 // If the shuffle only uses the lower halves of the input operands,
10466 // then extract them and perform the 'half' shuffle at half width.
10467 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10468 int HalfIdx1 = -1, HalfIdx2 = -1;
10469 SmallVector<int, 8> HalfMask;
10470 unsigned Offset = UndefLower ? HalfNumElts : 0;
10471 for (unsigned i = 0; i != HalfNumElts; ++i) {
10472 int M = Mask[i + Offset];
10474 HalfMask.push_back(M);
10478 // Determine which of the 4 half vectors this element is from.
10479 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10480 int HalfIdx = M / HalfNumElts;
10482 // Only shuffle using the lower halves of the inputs.
10483 // TODO: Investigate usefulness of shuffling with upper halves.
10484 if (HalfIdx != 0 && HalfIdx != 2)
10487 // Determine the element index into its half vector source.
10488 int HalfElt = M % HalfNumElts;
10490 // We can shuffle with up to 2 half vectors, set the new 'half'
10491 // shuffle mask accordingly.
10492 if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10493 HalfMask.push_back(HalfElt);
10494 HalfIdx1 = HalfIdx;
10497 if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10498 HalfMask.push_back(HalfElt + HalfNumElts);
10499 HalfIdx2 = HalfIdx;
10503 // Too many half vectors referenced.
10506 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10508 auto GetHalfVector = [&](int HalfIdx) {
10510 return DAG.getUNDEF(HalfVT);
10511 SDValue V = (HalfIdx < 2 ? V1 : V2);
10512 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10513 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10514 DAG.getIntPtrConstant(HalfIdx, DL));
10517 SDValue Half1 = GetHalfVector(HalfIdx1);
10518 SDValue Half2 = GetHalfVector(HalfIdx2);
10519 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10520 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10521 DAG.getIntPtrConstant(Offset, DL));
10524 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10527 /// This returns true if the elements from a particular input are already in the
10528 /// slot required by the given mask and require no permutation.
10529 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10530 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10531 int Size = Mask.size();
10532 for (int i = 0; i < Size; ++i)
10533 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10539 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10540 ArrayRef<int> Mask, SDValue V1,
10541 SDValue V2, SelectionDAG &DAG) {
10543 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10544 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10545 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10546 int NumElts = VT.getVectorNumElements();
10547 bool ShufpdMask = true;
10548 bool CommutableMask = true;
10549 unsigned Immediate = 0;
10550 for (int i = 0; i < NumElts; ++i) {
10553 int Val = (i & 6) + NumElts * (i & 1);
10554 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10555 if (Mask[i] < Val || Mask[i] > Val + 1)
10556 ShufpdMask = false;
10557 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10558 CommutableMask = false;
10559 Immediate |= (Mask[i] % 2) << i;
10562 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10563 DAG.getConstant(Immediate, DL, MVT::i8));
10564 if (CommutableMask)
10565 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10566 DAG.getConstant(Immediate, DL, MVT::i8));
10570 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10572 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10573 /// isn't available.
10574 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10575 const X86Subtarget *Subtarget,
10576 SelectionDAG &DAG) {
10578 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10579 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10580 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10581 ArrayRef<int> Mask = SVOp->getMask();
10582 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10584 SmallVector<int, 4> WidenedMask;
10585 if (canWidenShuffleElements(Mask, WidenedMask))
10586 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10589 if (isSingleInputShuffleMask(Mask)) {
10590 // Check for being able to broadcast a single element.
10591 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10592 Mask, Subtarget, DAG))
10595 // Use low duplicate instructions for masks that match their pattern.
10596 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10597 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10599 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10600 // Non-half-crossing single input shuffles can be lowerid with an
10601 // interleaved permutation.
10602 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10603 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10604 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10605 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10608 // With AVX2 we have direct support for this permutation.
10609 if (Subtarget->hasAVX2())
10610 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10611 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10613 // Otherwise, fall back.
10614 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10618 // Use dedicated unpack instructions for masks that match their pattern.
10620 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10623 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10627 // Check if the blend happens to exactly fit that of SHUFPD.
10629 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10632 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10633 // shuffle. However, if we have AVX2 and either inputs are already in place,
10634 // we will be able to shuffle even across lanes the other input in a single
10635 // instruction so skip this pattern.
10636 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10637 isShuffleMaskInputInPlace(1, Mask))))
10638 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10639 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10642 // If we have AVX2 then we always want to lower with a blend because an v4 we
10643 // can fully permute the elements.
10644 if (Subtarget->hasAVX2())
10645 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10648 // Otherwise fall back on generic lowering.
10649 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10652 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10654 /// This routine is only called when we have AVX2 and thus a reasonable
10655 /// instruction set for v4i64 shuffling..
10656 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10657 const X86Subtarget *Subtarget,
10658 SelectionDAG &DAG) {
10660 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10661 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10662 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10663 ArrayRef<int> Mask = SVOp->getMask();
10664 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10665 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10667 SmallVector<int, 4> WidenedMask;
10668 if (canWidenShuffleElements(Mask, WidenedMask))
10669 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10672 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10676 // Check for being able to broadcast a single element.
10677 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10678 Mask, Subtarget, DAG))
10681 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10682 // use lower latency instructions that will operate on both 128-bit lanes.
10683 SmallVector<int, 2> RepeatedMask;
10684 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10685 if (isSingleInputShuffleMask(Mask)) {
10686 int PSHUFDMask[] = {-1, -1, -1, -1};
10687 for (int i = 0; i < 2; ++i)
10688 if (RepeatedMask[i] >= 0) {
10689 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10690 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10692 return DAG.getBitcast(
10694 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10695 DAG.getBitcast(MVT::v8i32, V1),
10696 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10700 // AVX2 provides a direct instruction for permuting a single input across
10702 if (isSingleInputShuffleMask(Mask))
10703 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10704 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10706 // Try to use shift instructions.
10707 if (SDValue Shift =
10708 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10711 // Use dedicated unpack instructions for masks that match their pattern.
10713 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10716 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10717 // shuffle. However, if we have AVX2 and either inputs are already in place,
10718 // we will be able to shuffle even across lanes the other input in a single
10719 // instruction so skip this pattern.
10720 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10721 isShuffleMaskInputInPlace(1, Mask))))
10722 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10723 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10726 // Otherwise fall back on generic blend lowering.
10727 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10731 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10733 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10734 /// isn't available.
10735 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10736 const X86Subtarget *Subtarget,
10737 SelectionDAG &DAG) {
10739 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10740 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10741 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10742 ArrayRef<int> Mask = SVOp->getMask();
10743 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10745 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10749 // Check for being able to broadcast a single element.
10750 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10751 Mask, Subtarget, DAG))
10754 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10755 // options to efficiently lower the shuffle.
10756 SmallVector<int, 4> RepeatedMask;
10757 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10758 assert(RepeatedMask.size() == 4 &&
10759 "Repeated masks must be half the mask width!");
10761 // Use even/odd duplicate instructions for masks that match their pattern.
10762 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10763 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10764 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10765 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10767 if (isSingleInputShuffleMask(Mask))
10768 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10769 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10771 // Use dedicated unpack instructions for masks that match their pattern.
10773 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10776 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10777 // have already handled any direct blends. We also need to squash the
10778 // repeated mask into a simulated v4f32 mask.
10779 for (int i = 0; i < 4; ++i)
10780 if (RepeatedMask[i] >= 8)
10781 RepeatedMask[i] -= 4;
10782 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10785 // If we have a single input shuffle with different shuffle patterns in the
10786 // two 128-bit lanes use the variable mask to VPERMILPS.
10787 if (isSingleInputShuffleMask(Mask)) {
10788 SDValue VPermMask[8];
10789 for (int i = 0; i < 8; ++i)
10790 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10791 : DAG.getConstant(Mask[i], DL, MVT::i32);
10792 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10793 return DAG.getNode(
10794 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10795 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10797 if (Subtarget->hasAVX2())
10798 return DAG.getNode(
10799 X86ISD::VPERMV, DL, MVT::v8f32,
10800 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10802 // Otherwise, fall back.
10803 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10807 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10809 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10810 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10813 // If we have AVX2 then we always want to lower with a blend because at v8 we
10814 // can fully permute the elements.
10815 if (Subtarget->hasAVX2())
10816 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10819 // Otherwise fall back on generic lowering.
10820 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10823 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10825 /// This routine is only called when we have AVX2 and thus a reasonable
10826 /// instruction set for v8i32 shuffling..
10827 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10828 const X86Subtarget *Subtarget,
10829 SelectionDAG &DAG) {
10831 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10832 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10833 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10834 ArrayRef<int> Mask = SVOp->getMask();
10835 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10836 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10838 // Whenever we can lower this as a zext, that instruction is strictly faster
10839 // than any alternative. It also allows us to fold memory operands into the
10840 // shuffle in many cases.
10841 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10842 Mask, Subtarget, DAG))
10845 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10849 // Check for being able to broadcast a single element.
10850 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10851 Mask, Subtarget, DAG))
10854 // If the shuffle mask is repeated in each 128-bit lane we can use more
10855 // efficient instructions that mirror the shuffles across the two 128-bit
10857 SmallVector<int, 4> RepeatedMask;
10858 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10859 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10860 if (isSingleInputShuffleMask(Mask))
10861 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10862 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10864 // Use dedicated unpack instructions for masks that match their pattern.
10866 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10870 // Try to use shift instructions.
10871 if (SDValue Shift =
10872 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10875 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10876 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10879 // If the shuffle patterns aren't repeated but it is a single input, directly
10880 // generate a cross-lane VPERMD instruction.
10881 if (isSingleInputShuffleMask(Mask)) {
10882 SDValue VPermMask[8];
10883 for (int i = 0; i < 8; ++i)
10884 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10885 : DAG.getConstant(Mask[i], DL, MVT::i32);
10886 return DAG.getNode(
10887 X86ISD::VPERMV, DL, MVT::v8i32,
10888 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10891 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10893 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10894 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10897 // Otherwise fall back on generic blend lowering.
10898 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10902 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10904 /// This routine is only called when we have AVX2 and thus a reasonable
10905 /// instruction set for v16i16 shuffling..
10906 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10907 const X86Subtarget *Subtarget,
10908 SelectionDAG &DAG) {
10910 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10911 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10913 ArrayRef<int> Mask = SVOp->getMask();
10914 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10915 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10917 // Whenever we can lower this as a zext, that instruction is strictly faster
10918 // than any alternative. It also allows us to fold memory operands into the
10919 // shuffle in many cases.
10920 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10921 Mask, Subtarget, DAG))
10924 // Check for being able to broadcast a single element.
10925 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10926 Mask, Subtarget, DAG))
10929 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10933 // Use dedicated unpack instructions for masks that match their pattern.
10935 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10938 // Try to use shift instructions.
10939 if (SDValue Shift =
10940 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10943 // Try to use byte rotation instructions.
10944 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10945 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10948 if (isSingleInputShuffleMask(Mask)) {
10949 // There are no generalized cross-lane shuffle operations available on i16
10951 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10952 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10955 SmallVector<int, 8> RepeatedMask;
10956 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10957 // As this is a single-input shuffle, the repeated mask should be
10958 // a strictly valid v8i16 mask that we can pass through to the v8i16
10959 // lowering to handle even the v16 case.
10960 return lowerV8I16GeneralSingleInputVectorShuffle(
10961 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10964 SDValue PSHUFBMask[32];
10965 for (int i = 0; i < 16; ++i) {
10966 if (Mask[i] == -1) {
10967 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10971 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10972 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10973 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10974 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10976 return DAG.getBitcast(MVT::v16i16,
10977 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10978 DAG.getBitcast(MVT::v32i8, V1),
10979 DAG.getNode(ISD::BUILD_VECTOR, DL,
10980 MVT::v32i8, PSHUFBMask)));
10983 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10985 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10986 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10989 // Otherwise fall back on generic lowering.
10990 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10993 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10995 /// This routine is only called when we have AVX2 and thus a reasonable
10996 /// instruction set for v32i8 shuffling..
10997 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10998 const X86Subtarget *Subtarget,
10999 SelectionDAG &DAG) {
11001 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11002 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11003 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11004 ArrayRef<int> Mask = SVOp->getMask();
11005 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11006 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
11008 // Whenever we can lower this as a zext, that instruction is strictly faster
11009 // than any alternative. It also allows us to fold memory operands into the
11010 // shuffle in many cases.
11011 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11012 Mask, Subtarget, DAG))
11015 // Check for being able to broadcast a single element.
11016 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
11017 Mask, Subtarget, DAG))
11020 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11024 // Use dedicated unpack instructions for masks that match their pattern.
11026 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11029 // Try to use shift instructions.
11030 if (SDValue Shift =
11031 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11034 // Try to use byte rotation instructions.
11035 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11036 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11039 if (isSingleInputShuffleMask(Mask)) {
11040 // There are no generalized cross-lane shuffle operations available on i8
11042 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11043 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11046 SDValue PSHUFBMask[32];
11047 for (int i = 0; i < 32; ++i)
11050 ? DAG.getUNDEF(MVT::i8)
11051 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11054 return DAG.getNode(
11055 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11056 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11059 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11061 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11062 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11065 // Otherwise fall back on generic lowering.
11066 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11069 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11071 /// This routine either breaks down the specific type of a 256-bit x86 vector
11072 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11073 /// together based on the available instructions.
11074 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11075 MVT VT, const X86Subtarget *Subtarget,
11076 SelectionDAG &DAG) {
11078 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11079 ArrayRef<int> Mask = SVOp->getMask();
11081 // If we have a single input to the zero element, insert that into V1 if we
11082 // can do so cheaply.
11083 int NumElts = VT.getVectorNumElements();
11084 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11085 return M >= NumElts;
11088 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11089 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11090 DL, VT, V1, V2, Mask, Subtarget, DAG))
11093 // Handle special cases where the lower or upper half is UNDEF.
11095 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11098 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11099 // can check for those subtargets here and avoid much of the subtarget
11100 // querying in the per-vector-type lowering routines. With AVX1 we have
11101 // essentially *zero* ability to manipulate a 256-bit vector with integer
11102 // types. Since we'll use floating point types there eventually, just
11103 // immediately cast everything to a float and operate entirely in that domain.
11104 if (VT.isInteger() && !Subtarget->hasAVX2()) {
11105 int ElementBits = VT.getScalarSizeInBits();
11106 if (ElementBits < 32)
11107 // No floating point type available, decompose into 128-bit vectors.
11108 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11110 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11111 VT.getVectorNumElements());
11112 V1 = DAG.getBitcast(FpVT, V1);
11113 V2 = DAG.getBitcast(FpVT, V2);
11114 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11117 switch (VT.SimpleTy) {
11119 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11121 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11123 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11125 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11127 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11129 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11132 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11136 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11137 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11138 ArrayRef<int> Mask,
11139 SDValue V1, SDValue V2,
11140 SelectionDAG &DAG) {
11141 assert(VT.getScalarSizeInBits() == 64 &&
11142 "Unexpected element type size for 128bit shuffle.");
11144 // To handle 256 bit vector requires VLX and most probably
11145 // function lowerV2X128VectorShuffle() is better solution.
11146 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11148 SmallVector<int, 4> WidenedMask;
11149 if (!canWidenShuffleElements(Mask, WidenedMask))
11152 // Form a 128-bit permutation.
11153 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11154 // bits defined by a vshuf64x2 instruction's immediate control byte.
11155 unsigned PermMask = 0, Imm = 0;
11156 unsigned ControlBitsNum = WidenedMask.size() / 2;
11158 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11159 if (WidenedMask[i] == SM_SentinelZero)
11162 // Use first element in place of undef mask.
11163 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11164 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11167 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11168 DAG.getConstant(PermMask, DL, MVT::i8));
11171 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11172 ArrayRef<int> Mask, SDValue V1,
11173 SDValue V2, SelectionDAG &DAG) {
11175 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11177 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11178 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11180 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11181 if (isSingleInputShuffleMask(Mask))
11182 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11184 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11187 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11188 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11189 const X86Subtarget *Subtarget,
11190 SelectionDAG &DAG) {
11192 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11193 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11194 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11195 ArrayRef<int> Mask = SVOp->getMask();
11196 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11198 if (SDValue Shuf128 =
11199 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11202 if (SDValue Unpck =
11203 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11206 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11209 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11210 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11211 const X86Subtarget *Subtarget,
11212 SelectionDAG &DAG) {
11214 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11215 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11217 ArrayRef<int> Mask = SVOp->getMask();
11218 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11220 if (SDValue Unpck =
11221 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11224 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11227 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11228 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11229 const X86Subtarget *Subtarget,
11230 SelectionDAG &DAG) {
11232 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11233 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11234 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11235 ArrayRef<int> Mask = SVOp->getMask();
11236 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11238 if (SDValue Shuf128 =
11239 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11242 if (SDValue Unpck =
11243 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11246 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11249 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11250 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11251 const X86Subtarget *Subtarget,
11252 SelectionDAG &DAG) {
11254 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11255 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11256 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11257 ArrayRef<int> Mask = SVOp->getMask();
11258 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11260 if (SDValue Unpck =
11261 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11264 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11267 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11268 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11269 const X86Subtarget *Subtarget,
11270 SelectionDAG &DAG) {
11272 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11273 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11275 ArrayRef<int> Mask = SVOp->getMask();
11276 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11277 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11279 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11282 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11283 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11284 const X86Subtarget *Subtarget,
11285 SelectionDAG &DAG) {
11287 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11288 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11289 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11290 ArrayRef<int> Mask = SVOp->getMask();
11291 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11292 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11294 // FIXME: Implement direct support for this type!
11295 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11298 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11300 /// This routine either breaks down the specific type of a 512-bit x86 vector
11301 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11302 /// together based on the available instructions.
11303 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11304 MVT VT, const X86Subtarget *Subtarget,
11305 SelectionDAG &DAG) {
11307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11308 ArrayRef<int> Mask = SVOp->getMask();
11309 assert(Subtarget->hasAVX512() &&
11310 "Cannot lower 512-bit vectors w/ basic ISA!");
11312 // Check for being able to broadcast a single element.
11313 if (SDValue Broadcast =
11314 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11317 // Dispatch to each element type for lowering. If we don't have supprot for
11318 // specific element type shuffles at 512 bits, immediately split them and
11319 // lower them. Each lowering routine of a given type is allowed to assume that
11320 // the requisite ISA extensions for that element type are available.
11321 switch (VT.SimpleTy) {
11323 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11325 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11327 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11329 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11331 if (Subtarget->hasBWI())
11332 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11335 if (Subtarget->hasBWI())
11336 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11340 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11343 // Otherwise fall back on splitting.
11344 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11347 // Lower vXi1 vector shuffles.
11348 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11349 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11350 // vector, shuffle and then truncate it back.
11351 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11352 MVT VT, const X86Subtarget *Subtarget,
11353 SelectionDAG &DAG) {
11355 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11356 ArrayRef<int> Mask = SVOp->getMask();
11357 assert(Subtarget->hasAVX512() &&
11358 "Cannot lower 512-bit vectors w/o basic ISA!");
11360 switch (VT.SimpleTy) {
11362 llvm_unreachable("Expected a vector of i1 elements");
11364 ExtVT = MVT::v2i64;
11367 ExtVT = MVT::v4i32;
11370 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11373 ExtVT = MVT::v16i32;
11376 ExtVT = MVT::v32i16;
11379 ExtVT = MVT::v64i8;
11383 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11384 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11385 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11386 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11388 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11391 V2 = DAG.getUNDEF(ExtVT);
11392 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11393 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11394 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11395 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11397 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11398 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11399 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11401 /// \brief Top-level lowering for x86 vector shuffles.
11403 /// This handles decomposition, canonicalization, and lowering of all x86
11404 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11405 /// above in helper routines. The canonicalization attempts to widen shuffles
11406 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11407 /// s.t. only one of the two inputs needs to be tested, etc.
11408 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11409 SelectionDAG &DAG) {
11410 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11411 ArrayRef<int> Mask = SVOp->getMask();
11412 SDValue V1 = Op.getOperand(0);
11413 SDValue V2 = Op.getOperand(1);
11414 MVT VT = Op.getSimpleValueType();
11415 int NumElements = VT.getVectorNumElements();
11417 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11419 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11420 "Can't lower MMX shuffles");
11422 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11423 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11424 if (V1IsUndef && V2IsUndef)
11425 return DAG.getUNDEF(VT);
11427 // When we create a shuffle node we put the UNDEF node to second operand,
11428 // but in some cases the first operand may be transformed to UNDEF.
11429 // In this case we should just commute the node.
11431 return DAG.getCommutedVectorShuffle(*SVOp);
11433 // Check for non-undef masks pointing at an undef vector and make the masks
11434 // undef as well. This makes it easier to match the shuffle based solely on
11438 if (M >= NumElements) {
11439 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11440 for (int &M : NewMask)
11441 if (M >= NumElements)
11443 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11446 // We actually see shuffles that are entirely re-arrangements of a set of
11447 // zero inputs. This mostly happens while decomposing complex shuffles into
11448 // simple ones. Directly lower these as a buildvector of zeros.
11449 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11450 if (Zeroable.all())
11451 return getZeroVector(VT, Subtarget, DAG, dl);
11453 // Try to collapse shuffles into using a vector type with fewer elements but
11454 // wider element types. We cap this to not form integers or floating point
11455 // elements wider than 64 bits, but it might be interesting to form i128
11456 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11457 SmallVector<int, 16> WidenedMask;
11458 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11459 canWidenShuffleElements(Mask, WidenedMask)) {
11460 MVT NewEltVT = VT.isFloatingPoint()
11461 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11462 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11463 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11464 // Make sure that the new vector type is legal. For example, v2f64 isn't
11466 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11467 V1 = DAG.getBitcast(NewVT, V1);
11468 V2 = DAG.getBitcast(NewVT, V2);
11469 return DAG.getBitcast(
11470 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11474 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11475 for (int M : SVOp->getMask())
11477 ++NumUndefElements;
11478 else if (M < NumElements)
11483 // Commute the shuffle as needed such that more elements come from V1 than
11484 // V2. This allows us to match the shuffle pattern strictly on how many
11485 // elements come from V1 without handling the symmetric cases.
11486 if (NumV2Elements > NumV1Elements)
11487 return DAG.getCommutedVectorShuffle(*SVOp);
11489 // When the number of V1 and V2 elements are the same, try to minimize the
11490 // number of uses of V2 in the low half of the vector. When that is tied,
11491 // ensure that the sum of indices for V1 is equal to or lower than the sum
11492 // indices for V2. When those are equal, try to ensure that the number of odd
11493 // indices for V1 is lower than the number of odd indices for V2.
11494 if (NumV1Elements == NumV2Elements) {
11495 int LowV1Elements = 0, LowV2Elements = 0;
11496 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11497 if (M >= NumElements)
11501 if (LowV2Elements > LowV1Elements) {
11502 return DAG.getCommutedVectorShuffle(*SVOp);
11503 } else if (LowV2Elements == LowV1Elements) {
11504 int SumV1Indices = 0, SumV2Indices = 0;
11505 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11506 if (SVOp->getMask()[i] >= NumElements)
11508 else if (SVOp->getMask()[i] >= 0)
11510 if (SumV2Indices < SumV1Indices) {
11511 return DAG.getCommutedVectorShuffle(*SVOp);
11512 } else if (SumV2Indices == SumV1Indices) {
11513 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11514 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11515 if (SVOp->getMask()[i] >= NumElements)
11516 NumV2OddIndices += i % 2;
11517 else if (SVOp->getMask()[i] >= 0)
11518 NumV1OddIndices += i % 2;
11519 if (NumV2OddIndices < NumV1OddIndices)
11520 return DAG.getCommutedVectorShuffle(*SVOp);
11525 // For each vector width, delegate to a specialized lowering routine.
11526 if (VT.is128BitVector())
11527 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11529 if (VT.is256BitVector())
11530 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11532 if (VT.is512BitVector())
11533 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11536 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11537 llvm_unreachable("Unimplemented!");
11540 // This function assumes its argument is a BUILD_VECTOR of constants or
11541 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11543 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11544 unsigned &MaskValue) {
11546 unsigned NumElems = BuildVector->getNumOperands();
11548 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11549 // We don't handle the >2 lanes case right now.
11550 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11554 unsigned NumElemsInLane = NumElems / NumLanes;
11556 // Blend for v16i16 should be symmetric for the both lanes.
11557 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11558 SDValue EltCond = BuildVector->getOperand(i);
11559 SDValue SndLaneEltCond =
11560 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11562 int Lane1Cond = -1, Lane2Cond = -1;
11563 if (isa<ConstantSDNode>(EltCond))
11564 Lane1Cond = !isNullConstant(EltCond);
11565 if (isa<ConstantSDNode>(SndLaneEltCond))
11566 Lane2Cond = !isNullConstant(SndLaneEltCond);
11568 unsigned LaneMask = 0;
11569 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11570 // Lane1Cond != 0, means we want the first argument.
11571 // Lane1Cond == 0, means we want the second argument.
11572 // The encoding of this argument is 0 for the first argument, 1
11573 // for the second. Therefore, invert the condition.
11574 LaneMask = !Lane1Cond << i;
11575 else if (Lane1Cond < 0)
11576 LaneMask = !Lane2Cond << i;
11580 MaskValue |= LaneMask;
11582 MaskValue |= LaneMask << NumElemsInLane;
11587 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11588 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11589 const X86Subtarget *Subtarget,
11590 SelectionDAG &DAG) {
11591 SDValue Cond = Op.getOperand(0);
11592 SDValue LHS = Op.getOperand(1);
11593 SDValue RHS = Op.getOperand(2);
11595 MVT VT = Op.getSimpleValueType();
11597 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11599 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11601 // Only non-legal VSELECTs reach this lowering, convert those into generic
11602 // shuffles and re-use the shuffle lowering path for blends.
11603 SmallVector<int, 32> Mask;
11604 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11605 SDValue CondElt = CondBV->getOperand(i);
11607 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11610 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11613 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11614 // A vselect where all conditions and data are constants can be optimized into
11615 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11616 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11617 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11618 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11621 // Try to lower this to a blend-style vector shuffle. This can handle all
11622 // constant condition cases.
11623 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11626 // Variable blends are only legal from SSE4.1 onward.
11627 if (!Subtarget->hasSSE41())
11630 // Only some types will be legal on some subtargets. If we can emit a legal
11631 // VSELECT-matching blend, return Op, and but if we need to expand, return
11633 switch (Op.getSimpleValueType().SimpleTy) {
11635 // Most of the vector types have blends past SSE4.1.
11639 // The byte blends for AVX vectors were introduced only in AVX2.
11640 if (Subtarget->hasAVX2())
11647 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11648 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11651 // FIXME: We should custom lower this by fixing the condition and using i8
11657 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11658 MVT VT = Op.getSimpleValueType();
11661 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11664 if (VT.getSizeInBits() == 8) {
11665 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11666 Op.getOperand(0), Op.getOperand(1));
11667 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11668 DAG.getValueType(VT));
11669 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11672 if (VT.getSizeInBits() == 16) {
11673 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11674 if (isNullConstant(Op.getOperand(1)))
11675 return DAG.getNode(
11676 ISD::TRUNCATE, dl, MVT::i16,
11677 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11678 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11679 Op.getOperand(1)));
11680 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11681 Op.getOperand(0), Op.getOperand(1));
11682 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11683 DAG.getValueType(VT));
11684 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11687 if (VT == MVT::f32) {
11688 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11689 // the result back to FR32 register. It's only worth matching if the
11690 // result has a single use which is a store or a bitcast to i32. And in
11691 // the case of a store, it's not worth it if the index is a constant 0,
11692 // because a MOVSSmr can be used instead, which is smaller and faster.
11693 if (!Op.hasOneUse())
11695 SDNode *User = *Op.getNode()->use_begin();
11696 if ((User->getOpcode() != ISD::STORE ||
11697 isNullConstant(Op.getOperand(1))) &&
11698 (User->getOpcode() != ISD::BITCAST ||
11699 User->getValueType(0) != MVT::i32))
11701 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11702 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11704 return DAG.getBitcast(MVT::f32, Extract);
11707 if (VT == MVT::i32 || VT == MVT::i64) {
11708 // ExtractPS/pextrq works with constant index.
11709 if (isa<ConstantSDNode>(Op.getOperand(1)))
11715 /// Extract one bit from mask vector, like v16i1 or v8i1.
11716 /// AVX-512 feature.
11718 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11719 SDValue Vec = Op.getOperand(0);
11721 MVT VecVT = Vec.getSimpleValueType();
11722 SDValue Idx = Op.getOperand(1);
11723 MVT EltVT = Op.getSimpleValueType();
11725 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11726 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11727 "Unexpected vector type in ExtractBitFromMaskVector");
11729 // variable index can't be handled in mask registers,
11730 // extend vector to VR512
11731 if (!isa<ConstantSDNode>(Idx)) {
11732 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11733 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11734 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11735 ExtVT.getVectorElementType(), Ext, Idx);
11736 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11739 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11740 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11741 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11742 rc = getRegClassFor(MVT::v16i1);
11743 unsigned MaxSift = rc->getSize()*8 - 1;
11744 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11745 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11746 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11747 DAG.getConstant(MaxSift, dl, MVT::i8));
11748 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11749 DAG.getIntPtrConstant(0, dl));
11753 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11754 SelectionDAG &DAG) const {
11756 SDValue Vec = Op.getOperand(0);
11757 MVT VecVT = Vec.getSimpleValueType();
11758 SDValue Idx = Op.getOperand(1);
11760 if (Op.getSimpleValueType() == MVT::i1)
11761 return ExtractBitFromMaskVector(Op, DAG);
11763 if (!isa<ConstantSDNode>(Idx)) {
11764 if (VecVT.is512BitVector() ||
11765 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11766 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11769 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11770 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11771 MaskEltVT.getSizeInBits());
11773 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11774 auto PtrVT = getPointerTy(DAG.getDataLayout());
11775 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11776 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11777 DAG.getConstant(0, dl, PtrVT));
11778 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11779 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11780 DAG.getConstant(0, dl, PtrVT));
11785 // If this is a 256-bit vector result, first extract the 128-bit vector and
11786 // then extract the element from the 128-bit vector.
11787 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11789 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11790 // Get the 128-bit vector.
11791 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11792 MVT EltVT = VecVT.getVectorElementType();
11794 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11795 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11797 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11798 // this can be done with a mask.
11799 IdxVal &= ElemsPerChunk - 1;
11800 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11801 DAG.getConstant(IdxVal, dl, MVT::i32));
11804 assert(VecVT.is128BitVector() && "Unexpected vector length");
11806 if (Subtarget->hasSSE41())
11807 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11810 MVT VT = Op.getSimpleValueType();
11811 // TODO: handle v16i8.
11812 if (VT.getSizeInBits() == 16) {
11813 SDValue Vec = Op.getOperand(0);
11814 if (isNullConstant(Op.getOperand(1)))
11815 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11816 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11817 DAG.getBitcast(MVT::v4i32, Vec),
11818 Op.getOperand(1)));
11819 // Transform it so it match pextrw which produces a 32-bit result.
11820 MVT EltVT = MVT::i32;
11821 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11822 Op.getOperand(0), Op.getOperand(1));
11823 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11824 DAG.getValueType(VT));
11825 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11828 if (VT.getSizeInBits() == 32) {
11829 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11833 // SHUFPS the element to the lowest double word, then movss.
11834 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11835 MVT VVT = Op.getOperand(0).getSimpleValueType();
11836 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11837 DAG.getUNDEF(VVT), Mask);
11838 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11839 DAG.getIntPtrConstant(0, dl));
11842 if (VT.getSizeInBits() == 64) {
11843 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11844 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11845 // to match extract_elt for f64.
11846 if (isNullConstant(Op.getOperand(1)))
11849 // UNPCKHPD the element to the lowest double word, then movsd.
11850 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11851 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11852 int Mask[2] = { 1, -1 };
11853 MVT VVT = Op.getOperand(0).getSimpleValueType();
11854 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11855 DAG.getUNDEF(VVT), Mask);
11856 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11857 DAG.getIntPtrConstant(0, dl));
11863 /// Insert one bit to mask vector, like v16i1 or v8i1.
11864 /// AVX-512 feature.
11866 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11868 SDValue Vec = Op.getOperand(0);
11869 SDValue Elt = Op.getOperand(1);
11870 SDValue Idx = Op.getOperand(2);
11871 MVT VecVT = Vec.getSimpleValueType();
11873 if (!isa<ConstantSDNode>(Idx)) {
11874 // Non constant index. Extend source and destination,
11875 // insert element and then truncate the result.
11876 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11877 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11878 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11879 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11880 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11881 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11884 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11885 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11887 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11888 DAG.getConstant(IdxVal, dl, MVT::i8));
11889 if (Vec.getOpcode() == ISD::UNDEF)
11891 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11894 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11895 SelectionDAG &DAG) const {
11896 MVT VT = Op.getSimpleValueType();
11897 MVT EltVT = VT.getVectorElementType();
11899 if (EltVT == MVT::i1)
11900 return InsertBitToMaskVector(Op, DAG);
11903 SDValue N0 = Op.getOperand(0);
11904 SDValue N1 = Op.getOperand(1);
11905 SDValue N2 = Op.getOperand(2);
11906 if (!isa<ConstantSDNode>(N2))
11908 auto *N2C = cast<ConstantSDNode>(N2);
11909 unsigned IdxVal = N2C->getZExtValue();
11911 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11912 // into that, and then insert the subvector back into the result.
11913 if (VT.is256BitVector() || VT.is512BitVector()) {
11914 // With a 256-bit vector, we can insert into the zero element efficiently
11915 // using a blend if we have AVX or AVX2 and the right data type.
11916 if (VT.is256BitVector() && IdxVal == 0) {
11917 // TODO: It is worthwhile to cast integer to floating point and back
11918 // and incur a domain crossing penalty if that's what we'll end up
11919 // doing anyway after extracting to a 128-bit vector.
11920 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11921 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11922 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11923 N2 = DAG.getIntPtrConstant(1, dl);
11924 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11928 // Get the desired 128-bit vector chunk.
11929 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11931 // Insert the element into the desired chunk.
11932 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11933 assert(isPowerOf2_32(NumEltsIn128));
11934 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11935 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11937 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11938 DAG.getConstant(IdxIn128, dl, MVT::i32));
11940 // Insert the changed part back into the bigger vector
11941 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11943 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11945 if (Subtarget->hasSSE41()) {
11946 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11948 if (VT == MVT::v8i16) {
11949 Opc = X86ISD::PINSRW;
11951 assert(VT == MVT::v16i8);
11952 Opc = X86ISD::PINSRB;
11955 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11957 if (N1.getValueType() != MVT::i32)
11958 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11959 if (N2.getValueType() != MVT::i32)
11960 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11961 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11964 if (EltVT == MVT::f32) {
11965 // Bits [7:6] of the constant are the source select. This will always be
11966 // zero here. The DAG Combiner may combine an extract_elt index into
11967 // these bits. For example (insert (extract, 3), 2) could be matched by
11968 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11969 // Bits [5:4] of the constant are the destination select. This is the
11970 // value of the incoming immediate.
11971 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11972 // combine either bitwise AND or insert of float 0.0 to set these bits.
11974 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11975 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11976 // If this is an insertion of 32-bits into the low 32-bits of
11977 // a vector, we prefer to generate a blend with immediate rather
11978 // than an insertps. Blends are simpler operations in hardware and so
11979 // will always have equal or better performance than insertps.
11980 // But if optimizing for size and there's a load folding opportunity,
11981 // generate insertps because blendps does not have a 32-bit memory
11983 N2 = DAG.getIntPtrConstant(1, dl);
11984 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11985 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11987 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11988 // Create this as a scalar to vector..
11989 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11990 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11993 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11994 // PINSR* works with constant index.
11999 if (EltVT == MVT::i8)
12002 if (EltVT.getSizeInBits() == 16) {
12003 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12004 // as its second argument.
12005 if (N1.getValueType() != MVT::i32)
12006 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12007 if (N2.getValueType() != MVT::i32)
12008 N2 = DAG.getIntPtrConstant(IdxVal, dl);
12009 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12014 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12016 MVT OpVT = Op.getSimpleValueType();
12018 // If this is a 256-bit vector result, first insert into a 128-bit
12019 // vector and then insert into the 256-bit vector.
12020 if (!OpVT.is128BitVector()) {
12021 // Insert into a 128-bit vector.
12022 unsigned SizeFactor = OpVT.getSizeInBits()/128;
12023 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12024 OpVT.getVectorNumElements() / SizeFactor);
12026 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12028 // Insert the 128-bit vector.
12029 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12032 if (OpVT == MVT::v1i64 &&
12033 Op.getOperand(0).getValueType() == MVT::i64)
12034 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12036 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12037 assert(OpVT.is128BitVector() && "Expected an SSE type!");
12038 return DAG.getBitcast(
12039 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12042 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12043 // a simple subregister reference or explicit instructions to grab
12044 // upper bits of a vector.
12045 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12046 SelectionDAG &DAG) {
12048 SDValue In = Op.getOperand(0);
12049 SDValue Idx = Op.getOperand(1);
12050 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12051 MVT ResVT = Op.getSimpleValueType();
12052 MVT InVT = In.getSimpleValueType();
12054 if (Subtarget->hasFp256()) {
12055 if (ResVT.is128BitVector() &&
12056 (InVT.is256BitVector() || InVT.is512BitVector()) &&
12057 isa<ConstantSDNode>(Idx)) {
12058 return Extract128BitVector(In, IdxVal, DAG, dl);
12060 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12061 isa<ConstantSDNode>(Idx)) {
12062 return Extract256BitVector(In, IdxVal, DAG, dl);
12068 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12069 // simple superregister reference or explicit instructions to insert
12070 // the upper bits of a vector.
12071 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12072 SelectionDAG &DAG) {
12073 if (!Subtarget->hasAVX())
12077 SDValue Vec = Op.getOperand(0);
12078 SDValue SubVec = Op.getOperand(1);
12079 SDValue Idx = Op.getOperand(2);
12081 if (!isa<ConstantSDNode>(Idx))
12084 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12085 MVT OpVT = Op.getSimpleValueType();
12086 MVT SubVecVT = SubVec.getSimpleValueType();
12088 // Fold two 16-byte subvector loads into one 32-byte load:
12089 // (insert_subvector (insert_subvector undef, (load addr), 0),
12090 // (load addr + 16), Elts/2)
12092 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12093 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12094 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12095 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12096 if (Idx2 && Idx2->getZExtValue() == 0) {
12097 SDValue SubVec2 = Vec.getOperand(1);
12098 // If needed, look through a bitcast to get to the load.
12099 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12100 SubVec2 = SubVec2.getOperand(0);
12102 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12104 unsigned Alignment = FirstLd->getAlignment();
12105 unsigned AS = FirstLd->getAddressSpace();
12106 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12107 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12108 OpVT, AS, Alignment, &Fast) && Fast) {
12109 SDValue Ops[] = { SubVec2, SubVec };
12110 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12117 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12118 SubVecVT.is128BitVector())
12119 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12121 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12122 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12124 if (OpVT.getVectorElementType() == MVT::i1)
12125 return Insert1BitVector(Op, DAG);
12130 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12131 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12132 // one of the above mentioned nodes. It has to be wrapped because otherwise
12133 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12134 // be used to form addressing mode. These wrapped nodes will be selected
12137 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12138 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12140 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12141 // global base reg.
12142 unsigned char OpFlag = 0;
12143 unsigned WrapperKind = X86ISD::Wrapper;
12144 CodeModel::Model M = DAG.getTarget().getCodeModel();
12146 if (Subtarget->isPICStyleRIPRel() &&
12147 (M == CodeModel::Small || M == CodeModel::Kernel))
12148 WrapperKind = X86ISD::WrapperRIP;
12149 else if (Subtarget->isPICStyleGOT())
12150 OpFlag = X86II::MO_GOTOFF;
12151 else if (Subtarget->isPICStyleStubPIC())
12152 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12154 auto PtrVT = getPointerTy(DAG.getDataLayout());
12155 SDValue Result = DAG.getTargetConstantPool(
12156 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12158 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12159 // With PIC, the address is actually $g + Offset.
12162 DAG.getNode(ISD::ADD, DL, PtrVT,
12163 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12169 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12170 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12172 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12173 // global base reg.
12174 unsigned char OpFlag = 0;
12175 unsigned WrapperKind = X86ISD::Wrapper;
12176 CodeModel::Model M = DAG.getTarget().getCodeModel();
12178 if (Subtarget->isPICStyleRIPRel() &&
12179 (M == CodeModel::Small || M == CodeModel::Kernel))
12180 WrapperKind = X86ISD::WrapperRIP;
12181 else if (Subtarget->isPICStyleGOT())
12182 OpFlag = X86II::MO_GOTOFF;
12183 else if (Subtarget->isPICStyleStubPIC())
12184 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12186 auto PtrVT = getPointerTy(DAG.getDataLayout());
12187 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12189 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12191 // With PIC, the address is actually $g + Offset.
12194 DAG.getNode(ISD::ADD, DL, PtrVT,
12195 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12201 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12202 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12204 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12205 // global base reg.
12206 unsigned char OpFlag = 0;
12207 unsigned WrapperKind = X86ISD::Wrapper;
12208 CodeModel::Model M = DAG.getTarget().getCodeModel();
12210 if (Subtarget->isPICStyleRIPRel() &&
12211 (M == CodeModel::Small || M == CodeModel::Kernel)) {
12212 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12213 OpFlag = X86II::MO_GOTPCREL;
12214 WrapperKind = X86ISD::WrapperRIP;
12215 } else if (Subtarget->isPICStyleGOT()) {
12216 OpFlag = X86II::MO_GOT;
12217 } else if (Subtarget->isPICStyleStubPIC()) {
12218 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12219 } else if (Subtarget->isPICStyleStubNoDynamic()) {
12220 OpFlag = X86II::MO_DARWIN_NONLAZY;
12223 auto PtrVT = getPointerTy(DAG.getDataLayout());
12224 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12227 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12229 // With PIC, the address is actually $g + Offset.
12230 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12231 !Subtarget->is64Bit()) {
12233 DAG.getNode(ISD::ADD, DL, PtrVT,
12234 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12237 // For symbols that require a load from a stub to get the address, emit the
12239 if (isGlobalStubReference(OpFlag))
12240 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12241 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12242 false, false, false, 0);
12248 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12249 // Create the TargetBlockAddressAddress node.
12250 unsigned char OpFlags =
12251 Subtarget->ClassifyBlockAddressReference();
12252 CodeModel::Model M = DAG.getTarget().getCodeModel();
12253 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12254 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12256 auto PtrVT = getPointerTy(DAG.getDataLayout());
12257 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12259 if (Subtarget->isPICStyleRIPRel() &&
12260 (M == CodeModel::Small || M == CodeModel::Kernel))
12261 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12263 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12265 // With PIC, the address is actually $g + Offset.
12266 if (isGlobalRelativeToPICBase(OpFlags)) {
12267 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12268 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12275 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12276 int64_t Offset, SelectionDAG &DAG) const {
12277 // Create the TargetGlobalAddress node, folding in the constant
12278 // offset if it is legal.
12279 unsigned char OpFlags =
12280 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12281 CodeModel::Model M = DAG.getTarget().getCodeModel();
12282 auto PtrVT = getPointerTy(DAG.getDataLayout());
12284 if (OpFlags == X86II::MO_NO_FLAG &&
12285 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12286 // A direct static reference to a global.
12287 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12290 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12293 if (Subtarget->isPICStyleRIPRel() &&
12294 (M == CodeModel::Small || M == CodeModel::Kernel))
12295 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12297 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12299 // With PIC, the address is actually $g + Offset.
12300 if (isGlobalRelativeToPICBase(OpFlags)) {
12301 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12302 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12305 // For globals that require a load from a stub to get the address, emit the
12307 if (isGlobalStubReference(OpFlags))
12308 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12309 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12310 false, false, false, 0);
12312 // If there was a non-zero offset that we didn't fold, create an explicit
12313 // addition for it.
12315 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12316 DAG.getConstant(Offset, dl, PtrVT));
12322 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12323 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12324 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12325 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12329 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12330 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12331 unsigned char OperandFlags, bool LocalDynamic = false) {
12332 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12336 GA->getValueType(0),
12340 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12344 SDValue Ops[] = { Chain, TGA, *InFlag };
12345 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12347 SDValue Ops[] = { Chain, TGA };
12348 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12351 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12352 MFI->setAdjustsStack(true);
12353 MFI->setHasCalls(true);
12355 SDValue Flag = Chain.getValue(1);
12356 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12359 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12361 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12364 SDLoc dl(GA); // ? function entry point might be better
12365 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12366 DAG.getNode(X86ISD::GlobalBaseReg,
12367 SDLoc(), PtrVT), InFlag);
12368 InFlag = Chain.getValue(1);
12370 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12373 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12375 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12377 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12378 X86::RAX, X86II::MO_TLSGD);
12381 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12387 // Get the start address of the TLS block for this module.
12388 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12389 .getInfo<X86MachineFunctionInfo>();
12390 MFI->incNumLocalDynamicTLSAccesses();
12394 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12395 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12398 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12399 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12400 InFlag = Chain.getValue(1);
12401 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12402 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12405 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12409 unsigned char OperandFlags = X86II::MO_DTPOFF;
12410 unsigned WrapperKind = X86ISD::Wrapper;
12411 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12412 GA->getValueType(0),
12413 GA->getOffset(), OperandFlags);
12414 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12416 // Add x@dtpoff with the base.
12417 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12420 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12421 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12422 const EVT PtrVT, TLSModel::Model model,
12423 bool is64Bit, bool isPIC) {
12426 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12427 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12428 is64Bit ? 257 : 256));
12430 SDValue ThreadPointer =
12431 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12432 MachinePointerInfo(Ptr), false, false, false, 0);
12434 unsigned char OperandFlags = 0;
12435 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12437 unsigned WrapperKind = X86ISD::Wrapper;
12438 if (model == TLSModel::LocalExec) {
12439 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12440 } else if (model == TLSModel::InitialExec) {
12442 OperandFlags = X86II::MO_GOTTPOFF;
12443 WrapperKind = X86ISD::WrapperRIP;
12445 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12448 llvm_unreachable("Unexpected model");
12451 // emit "addl x@ntpoff,%eax" (local exec)
12452 // or "addl x@indntpoff,%eax" (initial exec)
12453 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12455 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12456 GA->getOffset(), OperandFlags);
12457 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12459 if (model == TLSModel::InitialExec) {
12460 if (isPIC && !is64Bit) {
12461 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12462 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12466 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12467 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12468 false, false, false, 0);
12471 // The address of the thread local variable is the add of the thread
12472 // pointer with the offset of the variable.
12473 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12477 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12479 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12481 // Cygwin uses emutls.
12482 // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12483 if (Subtarget->isTargetWindowsCygwin())
12484 return LowerToTLSEmulatedModel(GA, DAG);
12486 const GlobalValue *GV = GA->getGlobal();
12487 auto PtrVT = getPointerTy(DAG.getDataLayout());
12489 if (Subtarget->isTargetELF()) {
12490 if (DAG.getTarget().Options.EmulatedTLS)
12491 return LowerToTLSEmulatedModel(GA, DAG);
12492 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12494 case TLSModel::GeneralDynamic:
12495 if (Subtarget->is64Bit())
12496 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12497 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12498 case TLSModel::LocalDynamic:
12499 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12500 Subtarget->is64Bit());
12501 case TLSModel::InitialExec:
12502 case TLSModel::LocalExec:
12503 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12504 DAG.getTarget().getRelocationModel() ==
12507 llvm_unreachable("Unknown TLS model.");
12510 if (Subtarget->isTargetDarwin()) {
12511 // Darwin only has one model of TLS. Lower to that.
12512 unsigned char OpFlag = 0;
12513 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12514 X86ISD::WrapperRIP : X86ISD::Wrapper;
12516 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12517 // global base reg.
12518 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12519 !Subtarget->is64Bit();
12521 OpFlag = X86II::MO_TLVP_PIC_BASE;
12523 OpFlag = X86II::MO_TLVP;
12525 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12526 GA->getValueType(0),
12527 GA->getOffset(), OpFlag);
12528 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12530 // With PIC32, the address is actually $g + Offset.
12532 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12533 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12536 // Lowering the machine isd will make sure everything is in the right
12538 SDValue Chain = DAG.getEntryNode();
12539 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12540 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12541 SDValue Args[] = { Chain, Offset };
12542 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12544 DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12545 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12547 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12548 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12549 MFI->setAdjustsStack(true);
12551 // And our return value (tls address) is in the standard call return value
12553 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12554 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12557 if (Subtarget->isTargetKnownWindowsMSVC() ||
12558 Subtarget->isTargetWindowsGNU()) {
12559 // Just use the implicit TLS architecture
12560 // Need to generate someting similar to:
12561 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12563 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12564 // mov rcx, qword [rdx+rcx*8]
12565 // mov eax, .tls$:tlsvar
12566 // [rax+rcx] contains the address
12567 // Windows 64bit: gs:0x58
12568 // Windows 32bit: fs:__tls_array
12571 SDValue Chain = DAG.getEntryNode();
12573 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12574 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12575 // use its literal value of 0x2C.
12576 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12577 ? Type::getInt8PtrTy(*DAG.getContext(),
12579 : Type::getInt32PtrTy(*DAG.getContext(),
12582 SDValue TlsArray = Subtarget->is64Bit()
12583 ? DAG.getIntPtrConstant(0x58, dl)
12584 : (Subtarget->isTargetWindowsGNU()
12585 ? DAG.getIntPtrConstant(0x2C, dl)
12586 : DAG.getExternalSymbol("_tls_array", PtrVT));
12588 SDValue ThreadPointer =
12589 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12593 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12594 res = ThreadPointer;
12596 // Load the _tls_index variable
12597 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12598 if (Subtarget->is64Bit())
12599 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12600 MachinePointerInfo(), MVT::i32, false, false,
12603 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12606 auto &DL = DAG.getDataLayout();
12608 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12609 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12611 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12614 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12617 // Get the offset of start of .tls section
12618 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12619 GA->getValueType(0),
12620 GA->getOffset(), X86II::MO_SECREL);
12621 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12623 // The address of the thread local variable is the add of the thread
12624 // pointer with the offset of the variable.
12625 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12628 llvm_unreachable("TLS not implemented for this target.");
12631 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12632 /// and take a 2 x i32 value to shift plus a shift amount.
12633 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12634 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12635 MVT VT = Op.getSimpleValueType();
12636 unsigned VTBits = VT.getSizeInBits();
12638 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12639 SDValue ShOpLo = Op.getOperand(0);
12640 SDValue ShOpHi = Op.getOperand(1);
12641 SDValue ShAmt = Op.getOperand(2);
12642 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12643 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12645 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12646 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12647 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12648 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12649 : DAG.getConstant(0, dl, VT);
12651 SDValue Tmp2, Tmp3;
12652 if (Op.getOpcode() == ISD::SHL_PARTS) {
12653 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12654 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12656 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12657 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12660 // If the shift amount is larger or equal than the width of a part we can't
12661 // rely on the results of shld/shrd. Insert a test and select the appropriate
12662 // values for large shift amounts.
12663 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12664 DAG.getConstant(VTBits, dl, MVT::i8));
12665 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12666 AndNode, DAG.getConstant(0, dl, MVT::i8));
12669 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12670 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12671 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12673 if (Op.getOpcode() == ISD::SHL_PARTS) {
12674 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12675 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12677 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12678 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12681 SDValue Ops[2] = { Lo, Hi };
12682 return DAG.getMergeValues(Ops, dl);
12685 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12686 SelectionDAG &DAG) const {
12687 SDValue Src = Op.getOperand(0);
12688 MVT SrcVT = Src.getSimpleValueType();
12689 MVT VT = Op.getSimpleValueType();
12692 if (SrcVT.isVector()) {
12693 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12694 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12695 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12696 DAG.getUNDEF(SrcVT)));
12698 if (SrcVT.getVectorElementType() == MVT::i1) {
12699 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12700 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12701 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12706 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12707 "Unknown SINT_TO_FP to lower!");
12709 // These are really Legal; return the operand so the caller accepts it as
12711 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12713 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12714 Subtarget->is64Bit()) {
12718 SDValue ValueToStore = Op.getOperand(0);
12719 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12720 !Subtarget->is64Bit())
12721 // Bitcasting to f64 here allows us to do a single 64-bit store from
12722 // an SSE register, avoiding the store forwarding penalty that would come
12723 // with two 32-bit stores.
12724 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12726 unsigned Size = SrcVT.getSizeInBits()/8;
12727 MachineFunction &MF = DAG.getMachineFunction();
12728 auto PtrVT = getPointerTy(MF.getDataLayout());
12729 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12730 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12731 SDValue Chain = DAG.getStore(
12732 DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12733 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12735 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12738 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12740 SelectionDAG &DAG) const {
12744 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12746 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12748 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12750 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12752 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12753 MachineMemOperand *MMO;
12755 int SSFI = FI->getIndex();
12756 MMO = DAG.getMachineFunction().getMachineMemOperand(
12757 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12758 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12760 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12761 StackSlot = StackSlot.getOperand(1);
12763 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12764 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12766 Tys, Ops, SrcVT, MMO);
12769 Chain = Result.getValue(1);
12770 SDValue InFlag = Result.getValue(2);
12772 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12773 // shouldn't be necessary except that RFP cannot be live across
12774 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12775 MachineFunction &MF = DAG.getMachineFunction();
12776 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12777 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12778 auto PtrVT = getPointerTy(MF.getDataLayout());
12779 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12780 Tys = DAG.getVTList(MVT::Other);
12782 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12784 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12785 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12786 MachineMemOperand::MOStore, SSFISize, SSFISize);
12788 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12789 Ops, Op.getValueType(), MMO);
12790 Result = DAG.getLoad(
12791 Op.getValueType(), DL, Chain, StackSlot,
12792 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12793 false, false, false, 0);
12799 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12800 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12801 SelectionDAG &DAG) const {
12802 // This algorithm is not obvious. Here it is what we're trying to output:
12805 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12806 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12808 haddpd %xmm0, %xmm0
12810 pshufd $0x4e, %xmm0, %xmm1
12816 LLVMContext *Context = DAG.getContext();
12818 // Build some magic constants.
12819 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12820 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12821 auto PtrVT = getPointerTy(DAG.getDataLayout());
12822 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12824 SmallVector<Constant*,2> CV1;
12826 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12827 APInt(64, 0x4330000000000000ULL))));
12829 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12830 APInt(64, 0x4530000000000000ULL))));
12831 Constant *C1 = ConstantVector::get(CV1);
12832 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12834 // Load the 64-bit value into an XMM register.
12835 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12838 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12840 false, false, false, 16);
12842 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12845 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12846 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12847 false, false, false, 16);
12848 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12849 // TODO: Are there any fast-math-flags to propagate here?
12850 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12853 if (Subtarget->hasSSE3()) {
12854 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12855 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12857 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12858 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12860 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12861 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12865 DAG.getIntPtrConstant(0, dl));
12868 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12869 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12870 SelectionDAG &DAG) const {
12872 // FP constant to bias correct the final result.
12873 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12876 // Load the 32-bit value into an XMM register.
12877 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12880 // Zero out the upper parts of the register.
12881 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12883 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12884 DAG.getBitcast(MVT::v2f64, Load),
12885 DAG.getIntPtrConstant(0, dl));
12887 // Or the load with the bias.
12888 SDValue Or = DAG.getNode(
12889 ISD::OR, dl, MVT::v2i64,
12890 DAG.getBitcast(MVT::v2i64,
12891 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12892 DAG.getBitcast(MVT::v2i64,
12893 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12895 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12896 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12898 // Subtract the bias.
12899 // TODO: Are there any fast-math-flags to propagate here?
12900 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12902 // Handle final rounding.
12903 MVT DestVT = Op.getSimpleValueType();
12905 if (DestVT.bitsLT(MVT::f64))
12906 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12907 DAG.getIntPtrConstant(0, dl));
12908 if (DestVT.bitsGT(MVT::f64))
12909 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12911 // Handle final rounding.
12915 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12916 const X86Subtarget &Subtarget) {
12917 // The algorithm is the following:
12918 // #ifdef __SSE4_1__
12919 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12920 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12921 // (uint4) 0x53000000, 0xaa);
12923 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12924 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12926 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12927 // return (float4) lo + fhi;
12929 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12930 // reassociate the two FADDs, and if we do that, the algorithm fails
12931 // spectacularly (PR24512).
12932 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12933 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12934 // there's also the MachineCombiner reassociations happening on Machine IR.
12935 if (DAG.getTarget().Options.UnsafeFPMath)
12939 SDValue V = Op->getOperand(0);
12940 MVT VecIntVT = V.getSimpleValueType();
12941 bool Is128 = VecIntVT == MVT::v4i32;
12942 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12943 // If we convert to something else than the supported type, e.g., to v4f64,
12945 if (VecFloatVT != Op->getSimpleValueType(0))
12948 unsigned NumElts = VecIntVT.getVectorNumElements();
12949 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12950 "Unsupported custom type");
12951 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12953 // In the #idef/#else code, we have in common:
12954 // - The vector of constants:
12960 // Create the splat vector for 0x4b000000.
12961 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12962 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12963 CstLow, CstLow, CstLow, CstLow};
12964 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12965 makeArrayRef(&CstLowArray[0], NumElts));
12966 // Create the splat vector for 0x53000000.
12967 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12968 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12969 CstHigh, CstHigh, CstHigh, CstHigh};
12970 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12971 makeArrayRef(&CstHighArray[0], NumElts));
12973 // Create the right shift.
12974 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12975 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12976 CstShift, CstShift, CstShift, CstShift};
12977 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12978 makeArrayRef(&CstShiftArray[0], NumElts));
12979 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12982 if (Subtarget.hasSSE41()) {
12983 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12984 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12985 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12986 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12987 // Low will be bitcasted right away, so do not bother bitcasting back to its
12989 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12990 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12991 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12992 // (uint4) 0x53000000, 0xaa);
12993 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12994 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12995 // High will be bitcasted right away, so do not bother bitcasting back to
12996 // its original type.
12997 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12998 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
13000 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
13001 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13002 CstMask, CstMask, CstMask);
13003 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13004 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13005 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13007 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13008 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13011 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13012 SDValue CstFAdd = DAG.getConstantFP(
13013 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
13014 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13015 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13016 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13017 makeArrayRef(&CstFAddArray[0], NumElts));
13019 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13020 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13021 // TODO: Are there any fast-math-flags to propagate here?
13023 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13024 // return (float4) lo + fhi;
13025 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13026 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13029 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13030 SelectionDAG &DAG) const {
13031 SDValue N0 = Op.getOperand(0);
13032 MVT SVT = N0.getSimpleValueType();
13035 switch (SVT.SimpleTy) {
13037 llvm_unreachable("Custom UINT_TO_FP is not supported!");
13042 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13043 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13044 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13048 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13051 assert(Subtarget->hasAVX512());
13052 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13053 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13057 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13058 SelectionDAG &DAG) const {
13059 SDValue N0 = Op.getOperand(0);
13061 auto PtrVT = getPointerTy(DAG.getDataLayout());
13063 if (Op.getSimpleValueType().isVector())
13064 return lowerUINT_TO_FP_vec(Op, DAG);
13066 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13067 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13068 // the optimization here.
13069 if (DAG.SignBitIsZero(N0))
13070 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13072 MVT SrcVT = N0.getSimpleValueType();
13073 MVT DstVT = Op.getSimpleValueType();
13075 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13076 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13077 // Conversions from unsigned i32 to f32/f64 are legal,
13078 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13082 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13083 return LowerUINT_TO_FP_i64(Op, DAG);
13084 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13085 return LowerUINT_TO_FP_i32(Op, DAG);
13086 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13089 // Make a 64-bit buffer, and use it to build an FILD.
13090 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13091 if (SrcVT == MVT::i32) {
13092 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13093 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13094 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13095 StackSlot, MachinePointerInfo(),
13097 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13098 OffsetSlot, MachinePointerInfo(),
13100 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13104 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13105 SDValue ValueToStore = Op.getOperand(0);
13106 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13107 // Bitcasting to f64 here allows us to do a single 64-bit store from
13108 // an SSE register, avoiding the store forwarding penalty that would come
13109 // with two 32-bit stores.
13110 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13111 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13112 StackSlot, MachinePointerInfo(),
13114 // For i64 source, we need to add the appropriate power of 2 if the input
13115 // was negative. This is the same as the optimization in
13116 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13117 // we must be careful to do the computation in x87 extended precision, not
13118 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13119 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13120 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13121 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13122 MachineMemOperand::MOLoad, 8, 8);
13124 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13125 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13126 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13129 APInt FF(32, 0x5F800000ULL);
13131 // Check whether the sign bit is set.
13132 SDValue SignSet = DAG.getSetCC(
13133 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13134 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13136 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13137 SDValue FudgePtr = DAG.getConstantPool(
13138 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13140 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13141 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13142 SDValue Four = DAG.getIntPtrConstant(4, dl);
13143 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13145 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13147 // Load the value out, extending it from f32 to f80.
13148 // FIXME: Avoid the extend by constructing the right constant pool?
13149 SDValue Fudge = DAG.getExtLoad(
13150 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13151 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13152 false, false, false, 4);
13153 // Extend everything to 80 bits to force it to be done on x87.
13154 // TODO: Are there any fast-math-flags to propagate here?
13155 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13156 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13157 DAG.getIntPtrConstant(0, dl));
13160 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13161 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13162 // just return an <SDValue(), SDValue()> pair.
13163 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13164 // to i16, i32 or i64, and we lower it to a legal sequence.
13165 // If lowered to the final integer result we return a <result, SDValue()> pair.
13166 // Otherwise we lower it to a sequence ending with a FIST, return a
13167 // <FIST, StackSlot> pair, and the caller is responsible for loading
13168 // the final integer result from StackSlot.
13169 std::pair<SDValue,SDValue>
13170 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13171 bool IsSigned, bool IsReplace) const {
13174 EVT DstTy = Op.getValueType();
13175 EVT TheVT = Op.getOperand(0).getValueType();
13176 auto PtrVT = getPointerTy(DAG.getDataLayout());
13178 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13179 // f16 must be promoted before using the lowering in this routine.
13180 // fp128 does not use this lowering.
13181 return std::make_pair(SDValue(), SDValue());
13184 // If using FIST to compute an unsigned i64, we'll need some fixup
13185 // to handle values above the maximum signed i64. A FIST is always
13186 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13187 bool UnsignedFixup = !IsSigned &&
13188 DstTy == MVT::i64 &&
13189 (!Subtarget->is64Bit() ||
13190 !isScalarFPTypeInSSEReg(TheVT));
13192 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13193 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13194 // The low 32 bits of the fist result will have the correct uint32 result.
13195 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13199 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13200 DstTy.getSimpleVT() >= MVT::i16 &&
13201 "Unknown FP_TO_INT to lower!");
13203 // These are really Legal.
13204 if (DstTy == MVT::i32 &&
13205 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13206 return std::make_pair(SDValue(), SDValue());
13207 if (Subtarget->is64Bit() &&
13208 DstTy == MVT::i64 &&
13209 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13210 return std::make_pair(SDValue(), SDValue());
13212 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13214 MachineFunction &MF = DAG.getMachineFunction();
13215 unsigned MemSize = DstTy.getSizeInBits()/8;
13216 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13217 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13220 switch (DstTy.getSimpleVT().SimpleTy) {
13221 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13222 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13223 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13224 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13227 SDValue Chain = DAG.getEntryNode();
13228 SDValue Value = Op.getOperand(0);
13229 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13231 if (UnsignedFixup) {
13233 // Conversion to unsigned i64 is implemented with a select,
13234 // depending on whether the source value fits in the range
13235 // of a signed i64. Let Thresh be the FP equivalent of
13236 // 0x8000000000000000ULL.
13238 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13239 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13240 // Fist-to-mem64 FistSrc
13241 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13242 // to XOR'ing the high 32 bits with Adjust.
13244 // Being a power of 2, Thresh is exactly representable in all FP formats.
13245 // For X87 we'd like to use the smallest FP type for this constant, but
13246 // for DAG type consistency we have to match the FP operand type.
13248 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13249 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13250 bool LosesInfo = false;
13251 if (TheVT == MVT::f64)
13252 // The rounding mode is irrelevant as the conversion should be exact.
13253 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13255 else if (TheVT == MVT::f80)
13256 Status = Thresh.convert(APFloat::x87DoubleExtended,
13257 APFloat::rmNearestTiesToEven, &LosesInfo);
13259 assert(Status == APFloat::opOK && !LosesInfo &&
13260 "FP conversion should have been exact");
13262 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13264 SDValue Cmp = DAG.getSetCC(DL,
13265 getSetCCResultType(DAG.getDataLayout(),
13266 *DAG.getContext(), TheVT),
13267 Value, ThreshVal, ISD::SETLT);
13268 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13269 DAG.getConstant(0, DL, MVT::i32),
13270 DAG.getConstant(0x80000000, DL, MVT::i32));
13271 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13272 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13273 *DAG.getContext(), TheVT),
13274 Value, ThreshVal, ISD::SETLT);
13275 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13278 // FIXME This causes a redundant load/store if the SSE-class value is already
13279 // in memory, such as if it is on the callstack.
13280 if (isScalarFPTypeInSSEReg(TheVT)) {
13281 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13282 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13283 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13285 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13287 Chain, StackSlot, DAG.getValueType(TheVT)
13290 MachineMemOperand *MMO =
13291 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13292 MachineMemOperand::MOLoad, MemSize, MemSize);
13293 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13294 Chain = Value.getValue(1);
13295 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13296 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13299 MachineMemOperand *MMO =
13300 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13301 MachineMemOperand::MOStore, MemSize, MemSize);
13303 if (UnsignedFixup) {
13305 // Insert the FIST, load its result as two i32's,
13306 // and XOR the high i32 with Adjust.
13308 SDValue FistOps[] = { Chain, Value, StackSlot };
13309 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13310 FistOps, DstTy, MMO);
13312 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13313 MachinePointerInfo(),
13314 false, false, false, 0);
13315 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13316 DAG.getConstant(4, DL, PtrVT));
13318 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13319 MachinePointerInfo(),
13320 false, false, false, 0);
13321 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13323 if (Subtarget->is64Bit()) {
13324 // Join High32 and Low32 into a 64-bit result.
13325 // (High32 << 32) | Low32
13326 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13327 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13328 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13329 DAG.getConstant(32, DL, MVT::i8));
13330 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13331 return std::make_pair(Result, SDValue());
13334 SDValue ResultOps[] = { Low32, High32 };
13336 SDValue pair = IsReplace
13337 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13338 : DAG.getMergeValues(ResultOps, DL);
13339 return std::make_pair(pair, SDValue());
13341 // Build the FP_TO_INT*_IN_MEM
13342 SDValue Ops[] = { Chain, Value, StackSlot };
13343 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13345 return std::make_pair(FIST, StackSlot);
13349 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13350 const X86Subtarget *Subtarget) {
13351 MVT VT = Op->getSimpleValueType(0);
13352 SDValue In = Op->getOperand(0);
13353 MVT InVT = In.getSimpleValueType();
13356 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13357 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13359 // Optimize vectors in AVX mode:
13362 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13363 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13364 // Concat upper and lower parts.
13367 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13368 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13369 // Concat upper and lower parts.
13372 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13373 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13374 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13377 if (Subtarget->hasInt256())
13378 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13380 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13381 SDValue Undef = DAG.getUNDEF(InVT);
13382 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13383 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13384 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13386 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13387 VT.getVectorNumElements()/2);
13389 OpLo = DAG.getBitcast(HVT, OpLo);
13390 OpHi = DAG.getBitcast(HVT, OpHi);
13392 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13395 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13396 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13397 MVT VT = Op->getSimpleValueType(0);
13398 SDValue In = Op->getOperand(0);
13399 MVT InVT = In.getSimpleValueType();
13401 unsigned int NumElts = VT.getVectorNumElements();
13402 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13405 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13406 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13408 assert(InVT.getVectorElementType() == MVT::i1);
13409 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13411 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13413 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13415 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13416 if (VT.is512BitVector())
13418 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13421 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13422 SelectionDAG &DAG) {
13423 if (Subtarget->hasFp256())
13424 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13430 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13431 SelectionDAG &DAG) {
13433 MVT VT = Op.getSimpleValueType();
13434 SDValue In = Op.getOperand(0);
13435 MVT SVT = In.getSimpleValueType();
13437 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13438 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13440 if (Subtarget->hasFp256())
13441 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13444 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13445 VT.getVectorNumElements() != SVT.getVectorNumElements());
13449 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13450 const X86Subtarget *Subtarget) {
13453 MVT VT = Op.getSimpleValueType();
13454 SDValue In = Op.getOperand(0);
13455 MVT InVT = In.getSimpleValueType();
13457 assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13459 // Shift LSB to MSB and use VPMOVB2M - SKX.
13460 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13461 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13462 Subtarget->hasBWI()) || // legal, will go to VPMOVB2M, VPMOVW2M
13463 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13464 InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13465 Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13466 // Shift packed bytes not supported natively, bitcast to dword
13467 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13468 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13469 DAG.getBitcast(ExtVT, In),
13470 DAG.getConstant(ShiftInx, DL, ExtVT));
13471 ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13472 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13474 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13475 Subtarget->hasDQI()) || // legal, will go to VPMOVD2M, VPMOVQ2M
13476 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13477 InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13478 Subtarget->hasVLX())) { // legal, will go to VPMOVD2M, VPMOVQ2M
13480 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13481 DAG.getConstant(ShiftInx, DL, InVT));
13482 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13485 // Shift LSB to MSB, extend if necessary and use TESTM.
13486 unsigned NumElts = InVT.getVectorNumElements();
13487 if (InVT.getSizeInBits() < 512 &&
13488 (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13489 !Subtarget->hasVLX())) {
13490 assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13492 // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13493 // so vector should be extended to packed dword/qword.
13494 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13495 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13497 ShiftInx = InVT.getScalarSizeInBits() - 1;
13500 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13501 DAG.getConstant(ShiftInx, DL, InVT));
13502 return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13505 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13507 MVT VT = Op.getSimpleValueType();
13508 SDValue In = Op.getOperand(0);
13509 MVT InVT = In.getSimpleValueType();
13511 if (VT == MVT::i1) {
13512 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13513 "Invalid scalar TRUNCATE operation");
13514 if (InVT.getSizeInBits() >= 32)
13516 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13517 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13519 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13520 "Invalid TRUNCATE operation");
13522 if (VT.getVectorElementType() == MVT::i1)
13523 return LowerTruncateVecI1(Op, DAG, Subtarget);
13525 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13526 if (Subtarget->hasAVX512()) {
13527 // word to byte only under BWI
13528 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13529 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13530 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13531 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13533 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13534 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13535 if (Subtarget->hasInt256()) {
13536 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13537 In = DAG.getBitcast(MVT::v8i32, In);
13538 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13540 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13541 DAG.getIntPtrConstant(0, DL));
13544 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13545 DAG.getIntPtrConstant(0, DL));
13546 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13547 DAG.getIntPtrConstant(2, DL));
13548 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13549 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13550 static const int ShufMask[] = {0, 2, 4, 6};
13551 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13554 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13555 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13556 if (Subtarget->hasInt256()) {
13557 In = DAG.getBitcast(MVT::v32i8, In);
13559 SmallVector<SDValue,32> pshufbMask;
13560 for (unsigned i = 0; i < 2; ++i) {
13561 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13562 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13563 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13564 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13565 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13566 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13567 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13568 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13569 for (unsigned j = 0; j < 8; ++j)
13570 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13572 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13573 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13574 In = DAG.getBitcast(MVT::v4i64, In);
13576 static const int ShufMask[] = {0, 2, -1, -1};
13577 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13579 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13580 DAG.getIntPtrConstant(0, DL));
13581 return DAG.getBitcast(VT, In);
13584 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13585 DAG.getIntPtrConstant(0, DL));
13587 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13588 DAG.getIntPtrConstant(4, DL));
13590 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13591 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13593 // The PSHUFB mask:
13594 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13595 -1, -1, -1, -1, -1, -1, -1, -1};
13597 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13598 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13599 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13601 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13602 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13604 // The MOVLHPS Mask:
13605 static const int ShufMask2[] = {0, 1, 4, 5};
13606 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13607 return DAG.getBitcast(MVT::v8i16, res);
13610 // Handle truncation of V256 to V128 using shuffles.
13611 if (!VT.is128BitVector() || !InVT.is256BitVector())
13614 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13616 unsigned NumElems = VT.getVectorNumElements();
13617 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13619 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13620 // Prepare truncation shuffle mask
13621 for (unsigned i = 0; i != NumElems; ++i)
13622 MaskVec[i] = i * 2;
13623 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13624 DAG.getUNDEF(NVT), &MaskVec[0]);
13625 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13626 DAG.getIntPtrConstant(0, DL));
13629 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13630 SelectionDAG &DAG) const {
13631 assert(!Op.getSimpleValueType().isVector());
13633 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13634 /*IsSigned=*/ true, /*IsReplace=*/ false);
13635 SDValue FIST = Vals.first, StackSlot = Vals.second;
13636 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13637 if (!FIST.getNode())
13640 if (StackSlot.getNode())
13641 // Load the result.
13642 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13643 FIST, StackSlot, MachinePointerInfo(),
13644 false, false, false, 0);
13646 // The node is the result.
13650 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13651 SelectionDAG &DAG) const {
13652 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13653 /*IsSigned=*/ false, /*IsReplace=*/ false);
13654 SDValue FIST = Vals.first, StackSlot = Vals.second;
13655 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13656 if (!FIST.getNode())
13659 if (StackSlot.getNode())
13660 // Load the result.
13661 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13662 FIST, StackSlot, MachinePointerInfo(),
13663 false, false, false, 0);
13665 // The node is the result.
13669 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13671 MVT VT = Op.getSimpleValueType();
13672 SDValue In = Op.getOperand(0);
13673 MVT SVT = In.getSimpleValueType();
13675 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13677 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13678 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13679 In, DAG.getUNDEF(SVT)));
13682 /// The only differences between FABS and FNEG are the mask and the logic op.
13683 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13684 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13685 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13686 "Wrong opcode for lowering FABS or FNEG.");
13688 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13690 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13691 // into an FNABS. We'll lower the FABS after that if it is still in use.
13693 for (SDNode *User : Op->uses())
13694 if (User->getOpcode() == ISD::FNEG)
13698 MVT VT = Op.getSimpleValueType();
13700 bool IsF128 = (VT == MVT::f128);
13702 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13703 // decide if we should generate a 16-byte constant mask when we only need 4 or
13704 // 8 bytes for the scalar case.
13710 if (VT.isVector()) {
13712 EltVT = VT.getVectorElementType();
13713 NumElts = VT.getVectorNumElements();
13714 } else if (IsF128) {
13715 // SSE instructions are used for optimized f128 logical operations.
13716 LogicVT = MVT::f128;
13720 // There are no scalar bitwise logical SSE/AVX instructions, so we
13721 // generate a 16-byte vector constant and logic op even for the scalar case.
13722 // Using a 16-byte mask allows folding the load of the mask with
13723 // the logic op, so it can save (~4 bytes) on code size.
13724 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13726 NumElts = (VT == MVT::f64) ? 2 : 4;
13729 unsigned EltBits = EltVT.getSizeInBits();
13730 LLVMContext *Context = DAG.getContext();
13731 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13733 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13734 Constant *C = ConstantInt::get(*Context, MaskElt);
13735 C = ConstantVector::getSplat(NumElts, C);
13736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13737 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13738 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13740 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13741 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13742 false, false, false, Alignment);
13744 SDValue Op0 = Op.getOperand(0);
13745 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13747 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13748 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13750 if (VT.isVector() || IsF128)
13751 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13753 // For the scalar case extend to a 128-bit vector, perform the logic op,
13754 // and extract the scalar result back out.
13755 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13756 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13758 DAG.getIntPtrConstant(0, dl));
13761 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13763 LLVMContext *Context = DAG.getContext();
13764 SDValue Op0 = Op.getOperand(0);
13765 SDValue Op1 = Op.getOperand(1);
13767 MVT VT = Op.getSimpleValueType();
13768 MVT SrcVT = Op1.getSimpleValueType();
13769 bool IsF128 = (VT == MVT::f128);
13771 // If second operand is smaller, extend it first.
13772 if (SrcVT.bitsLT(VT)) {
13773 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13776 // And if it is bigger, shrink it first.
13777 if (SrcVT.bitsGT(VT)) {
13778 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13782 // At this point the operands and the result should have the same
13783 // type, and that won't be f80 since that is not custom lowered.
13784 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13785 "Unexpected type in LowerFCOPYSIGN");
13787 const fltSemantics &Sem =
13788 VT == MVT::f64 ? APFloat::IEEEdouble :
13789 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13790 const unsigned SizeInBits = VT.getSizeInBits();
13792 SmallVector<Constant *, 4> CV(
13793 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13794 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13796 // First, clear all bits but the sign bit from the second operand (sign).
13797 CV[0] = ConstantFP::get(*Context,
13798 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13799 Constant *C = ConstantVector::get(CV);
13800 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13801 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13803 // Perform all logic operations as 16-byte vectors because there are no
13804 // scalar FP logic instructions in SSE. This allows load folding of the
13805 // constants into the logic instructions.
13806 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13808 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13809 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13810 false, false, false, 16);
13812 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13813 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13815 // Next, clear the sign bit from the first operand (magnitude).
13816 // If it's a constant, we can clear it here.
13817 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13818 APFloat APF = Op0CN->getValueAPF();
13819 // If the magnitude is a positive zero, the sign bit alone is enough.
13820 if (APF.isPosZero())
13821 return IsF128 ? SignBit :
13822 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13823 DAG.getIntPtrConstant(0, dl));
13825 CV[0] = ConstantFP::get(*Context, APF);
13827 CV[0] = ConstantFP::get(
13829 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13831 C = ConstantVector::get(CV);
13832 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13834 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13835 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13836 false, false, false, 16);
13837 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13838 if (!isa<ConstantFPSDNode>(Op0)) {
13840 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13841 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13843 // OR the magnitude value with the sign bit.
13844 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13845 return IsF128 ? Val :
13846 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13847 DAG.getIntPtrConstant(0, dl));
13850 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13851 SDValue N0 = Op.getOperand(0);
13853 MVT VT = Op.getSimpleValueType();
13855 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13856 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13857 DAG.getConstant(1, dl, VT));
13858 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13861 // Check whether an OR'd tree is PTEST-able.
13862 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13863 SelectionDAG &DAG) {
13864 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13866 if (!Subtarget->hasSSE41())
13869 if (!Op->hasOneUse())
13872 SDNode *N = Op.getNode();
13875 SmallVector<SDValue, 8> Opnds;
13876 DenseMap<SDValue, unsigned> VecInMap;
13877 SmallVector<SDValue, 8> VecIns;
13878 EVT VT = MVT::Other;
13880 // Recognize a special case where a vector is casted into wide integer to
13882 Opnds.push_back(N->getOperand(0));
13883 Opnds.push_back(N->getOperand(1));
13885 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13886 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13887 // BFS traverse all OR'd operands.
13888 if (I->getOpcode() == ISD::OR) {
13889 Opnds.push_back(I->getOperand(0));
13890 Opnds.push_back(I->getOperand(1));
13891 // Re-evaluate the number of nodes to be traversed.
13892 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13896 // Quit if a non-EXTRACT_VECTOR_ELT
13897 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13900 // Quit if without a constant index.
13901 SDValue Idx = I->getOperand(1);
13902 if (!isa<ConstantSDNode>(Idx))
13905 SDValue ExtractedFromVec = I->getOperand(0);
13906 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13907 if (M == VecInMap.end()) {
13908 VT = ExtractedFromVec.getValueType();
13909 // Quit if not 128/256-bit vector.
13910 if (!VT.is128BitVector() && !VT.is256BitVector())
13912 // Quit if not the same type.
13913 if (VecInMap.begin() != VecInMap.end() &&
13914 VT != VecInMap.begin()->first.getValueType())
13916 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13917 VecIns.push_back(ExtractedFromVec);
13919 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13922 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13923 "Not extracted from 128-/256-bit vector.");
13925 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13927 for (DenseMap<SDValue, unsigned>::const_iterator
13928 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13929 // Quit if not all elements are used.
13930 if (I->second != FullMask)
13934 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13936 // Cast all vectors into TestVT for PTEST.
13937 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13938 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13940 // If more than one full vectors are evaluated, OR them first before PTEST.
13941 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13942 // Each iteration will OR 2 nodes and append the result until there is only
13943 // 1 node left, i.e. the final OR'd value of all vectors.
13944 SDValue LHS = VecIns[Slot];
13945 SDValue RHS = VecIns[Slot + 1];
13946 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13949 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13950 VecIns.back(), VecIns.back());
13953 /// \brief return true if \c Op has a use that doesn't just read flags.
13954 static bool hasNonFlagsUse(SDValue Op) {
13955 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13957 SDNode *User = *UI;
13958 unsigned UOpNo = UI.getOperandNo();
13959 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13960 // Look pass truncate.
13961 UOpNo = User->use_begin().getOperandNo();
13962 User = *User->use_begin();
13965 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13966 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13972 /// Emit nodes that will be selected as "test Op0,Op0", or something
13974 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13975 SelectionDAG &DAG) const {
13976 if (Op.getValueType() == MVT::i1) {
13977 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13978 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13979 DAG.getConstant(0, dl, MVT::i8));
13981 // CF and OF aren't always set the way we want. Determine which
13982 // of these we need.
13983 bool NeedCF = false;
13984 bool NeedOF = false;
13987 case X86::COND_A: case X86::COND_AE:
13988 case X86::COND_B: case X86::COND_BE:
13991 case X86::COND_G: case X86::COND_GE:
13992 case X86::COND_L: case X86::COND_LE:
13993 case X86::COND_O: case X86::COND_NO: {
13994 // Check if we really need to set the
13995 // Overflow flag. If NoSignedWrap is present
13996 // that is not actually needed.
13997 switch (Op->getOpcode()) {
14002 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14003 if (BinNode->Flags.hasNoSignedWrap())
14013 // See if we can use the EFLAGS value from the operand instead of
14014 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14015 // we prove that the arithmetic won't overflow, we can't use OF or CF.
14016 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14017 // Emit a CMP with 0, which is the TEST pattern.
14018 //if (Op.getValueType() == MVT::i1)
14019 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14020 // DAG.getConstant(0, MVT::i1));
14021 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14022 DAG.getConstant(0, dl, Op.getValueType()));
14024 unsigned Opcode = 0;
14025 unsigned NumOperands = 0;
14027 // Truncate operations may prevent the merge of the SETCC instruction
14028 // and the arithmetic instruction before it. Attempt to truncate the operands
14029 // of the arithmetic instruction and use a reduced bit-width instruction.
14030 bool NeedTruncation = false;
14031 SDValue ArithOp = Op;
14032 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14033 SDValue Arith = Op->getOperand(0);
14034 // Both the trunc and the arithmetic op need to have one user each.
14035 if (Arith->hasOneUse())
14036 switch (Arith.getOpcode()) {
14043 NeedTruncation = true;
14049 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14050 // which may be the result of a CAST. We use the variable 'Op', which is the
14051 // non-casted variable when we check for possible users.
14052 switch (ArithOp.getOpcode()) {
14054 // Due to an isel shortcoming, be conservative if this add is likely to be
14055 // selected as part of a load-modify-store instruction. When the root node
14056 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14057 // uses of other nodes in the match, such as the ADD in this case. This
14058 // leads to the ADD being left around and reselected, with the result being
14059 // two adds in the output. Alas, even if none our users are stores, that
14060 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14061 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14062 // climbing the DAG back to the root, and it doesn't seem to be worth the
14064 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14065 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14066 if (UI->getOpcode() != ISD::CopyToReg &&
14067 UI->getOpcode() != ISD::SETCC &&
14068 UI->getOpcode() != ISD::STORE)
14071 if (ConstantSDNode *C =
14072 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14073 // An add of one will be selected as an INC.
14074 if (C->isOne() && !Subtarget->slowIncDec()) {
14075 Opcode = X86ISD::INC;
14080 // An add of negative one (subtract of one) will be selected as a DEC.
14081 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14082 Opcode = X86ISD::DEC;
14088 // Otherwise use a regular EFLAGS-setting add.
14089 Opcode = X86ISD::ADD;
14094 // If we have a constant logical shift that's only used in a comparison
14095 // against zero turn it into an equivalent AND. This allows turning it into
14096 // a TEST instruction later.
14097 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14098 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14099 EVT VT = Op.getValueType();
14100 unsigned BitWidth = VT.getSizeInBits();
14101 unsigned ShAmt = Op->getConstantOperandVal(1);
14102 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14104 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14105 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14106 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14107 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14109 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14110 DAG.getConstant(Mask, dl, VT));
14111 DAG.ReplaceAllUsesWith(Op, New);
14117 // If the primary and result isn't used, don't bother using X86ISD::AND,
14118 // because a TEST instruction will be better.
14119 if (!hasNonFlagsUse(Op))
14125 // Due to the ISEL shortcoming noted above, be conservative if this op is
14126 // likely to be selected as part of a load-modify-store instruction.
14127 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14128 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14129 if (UI->getOpcode() == ISD::STORE)
14132 // Otherwise use a regular EFLAGS-setting instruction.
14133 switch (ArithOp.getOpcode()) {
14134 default: llvm_unreachable("unexpected operator!");
14135 case ISD::SUB: Opcode = X86ISD::SUB; break;
14136 case ISD::XOR: Opcode = X86ISD::XOR; break;
14137 case ISD::AND: Opcode = X86ISD::AND; break;
14139 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14140 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14141 if (EFLAGS.getNode())
14144 Opcode = X86ISD::OR;
14158 return SDValue(Op.getNode(), 1);
14164 // If we found that truncation is beneficial, perform the truncation and
14166 if (NeedTruncation) {
14167 EVT VT = Op.getValueType();
14168 SDValue WideVal = Op->getOperand(0);
14169 EVT WideVT = WideVal.getValueType();
14170 unsigned ConvertedOp = 0;
14171 // Use a target machine opcode to prevent further DAGCombine
14172 // optimizations that may separate the arithmetic operations
14173 // from the setcc node.
14174 switch (WideVal.getOpcode()) {
14176 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14177 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14178 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14179 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14180 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14184 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14185 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14186 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14187 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14188 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14194 // Emit a CMP with 0, which is the TEST pattern.
14195 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14196 DAG.getConstant(0, dl, Op.getValueType()));
14198 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14199 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14201 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14202 DAG.ReplaceAllUsesWith(Op, New);
14203 return SDValue(New.getNode(), 1);
14206 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14208 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14209 SDLoc dl, SelectionDAG &DAG) const {
14210 if (isNullConstant(Op1))
14211 return EmitTest(Op0, X86CC, dl, DAG);
14213 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14214 "Unexpected comparison operation for MVT::i1 operands");
14216 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14217 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14218 // Do the comparison at i32 if it's smaller, besides the Atom case.
14219 // This avoids subregister aliasing issues. Keep the smaller reference
14220 // if we're optimizing for size, however, as that'll allow better folding
14221 // of memory operations.
14222 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14223 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14224 !Subtarget->isAtom()) {
14225 unsigned ExtendOp =
14226 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14227 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14228 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14230 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14231 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14232 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14234 return SDValue(Sub.getNode(), 1);
14236 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14239 /// Convert a comparison if required by the subtarget.
14240 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14241 SelectionDAG &DAG) const {
14242 // If the subtarget does not support the FUCOMI instruction, floating-point
14243 // comparisons have to be converted.
14244 if (Subtarget->hasCMov() ||
14245 Cmp.getOpcode() != X86ISD::CMP ||
14246 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14247 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14250 // The instruction selector will select an FUCOM instruction instead of
14251 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14252 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14253 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14255 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14256 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14257 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14258 DAG.getConstant(8, dl, MVT::i8));
14259 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14261 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14262 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14263 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14266 /// The minimum architected relative accuracy is 2^-12. We need one
14267 /// Newton-Raphson step to have a good float result (24 bits of precision).
14268 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14269 DAGCombinerInfo &DCI,
14270 unsigned &RefinementSteps,
14271 bool &UseOneConstNR) const {
14272 EVT VT = Op.getValueType();
14273 const char *RecipOp;
14275 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14276 // TODO: Add support for AVX512 (v16f32).
14277 // It is likely not profitable to do this for f64 because a double-precision
14278 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14279 // instructions: convert to single, rsqrtss, convert back to double, refine
14280 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14281 // along with FMA, this could be a throughput win.
14282 if (VT == MVT::f32 && Subtarget->hasSSE1())
14284 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14285 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14286 RecipOp = "vec-sqrtf";
14290 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14291 if (!Recips.isEnabled(RecipOp))
14294 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14295 UseOneConstNR = false;
14296 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14299 /// The minimum architected relative accuracy is 2^-12. We need one
14300 /// Newton-Raphson step to have a good float result (24 bits of precision).
14301 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14302 DAGCombinerInfo &DCI,
14303 unsigned &RefinementSteps) const {
14304 EVT VT = Op.getValueType();
14305 const char *RecipOp;
14307 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14308 // TODO: Add support for AVX512 (v16f32).
14309 // It is likely not profitable to do this for f64 because a double-precision
14310 // reciprocal estimate with refinement on x86 prior to FMA requires
14311 // 15 instructions: convert to single, rcpss, convert back to double, refine
14312 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14313 // along with FMA, this could be a throughput win.
14314 if (VT == MVT::f32 && Subtarget->hasSSE1())
14316 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14317 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14318 RecipOp = "vec-divf";
14322 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14323 if (!Recips.isEnabled(RecipOp))
14326 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14327 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14330 /// If we have at least two divisions that use the same divisor, convert to
14331 /// multplication by a reciprocal. This may need to be adjusted for a given
14332 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14333 /// This is because we still need one division to calculate the reciprocal and
14334 /// then we need two multiplies by that reciprocal as replacements for the
14335 /// original divisions.
14336 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14340 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14341 /// if it's possible.
14342 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14343 SDLoc dl, SelectionDAG &DAG) const {
14344 SDValue Op0 = And.getOperand(0);
14345 SDValue Op1 = And.getOperand(1);
14346 if (Op0.getOpcode() == ISD::TRUNCATE)
14347 Op0 = Op0.getOperand(0);
14348 if (Op1.getOpcode() == ISD::TRUNCATE)
14349 Op1 = Op1.getOperand(0);
14352 if (Op1.getOpcode() == ISD::SHL)
14353 std::swap(Op0, Op1);
14354 if (Op0.getOpcode() == ISD::SHL) {
14355 if (isOneConstant(Op0.getOperand(0))) {
14356 // If we looked past a truncate, check that it's only truncating away
14358 unsigned BitWidth = Op0.getValueSizeInBits();
14359 unsigned AndBitWidth = And.getValueSizeInBits();
14360 if (BitWidth > AndBitWidth) {
14362 DAG.computeKnownBits(Op0, Zeros, Ones);
14363 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14367 RHS = Op0.getOperand(1);
14369 } else if (Op1.getOpcode() == ISD::Constant) {
14370 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14371 uint64_t AndRHSVal = AndRHS->getZExtValue();
14372 SDValue AndLHS = Op0;
14374 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14375 LHS = AndLHS.getOperand(0);
14376 RHS = AndLHS.getOperand(1);
14379 // Use BT if the immediate can't be encoded in a TEST instruction.
14380 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14382 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14386 if (LHS.getNode()) {
14387 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14388 // instruction. Since the shift amount is in-range-or-undefined, we know
14389 // that doing a bittest on the i32 value is ok. We extend to i32 because
14390 // the encoding for the i16 version is larger than the i32 version.
14391 // Also promote i16 to i32 for performance / code size reason.
14392 if (LHS.getValueType() == MVT::i8 ||
14393 LHS.getValueType() == MVT::i16)
14394 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14396 // If the operand types disagree, extend the shift amount to match. Since
14397 // BT ignores high bits (like shifts) we can use anyextend.
14398 if (LHS.getValueType() != RHS.getValueType())
14399 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14401 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14402 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14403 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14404 DAG.getConstant(Cond, dl, MVT::i8), BT);
14410 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14412 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14417 // SSE Condition code mapping:
14426 switch (SetCCOpcode) {
14427 default: llvm_unreachable("Unexpected SETCC condition");
14429 case ISD::SETEQ: SSECC = 0; break;
14431 case ISD::SETGT: Swap = true; // Fallthrough
14433 case ISD::SETOLT: SSECC = 1; break;
14435 case ISD::SETGE: Swap = true; // Fallthrough
14437 case ISD::SETOLE: SSECC = 2; break;
14438 case ISD::SETUO: SSECC = 3; break;
14440 case ISD::SETNE: SSECC = 4; break;
14441 case ISD::SETULE: Swap = true; // Fallthrough
14442 case ISD::SETUGE: SSECC = 5; break;
14443 case ISD::SETULT: Swap = true; // Fallthrough
14444 case ISD::SETUGT: SSECC = 6; break;
14445 case ISD::SETO: SSECC = 7; break;
14447 case ISD::SETONE: SSECC = 8; break;
14450 std::swap(Op0, Op1);
14455 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14456 // ones, and then concatenate the result back.
14457 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14458 MVT VT = Op.getSimpleValueType();
14460 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14461 "Unsupported value type for operation");
14463 unsigned NumElems = VT.getVectorNumElements();
14465 SDValue CC = Op.getOperand(2);
14467 // Extract the LHS vectors
14468 SDValue LHS = Op.getOperand(0);
14469 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14470 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14472 // Extract the RHS vectors
14473 SDValue RHS = Op.getOperand(1);
14474 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14475 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14477 // Issue the operation on the smaller types and concatenate the result back
14478 MVT EltVT = VT.getVectorElementType();
14479 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14480 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14481 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14482 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14485 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14486 SDValue Op0 = Op.getOperand(0);
14487 SDValue Op1 = Op.getOperand(1);
14488 SDValue CC = Op.getOperand(2);
14489 MVT VT = Op.getSimpleValueType();
14492 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14493 "Unexpected type for boolean compare operation");
14494 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14495 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14496 DAG.getConstant(-1, dl, VT));
14497 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14498 DAG.getConstant(-1, dl, VT));
14499 switch (SetCCOpcode) {
14500 default: llvm_unreachable("Unexpected SETCC condition");
14502 // (x == y) -> ~(x ^ y)
14503 return DAG.getNode(ISD::XOR, dl, VT,
14504 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14505 DAG.getConstant(-1, dl, VT));
14507 // (x != y) -> (x ^ y)
14508 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14511 // (x > y) -> (x & ~y)
14512 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14515 // (x < y) -> (~x & y)
14516 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14519 // (x <= y) -> (~x | y)
14520 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14523 // (x >=y) -> (x | ~y)
14524 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14528 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14529 const X86Subtarget *Subtarget) {
14530 SDValue Op0 = Op.getOperand(0);
14531 SDValue Op1 = Op.getOperand(1);
14532 SDValue CC = Op.getOperand(2);
14533 MVT VT = Op.getSimpleValueType();
14536 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14537 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14538 "Cannot set masked compare for this operation");
14540 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14542 bool Unsigned = false;
14545 switch (SetCCOpcode) {
14546 default: llvm_unreachable("Unexpected SETCC condition");
14547 case ISD::SETNE: SSECC = 4; break;
14548 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14549 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14550 case ISD::SETLT: Swap = true; //fall-through
14551 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14552 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14553 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14554 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14555 case ISD::SETULE: Unsigned = true; //fall-through
14556 case ISD::SETLE: SSECC = 2; break;
14560 std::swap(Op0, Op1);
14562 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14563 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14564 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14565 DAG.getConstant(SSECC, dl, MVT::i8));
14568 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14569 /// operand \p Op1. If non-trivial (for example because it's not constant)
14570 /// return an empty value.
14571 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14573 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14577 MVT VT = Op1.getSimpleValueType();
14578 MVT EVT = VT.getVectorElementType();
14579 unsigned n = VT.getVectorNumElements();
14580 SmallVector<SDValue, 8> ULTOp1;
14582 for (unsigned i = 0; i < n; ++i) {
14583 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14584 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14587 // Avoid underflow.
14588 APInt Val = Elt->getAPIntValue();
14592 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14595 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14598 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14599 SelectionDAG &DAG) {
14600 SDValue Op0 = Op.getOperand(0);
14601 SDValue Op1 = Op.getOperand(1);
14602 SDValue CC = Op.getOperand(2);
14603 MVT VT = Op.getSimpleValueType();
14604 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14605 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14610 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14611 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14614 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14615 unsigned Opc = X86ISD::CMPP;
14616 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14617 assert(VT.getVectorNumElements() <= 16);
14618 Opc = X86ISD::CMPM;
14620 // In the two special cases we can't handle, emit two comparisons.
14623 unsigned CombineOpc;
14624 if (SetCCOpcode == ISD::SETUEQ) {
14625 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14627 assert(SetCCOpcode == ISD::SETONE);
14628 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14631 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14632 DAG.getConstant(CC0, dl, MVT::i8));
14633 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14634 DAG.getConstant(CC1, dl, MVT::i8));
14635 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14637 // Handle all other FP comparisons here.
14638 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14639 DAG.getConstant(SSECC, dl, MVT::i8));
14642 MVT VTOp0 = Op0.getSimpleValueType();
14643 assert(VTOp0 == Op1.getSimpleValueType() &&
14644 "Expected operands with same type!");
14645 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14646 "Invalid number of packed elements for source and destination!");
14648 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14649 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14650 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14651 // legalizer firstly checks if the first operand in input to the setcc has
14652 // a legal type. If so, then it promotes the return type to that same type.
14653 // Otherwise, the return type is promoted to the 'next legal type' which,
14654 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14656 // We reach this code only if the following two conditions are met:
14657 // 1. Both return type and operand type have been promoted to wider types
14658 // by the type legalizer.
14659 // 2. The original operand type has been promoted to a 256-bit vector.
14661 // Note that condition 2. only applies for AVX targets.
14662 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14663 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14666 // The non-AVX512 code below works under the assumption that source and
14667 // destination types are the same.
14668 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14669 "Value types for source and destination must be the same!");
14671 // Break 256-bit integer vector compare into smaller ones.
14672 if (VT.is256BitVector() && !Subtarget->hasInt256())
14673 return Lower256IntVSETCC(Op, DAG);
14675 MVT OpVT = Op1.getSimpleValueType();
14676 if (OpVT.getVectorElementType() == MVT::i1)
14677 return LowerBoolVSETCC_AVX512(Op, DAG);
14679 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14680 if (Subtarget->hasAVX512()) {
14681 if (Op1.getSimpleValueType().is512BitVector() ||
14682 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14683 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14684 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14686 // In AVX-512 architecture setcc returns mask with i1 elements,
14687 // But there is no compare instruction for i8 and i16 elements in KNL.
14688 // We are not talking about 512-bit operands in this case, these
14689 // types are illegal.
14691 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14692 OpVT.getVectorElementType().getSizeInBits() >= 8))
14693 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14694 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14697 // Lower using XOP integer comparisons.
14698 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14699 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14700 // Translate compare code to XOP PCOM compare mode.
14701 unsigned CmpMode = 0;
14702 switch (SetCCOpcode) {
14703 default: llvm_unreachable("Unexpected SETCC condition");
14705 case ISD::SETLT: CmpMode = 0x00; break;
14707 case ISD::SETLE: CmpMode = 0x01; break;
14709 case ISD::SETGT: CmpMode = 0x02; break;
14711 case ISD::SETGE: CmpMode = 0x03; break;
14712 case ISD::SETEQ: CmpMode = 0x04; break;
14713 case ISD::SETNE: CmpMode = 0x05; break;
14716 // Are we comparing unsigned or signed integers?
14717 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14718 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14720 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14721 DAG.getConstant(CmpMode, dl, MVT::i8));
14724 // We are handling one of the integer comparisons here. Since SSE only has
14725 // GT and EQ comparisons for integer, swapping operands and multiple
14726 // operations may be required for some comparisons.
14728 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14729 bool Subus = false;
14731 switch (SetCCOpcode) {
14732 default: llvm_unreachable("Unexpected SETCC condition");
14733 case ISD::SETNE: Invert = true;
14734 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14735 case ISD::SETLT: Swap = true;
14736 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14737 case ISD::SETGE: Swap = true;
14738 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14739 Invert = true; break;
14740 case ISD::SETULT: Swap = true;
14741 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14742 FlipSigns = true; break;
14743 case ISD::SETUGE: Swap = true;
14744 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14745 FlipSigns = true; Invert = true; break;
14748 // Special case: Use min/max operations for SETULE/SETUGE
14749 MVT VET = VT.getVectorElementType();
14751 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14752 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14755 switch (SetCCOpcode) {
14757 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14758 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14761 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14764 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14765 if (!MinMax && hasSubus) {
14766 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14768 // t = psubus Op0, Op1
14769 // pcmpeq t, <0..0>
14770 switch (SetCCOpcode) {
14772 case ISD::SETULT: {
14773 // If the comparison is against a constant we can turn this into a
14774 // setule. With psubus, setule does not require a swap. This is
14775 // beneficial because the constant in the register is no longer
14776 // destructed as the destination so it can be hoisted out of a loop.
14777 // Only do this pre-AVX since vpcmp* is no longer destructive.
14778 if (Subtarget->hasAVX())
14780 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14781 if (ULEOp1.getNode()) {
14783 Subus = true; Invert = false; Swap = false;
14787 // Psubus is better than flip-sign because it requires no inversion.
14788 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14789 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14793 Opc = X86ISD::SUBUS;
14799 std::swap(Op0, Op1);
14801 // Check that the operation in question is available (most are plain SSE2,
14802 // but PCMPGTQ and PCMPEQQ have different requirements).
14803 if (VT == MVT::v2i64) {
14804 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14805 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14807 // First cast everything to the right type.
14808 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14809 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14811 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14812 // bits of the inputs before performing those operations. The lower
14813 // compare is always unsigned.
14816 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14818 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14819 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14820 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14821 Sign, Zero, Sign, Zero);
14823 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14824 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14826 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14827 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14828 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14830 // Create masks for only the low parts/high parts of the 64 bit integers.
14831 static const int MaskHi[] = { 1, 1, 3, 3 };
14832 static const int MaskLo[] = { 0, 0, 2, 2 };
14833 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14834 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14835 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14837 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14838 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14841 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14843 return DAG.getBitcast(VT, Result);
14846 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14847 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14848 // pcmpeqd + pshufd + pand.
14849 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14851 // First cast everything to the right type.
14852 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14853 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14856 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14858 // Make sure the lower and upper halves are both all-ones.
14859 static const int Mask[] = { 1, 0, 3, 2 };
14860 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14861 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14864 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14866 return DAG.getBitcast(VT, Result);
14870 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14871 // bits of the inputs before performing those operations.
14873 MVT EltVT = VT.getVectorElementType();
14874 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14876 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14877 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14880 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14882 // If the logical-not of the result is required, perform that now.
14884 Result = DAG.getNOT(dl, Result, VT);
14887 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14890 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14891 getZeroVector(VT, Subtarget, DAG, dl));
14896 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14898 MVT VT = Op.getSimpleValueType();
14900 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14902 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14903 && "SetCC type must be 8-bit or 1-bit integer");
14904 SDValue Op0 = Op.getOperand(0);
14905 SDValue Op1 = Op.getOperand(1);
14907 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14909 // Optimize to BT if possible.
14910 // Lower (X & (1 << N)) == 0 to BT(X, N).
14911 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14912 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14913 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14914 isNullConstant(Op1) &&
14915 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14916 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14918 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14923 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14925 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14926 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14928 // If the input is a setcc, then reuse the input setcc or use a new one with
14929 // the inverted condition.
14930 if (Op0.getOpcode() == X86ISD::SETCC) {
14931 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14932 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14936 CCode = X86::GetOppositeBranchCondition(CCode);
14937 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14938 DAG.getConstant(CCode, dl, MVT::i8),
14939 Op0.getOperand(1));
14941 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14945 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14946 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14948 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14949 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14952 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14953 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14954 if (X86CC == X86::COND_INVALID)
14957 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14958 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14959 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14960 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14962 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14966 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14967 SDValue LHS = Op.getOperand(0);
14968 SDValue RHS = Op.getOperand(1);
14969 SDValue Carry = Op.getOperand(2);
14970 SDValue Cond = Op.getOperand(3);
14973 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14974 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14976 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14977 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14978 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14979 SDValue SetCC = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14980 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14981 if (Op.getSimpleValueType() == MVT::i1)
14982 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
14986 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14987 static bool isX86LogicalCmp(SDValue Op) {
14988 unsigned Opc = Op.getNode()->getOpcode();
14989 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14990 Opc == X86ISD::SAHF)
14992 if (Op.getResNo() == 1 &&
14993 (Opc == X86ISD::ADD ||
14994 Opc == X86ISD::SUB ||
14995 Opc == X86ISD::ADC ||
14996 Opc == X86ISD::SBB ||
14997 Opc == X86ISD::SMUL ||
14998 Opc == X86ISD::UMUL ||
14999 Opc == X86ISD::INC ||
15000 Opc == X86ISD::DEC ||
15001 Opc == X86ISD::OR ||
15002 Opc == X86ISD::XOR ||
15003 Opc == X86ISD::AND))
15006 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15012 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15013 if (V.getOpcode() != ISD::TRUNCATE)
15016 SDValue VOp0 = V.getOperand(0);
15017 unsigned InBits = VOp0.getValueSizeInBits();
15018 unsigned Bits = V.getValueSizeInBits();
15019 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15022 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15023 bool addTest = true;
15024 SDValue Cond = Op.getOperand(0);
15025 SDValue Op1 = Op.getOperand(1);
15026 SDValue Op2 = Op.getOperand(2);
15028 MVT VT = Op1.getSimpleValueType();
15031 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15032 // are available or VBLENDV if AVX is available.
15033 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15034 if (Cond.getOpcode() == ISD::SETCC &&
15035 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15036 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15037 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15038 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15039 int SSECC = translateX86FSETCC(
15040 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15043 if (Subtarget->hasAVX512()) {
15044 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15045 DAG.getConstant(SSECC, DL, MVT::i8));
15046 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15049 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15050 DAG.getConstant(SSECC, DL, MVT::i8));
15052 // If we have AVX, we can use a variable vector select (VBLENDV) instead
15053 // of 3 logic instructions for size savings and potentially speed.
15054 // Unfortunately, there is no scalar form of VBLENDV.
15056 // If either operand is a constant, don't try this. We can expect to
15057 // optimize away at least one of the logic instructions later in that
15058 // case, so that sequence would be faster than a variable blend.
15060 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15061 // uses XMM0 as the selection register. That may need just as many
15062 // instructions as the AND/ANDN/OR sequence due to register moves, so
15065 if (Subtarget->hasAVX() &&
15066 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15068 // Convert to vectors, do a VSELECT, and convert back to scalar.
15069 // All of the conversions should be optimized away.
15071 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15072 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15073 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15074 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15076 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15077 VCmp = DAG.getBitcast(VCmpVT, VCmp);
15079 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15081 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15082 VSel, DAG.getIntPtrConstant(0, DL));
15084 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15085 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15086 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15090 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15092 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15093 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15094 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15095 Op1Scalar = Op1.getOperand(0);
15097 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15098 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15099 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15100 Op2Scalar = Op2.getOperand(0);
15101 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15102 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15103 Op1Scalar.getValueType(),
15104 Cond, Op1Scalar, Op2Scalar);
15105 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15106 return DAG.getBitcast(VT, newSelect);
15107 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15108 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15109 DAG.getIntPtrConstant(0, DL));
15113 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15114 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15115 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15116 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15117 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15118 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15119 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15121 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15124 if (Cond.getOpcode() == ISD::SETCC) {
15125 SDValue NewCond = LowerSETCC(Cond, DAG);
15126 if (NewCond.getNode())
15130 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15131 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15132 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15133 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15134 if (Cond.getOpcode() == X86ISD::SETCC &&
15135 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15136 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15137 SDValue Cmp = Cond.getOperand(1);
15139 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15141 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15142 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15143 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15145 SDValue CmpOp0 = Cmp.getOperand(0);
15146 // Apply further optimizations for special cases
15147 // (select (x != 0), -1, 0) -> neg & sbb
15148 // (select (x == 0), 0, -1) -> neg & sbb
15149 if (isNullConstant(Y) &&
15150 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15151 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15152 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15153 DAG.getConstant(0, DL,
15154 CmpOp0.getValueType()),
15156 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15157 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15158 SDValue(Neg.getNode(), 1));
15162 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15163 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15164 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15166 SDValue Res = // Res = 0 or -1.
15167 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15168 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15170 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15171 Res = DAG.getNOT(DL, Res, Res.getValueType());
15173 if (!isNullConstant(Op2))
15174 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15179 // Look past (and (setcc_carry (cmp ...)), 1).
15180 if (Cond.getOpcode() == ISD::AND &&
15181 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15182 isOneConstant(Cond.getOperand(1)))
15183 Cond = Cond.getOperand(0);
15185 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15186 // setting operand in place of the X86ISD::SETCC.
15187 unsigned CondOpcode = Cond.getOpcode();
15188 if (CondOpcode == X86ISD::SETCC ||
15189 CondOpcode == X86ISD::SETCC_CARRY) {
15190 CC = Cond.getOperand(0);
15192 SDValue Cmp = Cond.getOperand(1);
15193 unsigned Opc = Cmp.getOpcode();
15194 MVT VT = Op.getSimpleValueType();
15196 bool IllegalFPCMov = false;
15197 if (VT.isFloatingPoint() && !VT.isVector() &&
15198 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15199 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15201 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15202 Opc == X86ISD::BT) { // FIXME
15206 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15207 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15208 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15209 Cond.getOperand(0).getValueType() != MVT::i8)) {
15210 SDValue LHS = Cond.getOperand(0);
15211 SDValue RHS = Cond.getOperand(1);
15212 unsigned X86Opcode;
15215 switch (CondOpcode) {
15216 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15217 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15218 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15219 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15220 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15221 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15222 default: llvm_unreachable("unexpected overflowing operator");
15224 if (CondOpcode == ISD::UMULO)
15225 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15228 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15230 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15232 if (CondOpcode == ISD::UMULO)
15233 Cond = X86Op.getValue(2);
15235 Cond = X86Op.getValue(1);
15237 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15242 // Look past the truncate if the high bits are known zero.
15243 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15244 Cond = Cond.getOperand(0);
15246 // We know the result of AND is compared against zero. Try to match
15248 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15249 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15250 CC = NewSetCC.getOperand(0);
15251 Cond = NewSetCC.getOperand(1);
15258 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15259 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15262 // a < b ? -1 : 0 -> RES = ~setcc_carry
15263 // a < b ? 0 : -1 -> RES = setcc_carry
15264 // a >= b ? -1 : 0 -> RES = setcc_carry
15265 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15266 if (Cond.getOpcode() == X86ISD::SUB) {
15267 Cond = ConvertCmpIfNecessary(Cond, DAG);
15268 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15270 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15271 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15272 (isNullConstant(Op1) || isNullConstant(Op2))) {
15273 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15274 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15276 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15277 return DAG.getNOT(DL, Res, Res.getValueType());
15282 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15283 // widen the cmov and push the truncate through. This avoids introducing a new
15284 // branch during isel and doesn't add any extensions.
15285 if (Op.getValueType() == MVT::i8 &&
15286 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15287 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15288 if (T1.getValueType() == T2.getValueType() &&
15289 // Blacklist CopyFromReg to avoid partial register stalls.
15290 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15291 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15292 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15293 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15297 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15298 // condition is true.
15299 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15300 SDValue Ops[] = { Op2, Op1, CC, Cond };
15301 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15304 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15305 const X86Subtarget *Subtarget,
15306 SelectionDAG &DAG) {
15307 MVT VT = Op->getSimpleValueType(0);
15308 SDValue In = Op->getOperand(0);
15309 MVT InVT = In.getSimpleValueType();
15310 MVT VTElt = VT.getVectorElementType();
15311 MVT InVTElt = InVT.getVectorElementType();
15315 if ((InVTElt == MVT::i1) &&
15316 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15317 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15319 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15320 VTElt.getSizeInBits() <= 16)) ||
15322 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15323 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15325 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15326 VTElt.getSizeInBits() >= 32))))
15327 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15329 unsigned int NumElts = VT.getVectorNumElements();
15331 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15334 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15335 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15336 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15337 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15340 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15341 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15343 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15346 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15348 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15349 if (VT.is512BitVector())
15351 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15354 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15355 const X86Subtarget *Subtarget,
15356 SelectionDAG &DAG) {
15357 SDValue In = Op->getOperand(0);
15358 MVT VT = Op->getSimpleValueType(0);
15359 MVT InVT = In.getSimpleValueType();
15360 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15362 MVT InSVT = InVT.getVectorElementType();
15363 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15365 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15367 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15372 // SSE41 targets can use the pmovsx* instructions directly.
15373 if (Subtarget->hasSSE41())
15374 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15376 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15380 // As SRAI is only available on i16/i32 types, we expand only up to i32
15381 // and handle i64 separately.
15382 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15383 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15384 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15385 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15386 Curr = DAG.getBitcast(CurrVT, Curr);
15389 SDValue SignExt = Curr;
15390 if (CurrVT != InVT) {
15391 unsigned SignExtShift =
15392 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15393 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15394 DAG.getConstant(SignExtShift, dl, MVT::i8));
15400 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15401 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15402 DAG.getConstant(31, dl, MVT::i8));
15403 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15404 return DAG.getBitcast(VT, Ext);
15410 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15411 SelectionDAG &DAG) {
15412 MVT VT = Op->getSimpleValueType(0);
15413 SDValue In = Op->getOperand(0);
15414 MVT InVT = In.getSimpleValueType();
15417 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15418 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15420 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15421 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15422 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15425 if (Subtarget->hasInt256())
15426 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15428 // Optimize vectors in AVX mode
15429 // Sign extend v8i16 to v8i32 and
15432 // Divide input vector into two parts
15433 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15434 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15435 // concat the vectors to original VT
15437 unsigned NumElems = InVT.getVectorNumElements();
15438 SDValue Undef = DAG.getUNDEF(InVT);
15440 SmallVector<int,8> ShufMask1(NumElems, -1);
15441 for (unsigned i = 0; i != NumElems/2; ++i)
15444 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15446 SmallVector<int,8> ShufMask2(NumElems, -1);
15447 for (unsigned i = 0; i != NumElems/2; ++i)
15448 ShufMask2[i] = i + NumElems/2;
15450 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15452 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15453 VT.getVectorNumElements()/2);
15455 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15456 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15458 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15461 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15462 // may emit an illegal shuffle but the expansion is still better than scalar
15463 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15464 // we'll emit a shuffle and a arithmetic shift.
15465 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15466 // TODO: It is possible to support ZExt by zeroing the undef values during
15467 // the shuffle phase or after the shuffle.
15468 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15469 SelectionDAG &DAG) {
15470 MVT RegVT = Op.getSimpleValueType();
15471 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15472 assert(RegVT.isInteger() &&
15473 "We only custom lower integer vector sext loads.");
15475 // Nothing useful we can do without SSE2 shuffles.
15476 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15478 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15480 EVT MemVT = Ld->getMemoryVT();
15481 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15482 unsigned RegSz = RegVT.getSizeInBits();
15484 ISD::LoadExtType Ext = Ld->getExtensionType();
15486 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15487 && "Only anyext and sext are currently implemented.");
15488 assert(MemVT != RegVT && "Cannot extend to the same type");
15489 assert(MemVT.isVector() && "Must load a vector from memory");
15491 unsigned NumElems = RegVT.getVectorNumElements();
15492 unsigned MemSz = MemVT.getSizeInBits();
15493 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15495 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15496 // The only way in which we have a legal 256-bit vector result but not the
15497 // integer 256-bit operations needed to directly lower a sextload is if we
15498 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15499 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15500 // correctly legalized. We do this late to allow the canonical form of
15501 // sextload to persist throughout the rest of the DAG combiner -- it wants
15502 // to fold together any extensions it can, and so will fuse a sign_extend
15503 // of an sextload into a sextload targeting a wider value.
15505 if (MemSz == 128) {
15506 // Just switch this to a normal load.
15507 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15508 "it must be a legal 128-bit vector "
15510 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15511 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15512 Ld->isInvariant(), Ld->getAlignment());
15514 assert(MemSz < 128 &&
15515 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15516 // Do an sext load to a 128-bit vector type. We want to use the same
15517 // number of elements, but elements half as wide. This will end up being
15518 // recursively lowered by this routine, but will succeed as we definitely
15519 // have all the necessary features if we're using AVX1.
15521 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15522 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15524 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15525 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15526 Ld->isNonTemporal(), Ld->isInvariant(),
15527 Ld->getAlignment());
15530 // Replace chain users with the new chain.
15531 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15532 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15534 // Finally, do a normal sign-extend to the desired register.
15535 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15538 // All sizes must be a power of two.
15539 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15540 "Non-power-of-two elements are not custom lowered!");
15542 // Attempt to load the original value using scalar loads.
15543 // Find the largest scalar type that divides the total loaded size.
15544 MVT SclrLoadTy = MVT::i8;
15545 for (MVT Tp : MVT::integer_valuetypes()) {
15546 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15551 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15552 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15554 SclrLoadTy = MVT::f64;
15556 // Calculate the number of scalar loads that we need to perform
15557 // in order to load our vector from memory.
15558 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15560 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15561 "Can only lower sext loads with a single scalar load!");
15563 unsigned loadRegZize = RegSz;
15564 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15567 // Represent our vector as a sequence of elements which are the
15568 // largest scalar that we can load.
15569 EVT LoadUnitVecVT = EVT::getVectorVT(
15570 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15572 // Represent the data using the same element type that is stored in
15573 // memory. In practice, we ''widen'' MemVT.
15575 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15576 loadRegZize / MemVT.getScalarSizeInBits());
15578 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15579 "Invalid vector type");
15581 // We can't shuffle using an illegal type.
15582 assert(TLI.isTypeLegal(WideVecVT) &&
15583 "We only lower types that form legal widened vector types");
15585 SmallVector<SDValue, 8> Chains;
15586 SDValue Ptr = Ld->getBasePtr();
15587 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15588 TLI.getPointerTy(DAG.getDataLayout()));
15589 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15591 for (unsigned i = 0; i < NumLoads; ++i) {
15592 // Perform a single load.
15593 SDValue ScalarLoad =
15594 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15595 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15596 Ld->getAlignment());
15597 Chains.push_back(ScalarLoad.getValue(1));
15598 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15599 // another round of DAGCombining.
15601 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15603 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15604 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15606 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15609 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15611 // Bitcast the loaded value to a vector of the original element type, in
15612 // the size of the target vector type.
15613 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15614 unsigned SizeRatio = RegSz / MemSz;
15616 if (Ext == ISD::SEXTLOAD) {
15617 // If we have SSE4.1, we can directly emit a VSEXT node.
15618 if (Subtarget->hasSSE41()) {
15619 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15620 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15624 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15626 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15627 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15629 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15630 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15634 // Redistribute the loaded elements into the different locations.
15635 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15636 for (unsigned i = 0; i != NumElems; ++i)
15637 ShuffleVec[i * SizeRatio] = i;
15639 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15640 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15642 // Bitcast to the requested type.
15643 Shuff = DAG.getBitcast(RegVT, Shuff);
15644 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15648 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15649 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15650 // from the AND / OR.
15651 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15652 Opc = Op.getOpcode();
15653 if (Opc != ISD::OR && Opc != ISD::AND)
15655 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15656 Op.getOperand(0).hasOneUse() &&
15657 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15658 Op.getOperand(1).hasOneUse());
15661 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15662 // 1 and that the SETCC node has a single use.
15663 static bool isXor1OfSetCC(SDValue Op) {
15664 if (Op.getOpcode() != ISD::XOR)
15666 if (isOneConstant(Op.getOperand(1)))
15667 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15668 Op.getOperand(0).hasOneUse();
15672 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15673 bool addTest = true;
15674 SDValue Chain = Op.getOperand(0);
15675 SDValue Cond = Op.getOperand(1);
15676 SDValue Dest = Op.getOperand(2);
15679 bool Inverted = false;
15681 if (Cond.getOpcode() == ISD::SETCC) {
15682 // Check for setcc([su]{add,sub,mul}o == 0).
15683 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15684 isNullConstant(Cond.getOperand(1)) &&
15685 Cond.getOperand(0).getResNo() == 1 &&
15686 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15687 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15688 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15689 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15690 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15691 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15693 Cond = Cond.getOperand(0);
15695 SDValue NewCond = LowerSETCC(Cond, DAG);
15696 if (NewCond.getNode())
15701 // FIXME: LowerXALUO doesn't handle these!!
15702 else if (Cond.getOpcode() == X86ISD::ADD ||
15703 Cond.getOpcode() == X86ISD::SUB ||
15704 Cond.getOpcode() == X86ISD::SMUL ||
15705 Cond.getOpcode() == X86ISD::UMUL)
15706 Cond = LowerXALUO(Cond, DAG);
15709 // Look pass (and (setcc_carry (cmp ...)), 1).
15710 if (Cond.getOpcode() == ISD::AND &&
15711 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15712 isOneConstant(Cond.getOperand(1)))
15713 Cond = Cond.getOperand(0);
15715 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15716 // setting operand in place of the X86ISD::SETCC.
15717 unsigned CondOpcode = Cond.getOpcode();
15718 if (CondOpcode == X86ISD::SETCC ||
15719 CondOpcode == X86ISD::SETCC_CARRY) {
15720 CC = Cond.getOperand(0);
15722 SDValue Cmp = Cond.getOperand(1);
15723 unsigned Opc = Cmp.getOpcode();
15724 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15725 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15729 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15733 // These can only come from an arithmetic instruction with overflow,
15734 // e.g. SADDO, UADDO.
15735 Cond = Cond.getNode()->getOperand(1);
15741 CondOpcode = Cond.getOpcode();
15742 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15743 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15744 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15745 Cond.getOperand(0).getValueType() != MVT::i8)) {
15746 SDValue LHS = Cond.getOperand(0);
15747 SDValue RHS = Cond.getOperand(1);
15748 unsigned X86Opcode;
15751 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15752 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15754 switch (CondOpcode) {
15755 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15757 if (isOneConstant(RHS)) {
15758 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15761 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15762 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15764 if (isOneConstant(RHS)) {
15765 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15768 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15769 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15770 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15771 default: llvm_unreachable("unexpected overflowing operator");
15774 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15775 if (CondOpcode == ISD::UMULO)
15776 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15779 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15781 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15783 if (CondOpcode == ISD::UMULO)
15784 Cond = X86Op.getValue(2);
15786 Cond = X86Op.getValue(1);
15788 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15792 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15793 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15794 if (CondOpc == ISD::OR) {
15795 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15796 // two branches instead of an explicit OR instruction with a
15798 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15799 isX86LogicalCmp(Cmp)) {
15800 CC = Cond.getOperand(0).getOperand(0);
15801 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15802 Chain, Dest, CC, Cmp);
15803 CC = Cond.getOperand(1).getOperand(0);
15807 } else { // ISD::AND
15808 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15809 // two branches instead of an explicit AND instruction with a
15810 // separate test. However, we only do this if this block doesn't
15811 // have a fall-through edge, because this requires an explicit
15812 // jmp when the condition is false.
15813 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15814 isX86LogicalCmp(Cmp) &&
15815 Op.getNode()->hasOneUse()) {
15816 X86::CondCode CCode =
15817 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15818 CCode = X86::GetOppositeBranchCondition(CCode);
15819 CC = DAG.getConstant(CCode, dl, MVT::i8);
15820 SDNode *User = *Op.getNode()->use_begin();
15821 // Look for an unconditional branch following this conditional branch.
15822 // We need this because we need to reverse the successors in order
15823 // to implement FCMP_OEQ.
15824 if (User->getOpcode() == ISD::BR) {
15825 SDValue FalseBB = User->getOperand(1);
15827 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15828 assert(NewBR == User);
15832 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15833 Chain, Dest, CC, Cmp);
15834 X86::CondCode CCode =
15835 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15836 CCode = X86::GetOppositeBranchCondition(CCode);
15837 CC = DAG.getConstant(CCode, dl, MVT::i8);
15843 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15844 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15845 // It should be transformed during dag combiner except when the condition
15846 // is set by a arithmetics with overflow node.
15847 X86::CondCode CCode =
15848 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15849 CCode = X86::GetOppositeBranchCondition(CCode);
15850 CC = DAG.getConstant(CCode, dl, MVT::i8);
15851 Cond = Cond.getOperand(0).getOperand(1);
15853 } else if (Cond.getOpcode() == ISD::SETCC &&
15854 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15855 // For FCMP_OEQ, we can emit
15856 // two branches instead of an explicit AND instruction with a
15857 // separate test. However, we only do this if this block doesn't
15858 // have a fall-through edge, because this requires an explicit
15859 // jmp when the condition is false.
15860 if (Op.getNode()->hasOneUse()) {
15861 SDNode *User = *Op.getNode()->use_begin();
15862 // Look for an unconditional branch following this conditional branch.
15863 // We need this because we need to reverse the successors in order
15864 // to implement FCMP_OEQ.
15865 if (User->getOpcode() == ISD::BR) {
15866 SDValue FalseBB = User->getOperand(1);
15868 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15869 assert(NewBR == User);
15873 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15874 Cond.getOperand(0), Cond.getOperand(1));
15875 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15876 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15877 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15878 Chain, Dest, CC, Cmp);
15879 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15884 } else if (Cond.getOpcode() == ISD::SETCC &&
15885 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15886 // For FCMP_UNE, we can emit
15887 // two branches instead of an explicit AND instruction with a
15888 // separate test. However, we only do this if this block doesn't
15889 // have a fall-through edge, because this requires an explicit
15890 // jmp when the condition is false.
15891 if (Op.getNode()->hasOneUse()) {
15892 SDNode *User = *Op.getNode()->use_begin();
15893 // Look for an unconditional branch following this conditional branch.
15894 // We need this because we need to reverse the successors in order
15895 // to implement FCMP_UNE.
15896 if (User->getOpcode() == ISD::BR) {
15897 SDValue FalseBB = User->getOperand(1);
15899 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15900 assert(NewBR == User);
15903 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15904 Cond.getOperand(0), Cond.getOperand(1));
15905 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15906 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15907 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15908 Chain, Dest, CC, Cmp);
15909 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15919 // Look pass the truncate if the high bits are known zero.
15920 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15921 Cond = Cond.getOperand(0);
15923 // We know the result of AND is compared against zero. Try to match
15925 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15926 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15927 CC = NewSetCC.getOperand(0);
15928 Cond = NewSetCC.getOperand(1);
15935 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15936 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15937 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15939 Cond = ConvertCmpIfNecessary(Cond, DAG);
15940 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15941 Chain, Dest, CC, Cond);
15944 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15945 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15946 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15947 // that the guard pages used by the OS virtual memory manager are allocated in
15948 // correct sequence.
15950 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15951 SelectionDAG &DAG) const {
15952 MachineFunction &MF = DAG.getMachineFunction();
15953 bool SplitStack = MF.shouldSplitStack();
15954 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15959 SDNode *Node = Op.getNode();
15960 SDValue Chain = Op.getOperand(0);
15961 SDValue Size = Op.getOperand(1);
15962 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15963 EVT VT = Node->getValueType(0);
15965 // Chain the dynamic stack allocation so that it doesn't modify the stack
15966 // pointer when other instructions are using the stack.
15967 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15969 bool Is64Bit = Subtarget->is64Bit();
15970 MVT SPTy = getPointerTy(DAG.getDataLayout());
15974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15975 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15976 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15977 " not tell us which reg is the stack pointer!");
15978 EVT VT = Node->getValueType(0);
15979 SDValue Tmp3 = Node->getOperand(2);
15981 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15982 Chain = SP.getValue(1);
15983 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15984 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15985 unsigned StackAlign = TFI.getStackAlignment();
15986 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15987 if (Align > StackAlign)
15988 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15989 DAG.getConstant(-(uint64_t)Align, dl, VT));
15990 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15991 } else if (SplitStack) {
15992 MachineRegisterInfo &MRI = MF.getRegInfo();
15995 // The 64 bit implementation of segmented stacks needs to clobber both r10
15996 // r11. This makes it impossible to use it along with nested parameters.
15997 const Function *F = MF.getFunction();
15999 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
16001 if (I->hasNestAttr())
16002 report_fatal_error("Cannot use segmented stacks with functions that "
16003 "have nested arguments.");
16006 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16007 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16008 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16009 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16010 DAG.getRegister(Vreg, SPTy));
16013 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16015 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16016 Flag = Chain.getValue(1);
16017 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16019 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16021 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16022 unsigned SPReg = RegInfo->getStackRegister();
16023 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16024 Chain = SP.getValue(1);
16027 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16028 DAG.getConstant(-(uint64_t)Align, dl, VT));
16029 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16035 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16036 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16038 SDValue Ops[2] = {Result, Chain};
16039 return DAG.getMergeValues(Ops, dl);
16042 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16043 MachineFunction &MF = DAG.getMachineFunction();
16044 auto PtrVT = getPointerTy(MF.getDataLayout());
16045 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16047 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16050 if (!Subtarget->is64Bit() ||
16051 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16052 // vastart just stores the address of the VarArgsFrameIndex slot into the
16053 // memory location argument.
16054 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16055 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16056 MachinePointerInfo(SV), false, false, 0);
16060 // gp_offset (0 - 6 * 8)
16061 // fp_offset (48 - 48 + 8 * 16)
16062 // overflow_arg_area (point to parameters coming in memory).
16064 SmallVector<SDValue, 8> MemOps;
16065 SDValue FIN = Op.getOperand(1);
16067 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16068 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16070 FIN, MachinePointerInfo(SV), false, false, 0);
16071 MemOps.push_back(Store);
16074 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16075 Store = DAG.getStore(Op.getOperand(0), DL,
16076 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16078 FIN, MachinePointerInfo(SV, 4), false, false, 0);
16079 MemOps.push_back(Store);
16081 // Store ptr to overflow_arg_area
16082 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16083 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16084 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16085 MachinePointerInfo(SV, 8),
16087 MemOps.push_back(Store);
16089 // Store ptr to reg_save_area.
16090 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16091 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16092 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16093 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16094 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16095 MemOps.push_back(Store);
16096 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16099 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16100 assert(Subtarget->is64Bit() &&
16101 "LowerVAARG only handles 64-bit va_arg!");
16102 assert(Op.getNode()->getNumOperands() == 4);
16104 MachineFunction &MF = DAG.getMachineFunction();
16105 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16106 // The Win64 ABI uses char* instead of a structure.
16107 return DAG.expandVAArg(Op.getNode());
16109 SDValue Chain = Op.getOperand(0);
16110 SDValue SrcPtr = Op.getOperand(1);
16111 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16112 unsigned Align = Op.getConstantOperandVal(3);
16115 EVT ArgVT = Op.getNode()->getValueType(0);
16116 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16117 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16120 // Decide which area this value should be read from.
16121 // TODO: Implement the AMD64 ABI in its entirety. This simple
16122 // selection mechanism works only for the basic types.
16123 if (ArgVT == MVT::f80) {
16124 llvm_unreachable("va_arg for f80 not yet implemented");
16125 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16126 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16127 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16128 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16130 llvm_unreachable("Unhandled argument type in LowerVAARG");
16133 if (ArgMode == 2) {
16134 // Sanity Check: Make sure using fp_offset makes sense.
16135 assert(!Subtarget->useSoftFloat() &&
16136 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16137 Subtarget->hasSSE1());
16140 // Insert VAARG_64 node into the DAG
16141 // VAARG_64 returns two values: Variable Argument Address, Chain
16142 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16143 DAG.getConstant(ArgMode, dl, MVT::i8),
16144 DAG.getConstant(Align, dl, MVT::i32)};
16145 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16146 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16147 VTs, InstOps, MVT::i64,
16148 MachinePointerInfo(SV),
16150 /*Volatile=*/false,
16152 /*WriteMem=*/true);
16153 Chain = VAARG.getValue(1);
16155 // Load the next argument and return it
16156 return DAG.getLoad(ArgVT, dl,
16159 MachinePointerInfo(),
16160 false, false, false, 0);
16163 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16164 SelectionDAG &DAG) {
16165 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16166 // where a va_list is still an i8*.
16167 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16168 if (Subtarget->isCallingConvWin64(
16169 DAG.getMachineFunction().getFunction()->getCallingConv()))
16170 // Probably a Win64 va_copy.
16171 return DAG.expandVACopy(Op.getNode());
16173 SDValue Chain = Op.getOperand(0);
16174 SDValue DstPtr = Op.getOperand(1);
16175 SDValue SrcPtr = Op.getOperand(2);
16176 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16177 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16180 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16181 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16183 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16186 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16187 // amount is a constant. Takes immediate version of shift as input.
16188 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16189 SDValue SrcOp, uint64_t ShiftAmt,
16190 SelectionDAG &DAG) {
16191 MVT ElementType = VT.getVectorElementType();
16193 // Fold this packed shift into its first operand if ShiftAmt is 0.
16197 // Check for ShiftAmt >= element width
16198 if (ShiftAmt >= ElementType.getSizeInBits()) {
16199 if (Opc == X86ISD::VSRAI)
16200 ShiftAmt = ElementType.getSizeInBits() - 1;
16202 return DAG.getConstant(0, dl, VT);
16205 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16206 && "Unknown target vector shift-by-constant node");
16208 // Fold this packed vector shift into a build vector if SrcOp is a
16209 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16210 if (VT == SrcOp.getSimpleValueType() &&
16211 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16212 SmallVector<SDValue, 8> Elts;
16213 unsigned NumElts = SrcOp->getNumOperands();
16214 ConstantSDNode *ND;
16217 default: llvm_unreachable(nullptr);
16218 case X86ISD::VSHLI:
16219 for (unsigned i=0; i!=NumElts; ++i) {
16220 SDValue CurrentOp = SrcOp->getOperand(i);
16221 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16222 Elts.push_back(CurrentOp);
16225 ND = cast<ConstantSDNode>(CurrentOp);
16226 const APInt &C = ND->getAPIntValue();
16227 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16230 case X86ISD::VSRLI:
16231 for (unsigned i=0; i!=NumElts; ++i) {
16232 SDValue CurrentOp = SrcOp->getOperand(i);
16233 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16234 Elts.push_back(CurrentOp);
16237 ND = cast<ConstantSDNode>(CurrentOp);
16238 const APInt &C = ND->getAPIntValue();
16239 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16242 case X86ISD::VSRAI:
16243 for (unsigned i=0; i!=NumElts; ++i) {
16244 SDValue CurrentOp = SrcOp->getOperand(i);
16245 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16246 Elts.push_back(CurrentOp);
16249 ND = cast<ConstantSDNode>(CurrentOp);
16250 const APInt &C = ND->getAPIntValue();
16251 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16256 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16259 return DAG.getNode(Opc, dl, VT, SrcOp,
16260 DAG.getConstant(ShiftAmt, dl, MVT::i8));
16263 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16264 // may or may not be a constant. Takes immediate version of shift as input.
16265 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16266 SDValue SrcOp, SDValue ShAmt,
16267 SelectionDAG &DAG) {
16268 MVT SVT = ShAmt.getSimpleValueType();
16269 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16271 // Catch shift-by-constant.
16272 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16273 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16274 CShAmt->getZExtValue(), DAG);
16276 // Change opcode to non-immediate version
16278 default: llvm_unreachable("Unknown target vector shift node");
16279 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16280 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16281 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16284 const X86Subtarget &Subtarget =
16285 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16286 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16287 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16288 // Let the shuffle legalizer expand this shift amount node.
16289 SDValue Op0 = ShAmt.getOperand(0);
16290 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16291 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16293 // Need to build a vector containing shift amount.
16294 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16295 SmallVector<SDValue, 4> ShOps;
16296 ShOps.push_back(ShAmt);
16297 if (SVT == MVT::i32) {
16298 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16299 ShOps.push_back(DAG.getUNDEF(SVT));
16301 ShOps.push_back(DAG.getUNDEF(SVT));
16303 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16304 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16307 // The return type has to be a 128-bit type with the same element
16308 // type as the input type.
16309 MVT EltVT = VT.getVectorElementType();
16310 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16312 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16313 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16316 /// \brief Return Mask with the necessary casting or extending
16317 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16318 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16319 const X86Subtarget *Subtarget,
16320 SelectionDAG &DAG, SDLoc dl) {
16322 if (isAllOnesConstant(Mask))
16323 return DAG.getTargetConstant(1, dl, MaskVT);
16324 if (X86::isZeroNode(Mask))
16325 return DAG.getTargetConstant(0, dl, MaskVT);
16327 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16328 // Mask should be extended
16329 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16330 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16333 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16334 if (MaskVT == MVT::v64i1) {
16335 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16336 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16338 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16339 DAG.getConstant(0, dl, MVT::i32));
16340 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16341 DAG.getConstant(1, dl, MVT::i32));
16343 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16344 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16346 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16348 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16350 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16351 return DAG.getBitcast(MaskVT,
16352 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16356 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16357 Mask.getSimpleValueType().getSizeInBits());
16358 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16359 // are extracted by EXTRACT_SUBVECTOR.
16360 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16361 DAG.getBitcast(BitcastVT, Mask),
16362 DAG.getIntPtrConstant(0, dl));
16366 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16367 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16368 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16369 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16370 SDValue PreservedSrc,
16371 const X86Subtarget *Subtarget,
16372 SelectionDAG &DAG) {
16373 MVT VT = Op.getSimpleValueType();
16374 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16375 unsigned OpcodeSelect = ISD::VSELECT;
16378 if (isAllOnesConstant(Mask))
16381 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16383 switch (Op.getOpcode()) {
16385 case X86ISD::PCMPEQM:
16386 case X86ISD::PCMPGTM:
16388 case X86ISD::CMPMU:
16389 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16390 case X86ISD::VFPCLASS:
16391 case X86ISD::VFPCLASSS:
16392 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16393 case X86ISD::VTRUNC:
16394 case X86ISD::VTRUNCS:
16395 case X86ISD::VTRUNCUS:
16396 // We can't use ISD::VSELECT here because it is not always "Legal"
16397 // for the destination type. For example vpmovqb require only AVX512
16398 // and vselect that can operate on byte element type require BWI
16399 OpcodeSelect = X86ISD::SELECT;
16402 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16403 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16404 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16407 /// \brief Creates an SDNode for a predicated scalar operation.
16408 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16409 /// The mask is coming as MVT::i8 and it should be truncated
16410 /// to MVT::i1 while lowering masking intrinsics.
16411 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16412 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16413 /// for a scalar instruction.
16414 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16415 SDValue PreservedSrc,
16416 const X86Subtarget *Subtarget,
16417 SelectionDAG &DAG) {
16418 if (isAllOnesConstant(Mask))
16421 MVT VT = Op.getSimpleValueType();
16423 // The mask should be of type MVT::i1
16424 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16426 if (Op.getOpcode() == X86ISD::FSETCC)
16427 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16428 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16429 Op.getOpcode() == X86ISD::VFPCLASSS)
16430 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16432 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16433 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16434 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16437 static int getSEHRegistrationNodeSize(const Function *Fn) {
16438 if (!Fn->hasPersonalityFn())
16439 report_fatal_error(
16440 "querying registration node size for function without personality");
16441 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16442 // WinEHStatePass for the full struct definition.
16443 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16444 case EHPersonality::MSVC_X86SEH: return 24;
16445 case EHPersonality::MSVC_CXX: return 16;
16448 report_fatal_error(
16449 "can only recover FP for 32-bit MSVC EH personality functions");
16452 /// When the MSVC runtime transfers control to us, either to an outlined
16453 /// function or when returning to a parent frame after catching an exception, we
16454 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16455 /// Here's the math:
16456 /// RegNodeBase = EntryEBP - RegNodeSize
16457 /// ParentFP = RegNodeBase - ParentFrameOffset
16458 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16459 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16460 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16461 SDValue EntryEBP) {
16462 MachineFunction &MF = DAG.getMachineFunction();
16465 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16466 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16468 // It's possible that the parent function no longer has a personality function
16469 // if the exceptional code was optimized away, in which case we just return
16470 // the incoming EBP.
16471 if (!Fn->hasPersonalityFn())
16474 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16475 // registration, or the .set_setframe offset.
16476 MCSymbol *OffsetSym =
16477 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16478 GlobalValue::getRealLinkageName(Fn->getName()));
16479 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16480 SDValue ParentFrameOffset =
16481 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16483 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16484 // prologue to RBP in the parent function.
16485 const X86Subtarget &Subtarget =
16486 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16487 if (Subtarget.is64Bit())
16488 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16490 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16491 // RegNodeBase = EntryEBP - RegNodeSize
16492 // ParentFP = RegNodeBase - ParentFrameOffset
16493 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16494 DAG.getConstant(RegNodeSize, dl, PtrVT));
16495 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16498 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16499 SelectionDAG &DAG) {
16501 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16502 MVT VT = Op.getSimpleValueType();
16503 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16505 switch(IntrData->Type) {
16506 case INTR_TYPE_1OP:
16507 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16508 case INTR_TYPE_2OP:
16509 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16511 case INTR_TYPE_2OP_IMM8:
16512 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16513 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16514 case INTR_TYPE_3OP:
16515 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16516 Op.getOperand(2), Op.getOperand(3));
16517 case INTR_TYPE_4OP:
16518 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16519 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16520 case INTR_TYPE_1OP_MASK_RM: {
16521 SDValue Src = Op.getOperand(1);
16522 SDValue PassThru = Op.getOperand(2);
16523 SDValue Mask = Op.getOperand(3);
16524 SDValue RoundingMode;
16525 // We allways add rounding mode to the Node.
16526 // If the rounding mode is not specified, we add the
16527 // "current direction" mode.
16528 if (Op.getNumOperands() == 4)
16530 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16532 RoundingMode = Op.getOperand(4);
16533 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16534 if (IntrWithRoundingModeOpcode != 0)
16535 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16536 X86::STATIC_ROUNDING::CUR_DIRECTION)
16537 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16538 dl, Op.getValueType(), Src, RoundingMode),
16539 Mask, PassThru, Subtarget, DAG);
16540 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16542 Mask, PassThru, Subtarget, DAG);
16544 case INTR_TYPE_1OP_MASK: {
16545 SDValue Src = Op.getOperand(1);
16546 SDValue PassThru = Op.getOperand(2);
16547 SDValue Mask = Op.getOperand(3);
16548 // We add rounding mode to the Node when
16549 // - RM Opcode is specified and
16550 // - RM is not "current direction".
16551 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16552 if (IntrWithRoundingModeOpcode != 0) {
16553 SDValue Rnd = Op.getOperand(4);
16554 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16555 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16556 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16557 dl, Op.getValueType(),
16559 Mask, PassThru, Subtarget, DAG);
16562 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16563 Mask, PassThru, Subtarget, DAG);
16565 case INTR_TYPE_SCALAR_MASK: {
16566 SDValue Src1 = Op.getOperand(1);
16567 SDValue Src2 = Op.getOperand(2);
16568 SDValue passThru = Op.getOperand(3);
16569 SDValue Mask = Op.getOperand(4);
16570 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16571 Mask, passThru, Subtarget, DAG);
16573 case INTR_TYPE_SCALAR_MASK_RM: {
16574 SDValue Src1 = Op.getOperand(1);
16575 SDValue Src2 = Op.getOperand(2);
16576 SDValue Src0 = Op.getOperand(3);
16577 SDValue Mask = Op.getOperand(4);
16578 // There are 2 kinds of intrinsics in this group:
16579 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16580 // (2) With rounding mode and sae - 7 operands.
16581 if (Op.getNumOperands() == 6) {
16582 SDValue Sae = Op.getOperand(5);
16583 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16584 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16586 Mask, Src0, Subtarget, DAG);
16588 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16589 SDValue RoundingMode = Op.getOperand(5);
16590 SDValue Sae = Op.getOperand(6);
16591 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16592 RoundingMode, Sae),
16593 Mask, Src0, Subtarget, DAG);
16595 case INTR_TYPE_2OP_MASK:
16596 case INTR_TYPE_2OP_IMM8_MASK: {
16597 SDValue Src1 = Op.getOperand(1);
16598 SDValue Src2 = Op.getOperand(2);
16599 SDValue PassThru = Op.getOperand(3);
16600 SDValue Mask = Op.getOperand(4);
16602 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16603 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16605 // We specify 2 possible opcodes for intrinsics with rounding modes.
16606 // First, we check if the intrinsic may have non-default rounding mode,
16607 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16608 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16609 if (IntrWithRoundingModeOpcode != 0) {
16610 SDValue Rnd = Op.getOperand(5);
16611 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16612 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16613 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16614 dl, Op.getValueType(),
16616 Mask, PassThru, Subtarget, DAG);
16619 // TODO: Intrinsics should have fast-math-flags to propagate.
16620 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16621 Mask, PassThru, Subtarget, DAG);
16623 case INTR_TYPE_2OP_MASK_RM: {
16624 SDValue Src1 = Op.getOperand(1);
16625 SDValue Src2 = Op.getOperand(2);
16626 SDValue PassThru = Op.getOperand(3);
16627 SDValue Mask = Op.getOperand(4);
16628 // We specify 2 possible modes for intrinsics, with/without rounding
16630 // First, we check if the intrinsic have rounding mode (6 operands),
16631 // if not, we set rounding mode to "current".
16633 if (Op.getNumOperands() == 6)
16634 Rnd = Op.getOperand(5);
16636 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16637 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16639 Mask, PassThru, Subtarget, DAG);
16641 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16642 SDValue Src1 = Op.getOperand(1);
16643 SDValue Src2 = Op.getOperand(2);
16644 SDValue Src3 = Op.getOperand(3);
16645 SDValue PassThru = Op.getOperand(4);
16646 SDValue Mask = Op.getOperand(5);
16647 SDValue Sae = Op.getOperand(6);
16649 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16651 Mask, PassThru, Subtarget, DAG);
16653 case INTR_TYPE_3OP_MASK_RM: {
16654 SDValue Src1 = Op.getOperand(1);
16655 SDValue Src2 = Op.getOperand(2);
16656 SDValue Imm = Op.getOperand(3);
16657 SDValue PassThru = Op.getOperand(4);
16658 SDValue Mask = Op.getOperand(5);
16659 // We specify 2 possible modes for intrinsics, with/without rounding
16661 // First, we check if the intrinsic have rounding mode (7 operands),
16662 // if not, we set rounding mode to "current".
16664 if (Op.getNumOperands() == 7)
16665 Rnd = Op.getOperand(6);
16667 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16668 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16669 Src1, Src2, Imm, Rnd),
16670 Mask, PassThru, Subtarget, DAG);
16672 case INTR_TYPE_3OP_IMM8_MASK:
16673 case INTR_TYPE_3OP_MASK:
16674 case INSERT_SUBVEC: {
16675 SDValue Src1 = Op.getOperand(1);
16676 SDValue Src2 = Op.getOperand(2);
16677 SDValue Src3 = Op.getOperand(3);
16678 SDValue PassThru = Op.getOperand(4);
16679 SDValue Mask = Op.getOperand(5);
16681 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16682 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16683 else if (IntrData->Type == INSERT_SUBVEC) {
16684 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16685 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16686 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16687 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16688 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16691 // We specify 2 possible opcodes for intrinsics with rounding modes.
16692 // First, we check if the intrinsic may have non-default rounding mode,
16693 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16694 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16695 if (IntrWithRoundingModeOpcode != 0) {
16696 SDValue Rnd = Op.getOperand(6);
16697 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16698 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16699 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16700 dl, Op.getValueType(),
16701 Src1, Src2, Src3, Rnd),
16702 Mask, PassThru, Subtarget, DAG);
16705 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16707 Mask, PassThru, Subtarget, DAG);
16709 case VPERM_3OP_MASKZ:
16710 case VPERM_3OP_MASK:{
16711 // Src2 is the PassThru
16712 SDValue Src1 = Op.getOperand(1);
16713 SDValue Src2 = Op.getOperand(2);
16714 SDValue Src3 = Op.getOperand(3);
16715 SDValue Mask = Op.getOperand(4);
16716 MVT VT = Op.getSimpleValueType();
16717 SDValue PassThru = SDValue();
16719 // set PassThru element
16720 if (IntrData->Type == VPERM_3OP_MASKZ)
16721 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16723 PassThru = DAG.getBitcast(VT, Src2);
16725 // Swap Src1 and Src2 in the node creation
16726 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16727 dl, Op.getValueType(),
16729 Mask, PassThru, Subtarget, DAG);
16733 case FMA_OP_MASK: {
16734 SDValue Src1 = Op.getOperand(1);
16735 SDValue Src2 = Op.getOperand(2);
16736 SDValue Src3 = Op.getOperand(3);
16737 SDValue Mask = Op.getOperand(4);
16738 MVT VT = Op.getSimpleValueType();
16739 SDValue PassThru = SDValue();
16741 // set PassThru element
16742 if (IntrData->Type == FMA_OP_MASKZ)
16743 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16744 else if (IntrData->Type == FMA_OP_MASK3)
16749 // We specify 2 possible opcodes for intrinsics with rounding modes.
16750 // First, we check if the intrinsic may have non-default rounding mode,
16751 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16752 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16753 if (IntrWithRoundingModeOpcode != 0) {
16754 SDValue Rnd = Op.getOperand(5);
16755 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16756 X86::STATIC_ROUNDING::CUR_DIRECTION)
16757 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16758 dl, Op.getValueType(),
16759 Src1, Src2, Src3, Rnd),
16760 Mask, PassThru, Subtarget, DAG);
16762 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16763 dl, Op.getValueType(),
16765 Mask, PassThru, Subtarget, DAG);
16767 case TERLOG_OP_MASK:
16768 case TERLOG_OP_MASKZ: {
16769 SDValue Src1 = Op.getOperand(1);
16770 SDValue Src2 = Op.getOperand(2);
16771 SDValue Src3 = Op.getOperand(3);
16772 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16773 SDValue Mask = Op.getOperand(5);
16774 MVT VT = Op.getSimpleValueType();
16775 SDValue PassThru = Src1;
16776 // Set PassThru element.
16777 if (IntrData->Type == TERLOG_OP_MASKZ)
16778 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16780 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16781 Src1, Src2, Src3, Src4),
16782 Mask, PassThru, Subtarget, DAG);
16785 // FPclass intrinsics with mask
16786 SDValue Src1 = Op.getOperand(1);
16787 MVT VT = Src1.getSimpleValueType();
16788 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16789 SDValue Imm = Op.getOperand(2);
16790 SDValue Mask = Op.getOperand(3);
16791 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16792 Mask.getSimpleValueType().getSizeInBits());
16793 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16794 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16795 DAG.getTargetConstant(0, dl, MaskVT),
16797 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16798 DAG.getUNDEF(BitcastVT), FPclassMask,
16799 DAG.getIntPtrConstant(0, dl));
16800 return DAG.getBitcast(Op.getValueType(), Res);
16803 SDValue Src1 = Op.getOperand(1);
16804 SDValue Imm = Op.getOperand(2);
16805 SDValue Mask = Op.getOperand(3);
16806 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16807 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16808 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16809 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16812 case CMP_MASK_CC: {
16813 // Comparison intrinsics with masks.
16814 // Example of transformation:
16815 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16816 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16818 // (v8i1 (insert_subvector undef,
16819 // (v2i1 (and (PCMPEQM %a, %b),
16820 // (extract_subvector
16821 // (v8i1 (bitcast %mask)), 0))), 0))))
16822 MVT VT = Op.getOperand(1).getSimpleValueType();
16823 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16824 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16825 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16826 Mask.getSimpleValueType().getSizeInBits());
16828 if (IntrData->Type == CMP_MASK_CC) {
16829 SDValue CC = Op.getOperand(3);
16830 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16831 // We specify 2 possible opcodes for intrinsics with rounding modes.
16832 // First, we check if the intrinsic may have non-default rounding mode,
16833 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16834 if (IntrData->Opc1 != 0) {
16835 SDValue Rnd = Op.getOperand(5);
16836 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16837 X86::STATIC_ROUNDING::CUR_DIRECTION)
16838 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16839 Op.getOperand(2), CC, Rnd);
16841 //default rounding mode
16843 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16844 Op.getOperand(2), CC);
16847 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16848 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16851 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16852 DAG.getTargetConstant(0, dl,
16855 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16856 DAG.getUNDEF(BitcastVT), CmpMask,
16857 DAG.getIntPtrConstant(0, dl));
16858 return DAG.getBitcast(Op.getValueType(), Res);
16860 case CMP_MASK_SCALAR_CC: {
16861 SDValue Src1 = Op.getOperand(1);
16862 SDValue Src2 = Op.getOperand(2);
16863 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16864 SDValue Mask = Op.getOperand(4);
16867 if (IntrData->Opc1 != 0) {
16868 SDValue Rnd = Op.getOperand(5);
16869 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16870 X86::STATIC_ROUNDING::CUR_DIRECTION)
16871 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16873 //default rounding mode
16875 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16877 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16878 DAG.getTargetConstant(0, dl,
16882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16883 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16884 DAG.getValueType(MVT::i1));
16886 case COMI: { // Comparison intrinsics
16887 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16888 SDValue LHS = Op.getOperand(1);
16889 SDValue RHS = Op.getOperand(2);
16890 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16891 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16892 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16893 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16894 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16895 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16897 case COMI_RM: { // Comparison intrinsics with Sae
16898 SDValue LHS = Op.getOperand(1);
16899 SDValue RHS = Op.getOperand(2);
16900 SDValue CC = Op.getOperand(3);
16901 SDValue Sae = Op.getOperand(4);
16902 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16903 // choose between ordered and unordered (comi/ucomi)
16904 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16906 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16907 X86::STATIC_ROUNDING::CUR_DIRECTION)
16908 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16910 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16911 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16912 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16913 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16916 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16917 Op.getOperand(1), Op.getOperand(2), DAG);
16919 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16920 Op.getSimpleValueType(),
16922 Op.getOperand(2), DAG),
16923 Op.getOperand(4), Op.getOperand(3), Subtarget,
16925 case COMPRESS_EXPAND_IN_REG: {
16926 SDValue Mask = Op.getOperand(3);
16927 SDValue DataToCompress = Op.getOperand(1);
16928 SDValue PassThru = Op.getOperand(2);
16929 if (isAllOnesConstant(Mask)) // return data as is
16930 return Op.getOperand(1);
16932 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16934 Mask, PassThru, Subtarget, DAG);
16937 SDValue Mask = Op.getOperand(1);
16938 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16939 Mask.getSimpleValueType().getSizeInBits());
16940 Mask = DAG.getBitcast(MaskVT, Mask);
16941 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16944 SDValue Mask = Op.getOperand(3);
16945 MVT VT = Op.getSimpleValueType();
16946 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16947 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16948 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16952 MVT VT = Op.getSimpleValueType();
16953 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16955 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16956 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16957 // Arguments should be swapped.
16958 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16959 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16961 return DAG.getBitcast(VT, Res);
16963 case CONVERT_TO_MASK: {
16964 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16965 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16966 MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16968 SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16970 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16971 DAG.getUNDEF(BitcastVT), CvtMask,
16972 DAG.getIntPtrConstant(0, dl));
16973 return DAG.getBitcast(Op.getValueType(), Res);
16975 case CONVERT_MASK_TO_VEC: {
16976 SDValue Mask = Op.getOperand(1);
16977 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16978 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16979 return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16981 case BRCST_SUBVEC_TO_VEC: {
16982 SDValue Src = Op.getOperand(1);
16983 SDValue Passthru = Op.getOperand(2);
16984 SDValue Mask = Op.getOperand(3);
16985 EVT resVT = Passthru.getValueType();
16986 SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16987 DAG.getUNDEF(resVT), Src,
16988 DAG.getIntPtrConstant(0, dl));
16990 if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16991 immVal = DAG.getConstant(0x44, dl, MVT::i8);
16993 immVal = DAG.getConstant(0, dl, MVT::i8);
16994 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16995 subVec, subVec, immVal),
16996 Mask, Passthru, Subtarget, DAG);
17004 default: return SDValue(); // Don't custom lower most intrinsics.
17006 case Intrinsic::x86_avx2_permd:
17007 case Intrinsic::x86_avx2_permps:
17008 // Operands intentionally swapped. Mask is last operand to intrinsic,
17009 // but second operand for node/instruction.
17010 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17011 Op.getOperand(2), Op.getOperand(1));
17013 // ptest and testp intrinsics. The intrinsic these come from are designed to
17014 // return an integer value, not just an instruction so lower it to the ptest
17015 // or testp pattern and a setcc for the result.
17016 case Intrinsic::x86_sse41_ptestz:
17017 case Intrinsic::x86_sse41_ptestc:
17018 case Intrinsic::x86_sse41_ptestnzc:
17019 case Intrinsic::x86_avx_ptestz_256:
17020 case Intrinsic::x86_avx_ptestc_256:
17021 case Intrinsic::x86_avx_ptestnzc_256:
17022 case Intrinsic::x86_avx_vtestz_ps:
17023 case Intrinsic::x86_avx_vtestc_ps:
17024 case Intrinsic::x86_avx_vtestnzc_ps:
17025 case Intrinsic::x86_avx_vtestz_pd:
17026 case Intrinsic::x86_avx_vtestc_pd:
17027 case Intrinsic::x86_avx_vtestnzc_pd:
17028 case Intrinsic::x86_avx_vtestz_ps_256:
17029 case Intrinsic::x86_avx_vtestc_ps_256:
17030 case Intrinsic::x86_avx_vtestnzc_ps_256:
17031 case Intrinsic::x86_avx_vtestz_pd_256:
17032 case Intrinsic::x86_avx_vtestc_pd_256:
17033 case Intrinsic::x86_avx_vtestnzc_pd_256: {
17034 bool IsTestPacked = false;
17037 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17038 case Intrinsic::x86_avx_vtestz_ps:
17039 case Intrinsic::x86_avx_vtestz_pd:
17040 case Intrinsic::x86_avx_vtestz_ps_256:
17041 case Intrinsic::x86_avx_vtestz_pd_256:
17042 IsTestPacked = true; // Fallthrough
17043 case Intrinsic::x86_sse41_ptestz:
17044 case Intrinsic::x86_avx_ptestz_256:
17046 X86CC = X86::COND_E;
17048 case Intrinsic::x86_avx_vtestc_ps:
17049 case Intrinsic::x86_avx_vtestc_pd:
17050 case Intrinsic::x86_avx_vtestc_ps_256:
17051 case Intrinsic::x86_avx_vtestc_pd_256:
17052 IsTestPacked = true; // Fallthrough
17053 case Intrinsic::x86_sse41_ptestc:
17054 case Intrinsic::x86_avx_ptestc_256:
17056 X86CC = X86::COND_B;
17058 case Intrinsic::x86_avx_vtestnzc_ps:
17059 case Intrinsic::x86_avx_vtestnzc_pd:
17060 case Intrinsic::x86_avx_vtestnzc_ps_256:
17061 case Intrinsic::x86_avx_vtestnzc_pd_256:
17062 IsTestPacked = true; // Fallthrough
17063 case Intrinsic::x86_sse41_ptestnzc:
17064 case Intrinsic::x86_avx_ptestnzc_256:
17066 X86CC = X86::COND_A;
17070 SDValue LHS = Op.getOperand(1);
17071 SDValue RHS = Op.getOperand(2);
17072 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17073 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17074 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17075 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17076 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17078 case Intrinsic::x86_avx512_kortestz_w:
17079 case Intrinsic::x86_avx512_kortestc_w: {
17080 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17081 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17082 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17083 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17084 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17085 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17086 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17089 case Intrinsic::x86_sse42_pcmpistria128:
17090 case Intrinsic::x86_sse42_pcmpestria128:
17091 case Intrinsic::x86_sse42_pcmpistric128:
17092 case Intrinsic::x86_sse42_pcmpestric128:
17093 case Intrinsic::x86_sse42_pcmpistrio128:
17094 case Intrinsic::x86_sse42_pcmpestrio128:
17095 case Intrinsic::x86_sse42_pcmpistris128:
17096 case Intrinsic::x86_sse42_pcmpestris128:
17097 case Intrinsic::x86_sse42_pcmpistriz128:
17098 case Intrinsic::x86_sse42_pcmpestriz128: {
17102 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17103 case Intrinsic::x86_sse42_pcmpistria128:
17104 Opcode = X86ISD::PCMPISTRI;
17105 X86CC = X86::COND_A;
17107 case Intrinsic::x86_sse42_pcmpestria128:
17108 Opcode = X86ISD::PCMPESTRI;
17109 X86CC = X86::COND_A;
17111 case Intrinsic::x86_sse42_pcmpistric128:
17112 Opcode = X86ISD::PCMPISTRI;
17113 X86CC = X86::COND_B;
17115 case Intrinsic::x86_sse42_pcmpestric128:
17116 Opcode = X86ISD::PCMPESTRI;
17117 X86CC = X86::COND_B;
17119 case Intrinsic::x86_sse42_pcmpistrio128:
17120 Opcode = X86ISD::PCMPISTRI;
17121 X86CC = X86::COND_O;
17123 case Intrinsic::x86_sse42_pcmpestrio128:
17124 Opcode = X86ISD::PCMPESTRI;
17125 X86CC = X86::COND_O;
17127 case Intrinsic::x86_sse42_pcmpistris128:
17128 Opcode = X86ISD::PCMPISTRI;
17129 X86CC = X86::COND_S;
17131 case Intrinsic::x86_sse42_pcmpestris128:
17132 Opcode = X86ISD::PCMPESTRI;
17133 X86CC = X86::COND_S;
17135 case Intrinsic::x86_sse42_pcmpistriz128:
17136 Opcode = X86ISD::PCMPISTRI;
17137 X86CC = X86::COND_E;
17139 case Intrinsic::x86_sse42_pcmpestriz128:
17140 Opcode = X86ISD::PCMPESTRI;
17141 X86CC = X86::COND_E;
17144 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17145 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17146 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17147 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17148 DAG.getConstant(X86CC, dl, MVT::i8),
17149 SDValue(PCMP.getNode(), 1));
17150 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17153 case Intrinsic::x86_sse42_pcmpistri128:
17154 case Intrinsic::x86_sse42_pcmpestri128: {
17156 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17157 Opcode = X86ISD::PCMPISTRI;
17159 Opcode = X86ISD::PCMPESTRI;
17161 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17162 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17163 return DAG.getNode(Opcode, dl, VTs, NewOps);
17166 case Intrinsic::x86_seh_lsda: {
17167 // Compute the symbol for the LSDA. We know it'll get emitted later.
17168 MachineFunction &MF = DAG.getMachineFunction();
17169 SDValue Op1 = Op.getOperand(1);
17170 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17171 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17172 GlobalValue::getRealLinkageName(Fn->getName()));
17174 // Generate a simple absolute symbol reference. This intrinsic is only
17175 // supported on 32-bit Windows, which isn't PIC.
17176 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17177 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17180 case Intrinsic::x86_seh_recoverfp: {
17181 SDValue FnOp = Op.getOperand(1);
17182 SDValue IncomingFPOp = Op.getOperand(2);
17183 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17184 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17186 report_fatal_error(
17187 "llvm.x86.seh.recoverfp must take a function as the first argument");
17188 return recoverFramePointer(DAG, Fn, IncomingFPOp);
17191 case Intrinsic::localaddress: {
17192 // Returns one of the stack, base, or frame pointer registers, depending on
17193 // which is used to reference local variables.
17194 MachineFunction &MF = DAG.getMachineFunction();
17195 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17197 if (RegInfo->hasBasePointer(MF))
17198 Reg = RegInfo->getBaseRegister();
17199 else // This function handles the SP or FP case.
17200 Reg = RegInfo->getPtrSizedFrameRegister(MF);
17201 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17206 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17207 SDValue Src, SDValue Mask, SDValue Base,
17208 SDValue Index, SDValue ScaleOp, SDValue Chain,
17209 const X86Subtarget * Subtarget) {
17211 auto *C = cast<ConstantSDNode>(ScaleOp);
17212 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17213 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17214 Index.getSimpleValueType().getVectorNumElements());
17216 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17217 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17218 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17219 SDValue Segment = DAG.getRegister(0, MVT::i32);
17220 if (Src.getOpcode() == ISD::UNDEF)
17221 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17222 SDValue Ops[] = {Src, VMask, Base, Scale, Index, Disp, Segment, Chain};
17223 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17224 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17225 return DAG.getMergeValues(RetOps, dl);
17228 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17229 SDValue Src, SDValue Mask, SDValue Base,
17230 SDValue Index, SDValue ScaleOp, SDValue Chain,
17231 const X86Subtarget &Subtarget) {
17233 auto *C = cast<ConstantSDNode>(ScaleOp);
17234 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17235 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17236 SDValue Segment = DAG.getRegister(0, MVT::i32);
17237 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17238 Index.getSimpleValueType().getVectorNumElements());
17240 SDValue VMask = getMaskNode(Mask, MaskVT, &Subtarget, DAG, dl);
17241 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17242 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, VMask, Src, Chain};
17243 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17244 return SDValue(Res, 1);
17247 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17248 SDValue Mask, SDValue Base, SDValue Index,
17249 SDValue ScaleOp, SDValue Chain,
17250 const X86Subtarget &Subtarget) {
17252 auto *C = cast<ConstantSDNode>(ScaleOp);
17253 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17254 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17255 SDValue Segment = DAG.getRegister(0, MVT::i32);
17257 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17258 SDValue VMask = getMaskNode(Mask, MaskVT, &Subtarget, DAG, dl);
17259 //SDVTList VTs = DAG.getVTList(MVT::Other);
17260 SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
17261 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17262 return SDValue(Res, 0);
17265 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17266 // read performance monitor counters (x86_rdpmc).
17267 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17268 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17269 SmallVectorImpl<SDValue> &Results) {
17270 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17271 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17274 // The ECX register is used to select the index of the performance counter
17276 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17278 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17280 // Reads the content of a 64-bit performance counter and returns it in the
17281 // registers EDX:EAX.
17282 if (Subtarget->is64Bit()) {
17283 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17284 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17287 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17288 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17291 Chain = HI.getValue(1);
17293 if (Subtarget->is64Bit()) {
17294 // The EAX register is loaded with the low-order 32 bits. The EDX register
17295 // is loaded with the supported high-order bits of the counter.
17296 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17297 DAG.getConstant(32, DL, MVT::i8));
17298 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17299 Results.push_back(Chain);
17303 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17304 SDValue Ops[] = { LO, HI };
17305 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17306 Results.push_back(Pair);
17307 Results.push_back(Chain);
17310 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17311 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17312 // also used to custom lower READCYCLECOUNTER nodes.
17313 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17314 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17315 SmallVectorImpl<SDValue> &Results) {
17316 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17317 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17320 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17321 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17322 // and the EAX register is loaded with the low-order 32 bits.
17323 if (Subtarget->is64Bit()) {
17324 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17325 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17328 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17329 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17332 SDValue Chain = HI.getValue(1);
17334 if (Opcode == X86ISD::RDTSCP_DAG) {
17335 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17337 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17338 // the ECX register. Add 'ecx' explicitly to the chain.
17339 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17341 // Explicitly store the content of ECX at the location passed in input
17342 // to the 'rdtscp' intrinsic.
17343 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17344 MachinePointerInfo(), false, false, 0);
17347 if (Subtarget->is64Bit()) {
17348 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17349 // the EAX register is loaded with the low-order 32 bits.
17350 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17351 DAG.getConstant(32, DL, MVT::i8));
17352 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17353 Results.push_back(Chain);
17357 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17358 SDValue Ops[] = { LO, HI };
17359 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17360 Results.push_back(Pair);
17361 Results.push_back(Chain);
17364 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17365 SelectionDAG &DAG) {
17366 SmallVector<SDValue, 2> Results;
17368 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17370 return DAG.getMergeValues(Results, DL);
17373 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17374 MachineFunction &MF = DAG.getMachineFunction();
17375 SDValue Chain = Op.getOperand(0);
17376 SDValue RegNode = Op.getOperand(2);
17377 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17379 report_fatal_error("EH registrations only live in functions using WinEH");
17381 // Cast the operand to an alloca, and remember the frame index.
17382 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17384 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17385 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17387 // Return the chain operand without making any DAG nodes.
17391 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17392 /// return truncate Store/MaskedStore Node
17393 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17397 SDValue Mask = Op.getOperand(4);
17398 SDValue DataToTruncate = Op.getOperand(3);
17399 SDValue Addr = Op.getOperand(2);
17400 SDValue Chain = Op.getOperand(0);
17402 MVT VT = DataToTruncate.getSimpleValueType();
17403 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17405 if (isAllOnesConstant(Mask)) // return just a truncate store
17406 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17407 MachinePointerInfo(), SVT, false, false,
17408 SVT.getScalarSizeInBits()/8);
17410 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17411 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17412 Mask.getSimpleValueType().getSizeInBits());
17413 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17414 // are extracted by EXTRACT_SUBVECTOR.
17415 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17416 DAG.getBitcast(BitcastVT, Mask),
17417 DAG.getIntPtrConstant(0, dl));
17419 MachineMemOperand *MMO = DAG.getMachineFunction().
17420 getMachineMemOperand(MachinePointerInfo(),
17421 MachineMemOperand::MOStore, SVT.getStoreSize(),
17422 SVT.getScalarSizeInBits()/8);
17424 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17425 VMask, SVT, MMO, true);
17428 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17429 SelectionDAG &DAG) {
17430 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17432 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17434 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17435 return MarkEHRegistrationNode(Op, DAG);
17436 if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17437 IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17438 IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17439 IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17440 // We need a frame pointer because this will get lowered to a PUSH/POP
17442 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17443 MFI->setHasCopyImplyingStackAdjustment(true);
17444 // Don't do anything here, we will expand these intrinsics out later
17445 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17452 switch(IntrData->Type) {
17453 default: llvm_unreachable("Unknown Intrinsic Type");
17456 // Emit the node with the right value type.
17457 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17458 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17460 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17461 // Otherwise return the value from Rand, which is always 0, casted to i32.
17462 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17463 DAG.getConstant(1, dl, Op->getValueType(1)),
17464 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17465 SDValue(Result.getNode(), 1) };
17466 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17467 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17470 // Return { result, isValid, chain }.
17471 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17472 SDValue(Result.getNode(), 2));
17475 //gather(v1, mask, index, base, scale);
17476 SDValue Chain = Op.getOperand(0);
17477 SDValue Src = Op.getOperand(2);
17478 SDValue Base = Op.getOperand(3);
17479 SDValue Index = Op.getOperand(4);
17480 SDValue Mask = Op.getOperand(5);
17481 SDValue Scale = Op.getOperand(6);
17482 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17486 //scatter(base, mask, index, v1, scale);
17487 SDValue Chain = Op.getOperand(0);
17488 SDValue Base = Op.getOperand(2);
17489 SDValue Mask = Op.getOperand(3);
17490 SDValue Index = Op.getOperand(4);
17491 SDValue Src = Op.getOperand(5);
17492 SDValue Scale = Op.getOperand(6);
17493 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17494 Scale, Chain, *Subtarget);
17497 SDValue Hint = Op.getOperand(6);
17498 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17499 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17500 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17501 SDValue Chain = Op.getOperand(0);
17502 SDValue Mask = Op.getOperand(2);
17503 SDValue Index = Op.getOperand(3);
17504 SDValue Base = Op.getOperand(4);
17505 SDValue Scale = Op.getOperand(5);
17506 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
17509 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17511 SmallVector<SDValue, 2> Results;
17512 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17514 return DAG.getMergeValues(Results, dl);
17516 // Read Performance Monitoring Counters.
17518 SmallVector<SDValue, 2> Results;
17519 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17520 return DAG.getMergeValues(Results, dl);
17522 // XTEST intrinsics.
17524 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17525 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17526 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17527 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17529 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17530 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17531 Ret, SDValue(InTrans.getNode(), 1));
17535 SmallVector<SDValue, 2> Results;
17536 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17537 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17538 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17539 DAG.getConstant(-1, dl, MVT::i8));
17540 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17541 Op.getOperand(4), GenCF.getValue(1));
17542 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17543 Op.getOperand(5), MachinePointerInfo(),
17545 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17546 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17548 Results.push_back(SetCC);
17549 Results.push_back(Store);
17550 return DAG.getMergeValues(Results, dl);
17552 case COMPRESS_TO_MEM: {
17553 SDValue Mask = Op.getOperand(4);
17554 SDValue DataToCompress = Op.getOperand(3);
17555 SDValue Addr = Op.getOperand(2);
17556 SDValue Chain = Op.getOperand(0);
17558 MVT VT = DataToCompress.getSimpleValueType();
17559 if (isAllOnesConstant(Mask)) // return just a store
17560 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17561 MachinePointerInfo(), false, false,
17562 VT.getScalarSizeInBits()/8);
17564 SDValue Compressed =
17565 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17566 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17567 return DAG.getStore(Chain, dl, Compressed, Addr,
17568 MachinePointerInfo(), false, false,
17569 VT.getScalarSizeInBits()/8);
17571 case TRUNCATE_TO_MEM_VI8:
17572 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17573 case TRUNCATE_TO_MEM_VI16:
17574 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17575 case TRUNCATE_TO_MEM_VI32:
17576 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17577 case EXPAND_FROM_MEM: {
17578 SDValue Mask = Op.getOperand(4);
17579 SDValue PassThru = Op.getOperand(3);
17580 SDValue Addr = Op.getOperand(2);
17581 SDValue Chain = Op.getOperand(0);
17582 MVT VT = Op.getSimpleValueType();
17584 if (isAllOnesConstant(Mask)) // return just a load
17585 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17586 false, VT.getScalarSizeInBits()/8);
17588 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17589 false, false, false,
17590 VT.getScalarSizeInBits()/8);
17592 SDValue Results[] = {
17593 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17594 Mask, PassThru, Subtarget, DAG), Chain};
17595 return DAG.getMergeValues(Results, dl);
17599 SDValue Mask = Op.getOperand(4);
17600 SDValue PassThru = Op.getOperand(3);
17601 SDValue Addr = Op.getOperand(2);
17602 SDValue Chain = Op.getOperand(0);
17603 MVT VT = Op.getSimpleValueType();
17605 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
17606 assert(MemIntr && "Expected MemIntrinsicSDNode!");
17608 if (isAllOnesConstant(Mask)) // return just a load
17609 return DAG.getLoad(VT, dl, Chain, Addr, MemIntr->getMemOperand());
17611 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17612 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17613 return DAG.getMaskedLoad(VT, dl, Chain, Addr, VMask, PassThru, VT,
17614 MemIntr->getMemOperand(), ISD::NON_EXTLOAD);
17619 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17620 SelectionDAG &DAG) const {
17621 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17622 MFI->setReturnAddressIsTaken(true);
17624 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17627 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17629 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17632 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17633 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17634 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17635 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17636 DAG.getNode(ISD::ADD, dl, PtrVT,
17637 FrameAddr, Offset),
17638 MachinePointerInfo(), false, false, false, 0);
17641 // Just load the return address.
17642 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17643 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17644 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17647 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17648 MachineFunction &MF = DAG.getMachineFunction();
17649 MachineFrameInfo *MFI = MF.getFrameInfo();
17650 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17651 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17652 EVT VT = Op.getValueType();
17654 MFI->setFrameAddressIsTaken(true);
17656 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17657 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17658 // is not possible to crawl up the stack without looking at the unwind codes
17660 int FrameAddrIndex = FuncInfo->getFAIndex();
17661 if (!FrameAddrIndex) {
17662 // Set up a frame object for the return address.
17663 unsigned SlotSize = RegInfo->getSlotSize();
17664 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17665 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17666 FuncInfo->setFAIndex(FrameAddrIndex);
17668 return DAG.getFrameIndex(FrameAddrIndex, VT);
17671 unsigned FrameReg =
17672 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17673 SDLoc dl(Op); // FIXME probably not meaningful
17674 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17675 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17676 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17677 "Invalid Frame Register!");
17678 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17680 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17681 MachinePointerInfo(),
17682 false, false, false, 0);
17686 // FIXME? Maybe this could be a TableGen attribute on some registers and
17687 // this table could be generated automatically from RegInfo.
17688 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17689 SelectionDAG &DAG) const {
17690 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17691 const MachineFunction &MF = DAG.getMachineFunction();
17693 unsigned Reg = StringSwitch<unsigned>(RegName)
17694 .Case("esp", X86::ESP)
17695 .Case("rsp", X86::RSP)
17696 .Case("ebp", X86::EBP)
17697 .Case("rbp", X86::RBP)
17700 if (Reg == X86::EBP || Reg == X86::RBP) {
17701 if (!TFI.hasFP(MF))
17702 report_fatal_error("register " + StringRef(RegName) +
17703 " is allocatable: function has no frame pointer");
17706 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17707 unsigned FrameReg =
17708 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17709 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17710 "Invalid Frame Register!");
17718 report_fatal_error("Invalid register name global variable");
17721 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17722 SelectionDAG &DAG) const {
17723 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17724 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17727 unsigned X86TargetLowering::getExceptionPointerRegister(
17728 const Constant *PersonalityFn) const {
17729 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17730 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17732 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17735 unsigned X86TargetLowering::getExceptionSelectorRegister(
17736 const Constant *PersonalityFn) const {
17737 // Funclet personalities don't use selectors (the runtime does the selection).
17738 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17739 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17742 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17743 SDValue Chain = Op.getOperand(0);
17744 SDValue Offset = Op.getOperand(1);
17745 SDValue Handler = Op.getOperand(2);
17748 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17749 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17750 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17751 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17752 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17753 "Invalid Frame Register!");
17754 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17755 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17757 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17758 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17760 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17761 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17763 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17765 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17766 DAG.getRegister(StoreAddrReg, PtrVT));
17769 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17770 SelectionDAG &DAG) const {
17772 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17773 DAG.getVTList(MVT::i32, MVT::Other),
17774 Op.getOperand(0), Op.getOperand(1));
17777 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17778 SelectionDAG &DAG) const {
17780 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17781 Op.getOperand(0), Op.getOperand(1));
17784 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17785 return Op.getOperand(0);
17788 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17789 SelectionDAG &DAG) const {
17790 SDValue Root = Op.getOperand(0);
17791 SDValue Trmp = Op.getOperand(1); // trampoline
17792 SDValue FPtr = Op.getOperand(2); // nested function
17793 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17796 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17797 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17799 if (Subtarget->is64Bit()) {
17800 SDValue OutChains[6];
17802 // Large code-model.
17803 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17804 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17806 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17807 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17809 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17811 // Load the pointer to the nested function into R11.
17812 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17813 SDValue Addr = Trmp;
17814 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17815 Addr, MachinePointerInfo(TrmpAddr),
17818 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17819 DAG.getConstant(2, dl, MVT::i64));
17820 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17821 MachinePointerInfo(TrmpAddr, 2),
17824 // Load the 'nest' parameter value into R10.
17825 // R10 is specified in X86CallingConv.td
17826 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17827 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17828 DAG.getConstant(10, dl, MVT::i64));
17829 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17830 Addr, MachinePointerInfo(TrmpAddr, 10),
17833 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17834 DAG.getConstant(12, dl, MVT::i64));
17835 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17836 MachinePointerInfo(TrmpAddr, 12),
17839 // Jump to the nested function.
17840 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17841 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17842 DAG.getConstant(20, dl, MVT::i64));
17843 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17844 Addr, MachinePointerInfo(TrmpAddr, 20),
17847 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17848 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17849 DAG.getConstant(22, dl, MVT::i64));
17850 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17851 Addr, MachinePointerInfo(TrmpAddr, 22),
17854 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17856 const Function *Func =
17857 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17858 CallingConv::ID CC = Func->getCallingConv();
17863 llvm_unreachable("Unsupported calling convention");
17864 case CallingConv::C:
17865 case CallingConv::X86_StdCall: {
17866 // Pass 'nest' parameter in ECX.
17867 // Must be kept in sync with X86CallingConv.td
17868 NestReg = X86::ECX;
17870 // Check that ECX wasn't needed by an 'inreg' parameter.
17871 FunctionType *FTy = Func->getFunctionType();
17872 const AttributeSet &Attrs = Func->getAttributes();
17874 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17875 unsigned InRegCount = 0;
17878 for (FunctionType::param_iterator I = FTy->param_begin(),
17879 E = FTy->param_end(); I != E; ++I, ++Idx)
17880 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17881 auto &DL = DAG.getDataLayout();
17882 // FIXME: should only count parameters that are lowered to integers.
17883 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17886 if (InRegCount > 2) {
17887 report_fatal_error("Nest register in use - reduce number of inreg"
17893 case CallingConv::X86_FastCall:
17894 case CallingConv::X86_ThisCall:
17895 case CallingConv::Fast:
17896 // Pass 'nest' parameter in EAX.
17897 // Must be kept in sync with X86CallingConv.td
17898 NestReg = X86::EAX;
17902 SDValue OutChains[4];
17903 SDValue Addr, Disp;
17905 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17906 DAG.getConstant(10, dl, MVT::i32));
17907 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17909 // This is storing the opcode for MOV32ri.
17910 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17911 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17912 OutChains[0] = DAG.getStore(Root, dl,
17913 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17914 Trmp, MachinePointerInfo(TrmpAddr),
17917 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17918 DAG.getConstant(1, dl, MVT::i32));
17919 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17920 MachinePointerInfo(TrmpAddr, 1),
17923 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17925 DAG.getConstant(5, dl, MVT::i32));
17926 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17927 Addr, MachinePointerInfo(TrmpAddr, 5),
17930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17931 DAG.getConstant(6, dl, MVT::i32));
17932 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17933 MachinePointerInfo(TrmpAddr, 6),
17936 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17940 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17941 SelectionDAG &DAG) const {
17943 The rounding mode is in bits 11:10 of FPSR, and has the following
17945 00 Round to nearest
17950 FLT_ROUNDS, on the other hand, expects the following:
17957 To perform the conversion, we do:
17958 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17961 MachineFunction &MF = DAG.getMachineFunction();
17962 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17963 unsigned StackAlignment = TFI.getStackAlignment();
17964 MVT VT = Op.getSimpleValueType();
17967 // Save FP Control Word to stack slot
17968 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17969 SDValue StackSlot =
17970 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17972 MachineMemOperand *MMO =
17973 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17974 MachineMemOperand::MOStore, 2, 2);
17976 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17977 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17978 DAG.getVTList(MVT::Other),
17979 Ops, MVT::i16, MMO);
17981 // Load FP Control Word from stack slot
17982 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17983 MachinePointerInfo(), false, false, false, 0);
17985 // Transform as necessary
17987 DAG.getNode(ISD::SRL, DL, MVT::i16,
17988 DAG.getNode(ISD::AND, DL, MVT::i16,
17989 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17990 DAG.getConstant(11, DL, MVT::i8));
17992 DAG.getNode(ISD::SRL, DL, MVT::i16,
17993 DAG.getNode(ISD::AND, DL, MVT::i16,
17994 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17995 DAG.getConstant(9, DL, MVT::i8));
17998 DAG.getNode(ISD::AND, DL, MVT::i16,
17999 DAG.getNode(ISD::ADD, DL, MVT::i16,
18000 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18001 DAG.getConstant(1, DL, MVT::i16)),
18002 DAG.getConstant(3, DL, MVT::i16));
18004 return DAG.getNode((VT.getSizeInBits() < 16 ?
18005 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18008 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
18010 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
18011 // to 512-bit vector.
18012 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
18013 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
18014 // split the vector, perform operation on it's Lo a Hi part and
18015 // concatenate the results.
18016 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
18018 MVT VT = Op.getSimpleValueType();
18019 MVT EltVT = VT.getVectorElementType();
18020 unsigned NumElems = VT.getVectorNumElements();
18022 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
18023 // Extend to 512 bit vector.
18024 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18025 "Unsupported value type for operation");
18027 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
18028 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18029 DAG.getUNDEF(NewVT),
18031 DAG.getIntPtrConstant(0, dl));
18032 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18034 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18035 DAG.getIntPtrConstant(0, dl));
18038 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18039 "Unsupported element type");
18041 if (16 < NumElems) {
18042 // Split vector, it's Lo and Hi parts will be handled in next iteration.
18044 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18045 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18047 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18048 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18050 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18053 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18055 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18056 "Unsupported value type for operation");
18058 // Use native supported vector instruction vplzcntd.
18059 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18060 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18061 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18062 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18064 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18067 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18068 SelectionDAG &DAG) {
18069 MVT VT = Op.getSimpleValueType();
18071 unsigned NumBits = VT.getSizeInBits();
18074 if (VT.isVector() && Subtarget->hasAVX512())
18075 return LowerVectorCTLZ_AVX512(Op, DAG);
18077 Op = Op.getOperand(0);
18078 if (VT == MVT::i8) {
18079 // Zero extend to i32 since there is not an i8 bsr.
18081 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18084 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18085 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18086 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18088 // If src is zero (i.e. bsr sets ZF), returns NumBits.
18091 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18092 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18095 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18097 // Finally xor with NumBits-1.
18098 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18099 DAG.getConstant(NumBits - 1, dl, OpVT));
18102 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18106 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18107 SelectionDAG &DAG) {
18108 MVT VT = Op.getSimpleValueType();
18110 unsigned NumBits = VT.getSizeInBits();
18113 Op = Op.getOperand(0);
18114 if (VT == MVT::i8) {
18115 // Zero extend to i32 since there is not an i8 bsr.
18117 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18120 // Issue a bsr (scan bits in reverse).
18121 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18122 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18124 // And xor with NumBits-1.
18125 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18126 DAG.getConstant(NumBits - 1, dl, OpVT));
18129 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18133 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18134 MVT VT = Op.getSimpleValueType();
18135 unsigned NumBits = VT.getScalarSizeInBits();
18138 if (VT.isVector()) {
18139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18141 SDValue N0 = Op.getOperand(0);
18142 SDValue Zero = DAG.getConstant(0, dl, VT);
18144 // lsb(x) = (x & -x)
18145 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18146 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18148 // cttz_undef(x) = (width - 1) - ctlz(lsb)
18149 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18150 TLI.isOperationLegal(ISD::CTLZ, VT)) {
18151 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18152 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18153 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18156 // cttz(x) = ctpop(lsb - 1)
18157 SDValue One = DAG.getConstant(1, dl, VT);
18158 return DAG.getNode(ISD::CTPOP, dl, VT,
18159 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18162 assert(Op.getOpcode() == ISD::CTTZ &&
18163 "Only scalar CTTZ requires custom lowering");
18165 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18166 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18167 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18169 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18172 DAG.getConstant(NumBits, dl, VT),
18173 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18176 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18179 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18180 // ones, and then concatenate the result back.
18181 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18182 MVT VT = Op.getSimpleValueType();
18184 assert(VT.is256BitVector() && VT.isInteger() &&
18185 "Unsupported value type for operation");
18187 unsigned NumElems = VT.getVectorNumElements();
18190 // Extract the LHS vectors
18191 SDValue LHS = Op.getOperand(0);
18192 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18193 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18195 // Extract the RHS vectors
18196 SDValue RHS = Op.getOperand(1);
18197 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18198 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18200 MVT EltVT = VT.getVectorElementType();
18201 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18203 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18204 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18205 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18208 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18209 if (Op.getValueType() == MVT::i1)
18210 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18211 Op.getOperand(0), Op.getOperand(1));
18212 assert(Op.getSimpleValueType().is256BitVector() &&
18213 Op.getSimpleValueType().isInteger() &&
18214 "Only handle AVX 256-bit vector integer operation");
18215 return Lower256IntArith(Op, DAG);
18218 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18219 if (Op.getValueType() == MVT::i1)
18220 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18221 Op.getOperand(0), Op.getOperand(1));
18222 assert(Op.getSimpleValueType().is256BitVector() &&
18223 Op.getSimpleValueType().isInteger() &&
18224 "Only handle AVX 256-bit vector integer operation");
18225 return Lower256IntArith(Op, DAG);
18228 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18229 assert(Op.getSimpleValueType().is256BitVector() &&
18230 Op.getSimpleValueType().isInteger() &&
18231 "Only handle AVX 256-bit vector integer operation");
18232 return Lower256IntArith(Op, DAG);
18235 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18236 SelectionDAG &DAG) {
18238 MVT VT = Op.getSimpleValueType();
18241 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18243 // Decompose 256-bit ops into smaller 128-bit ops.
18244 if (VT.is256BitVector() && !Subtarget->hasInt256())
18245 return Lower256IntArith(Op, DAG);
18247 SDValue A = Op.getOperand(0);
18248 SDValue B = Op.getOperand(1);
18250 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18251 // pairs, multiply and truncate.
18252 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18253 if (Subtarget->hasInt256()) {
18254 if (VT == MVT::v32i8) {
18255 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18256 SDValue Lo = DAG.getIntPtrConstant(0, dl);
18257 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18258 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18259 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18260 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18261 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18262 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18263 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18264 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18267 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18268 return DAG.getNode(
18269 ISD::TRUNCATE, dl, VT,
18270 DAG.getNode(ISD::MUL, dl, ExVT,
18271 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18272 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18275 assert(VT == MVT::v16i8 &&
18276 "Pre-AVX2 support only supports v16i8 multiplication");
18277 MVT ExVT = MVT::v8i16;
18279 // Extract the lo parts and sign extend to i16
18281 if (Subtarget->hasSSE41()) {
18282 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18283 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18285 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18286 -1, 4, -1, 5, -1, 6, -1, 7};
18287 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18288 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18289 ALo = DAG.getBitcast(ExVT, ALo);
18290 BLo = DAG.getBitcast(ExVT, BLo);
18291 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18292 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18295 // Extract the hi parts and sign extend to i16
18297 if (Subtarget->hasSSE41()) {
18298 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18299 -1, -1, -1, -1, -1, -1, -1, -1};
18300 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18301 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18302 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18303 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18305 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18306 -1, 12, -1, 13, -1, 14, -1, 15};
18307 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18308 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18309 AHi = DAG.getBitcast(ExVT, AHi);
18310 BHi = DAG.getBitcast(ExVT, BHi);
18311 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18312 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18315 // Multiply, mask the lower 8bits of the lo/hi results and pack
18316 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18317 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18318 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18319 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18320 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18323 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18324 if (VT == MVT::v4i32) {
18325 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18326 "Should not custom lower when pmuldq is available!");
18328 // Extract the odd parts.
18329 static const int UnpackMask[] = { 1, -1, 3, -1 };
18330 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18331 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18333 // Multiply the even parts.
18334 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18335 // Now multiply odd parts.
18336 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18338 Evens = DAG.getBitcast(VT, Evens);
18339 Odds = DAG.getBitcast(VT, Odds);
18341 // Merge the two vectors back together with a shuffle. This expands into 2
18343 static const int ShufMask[] = { 0, 4, 2, 6 };
18344 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18347 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18348 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18350 // Ahi = psrlqi(a, 32);
18351 // Bhi = psrlqi(b, 32);
18353 // AloBlo = pmuludq(a, b);
18354 // AloBhi = pmuludq(a, Bhi);
18355 // AhiBlo = pmuludq(Ahi, b);
18357 // AloBhi = psllqi(AloBhi, 32);
18358 // AhiBlo = psllqi(AhiBlo, 32);
18359 // return AloBlo + AloBhi + AhiBlo;
18361 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18362 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18364 SDValue AhiBlo = Ahi;
18365 SDValue AloBhi = Bhi;
18366 // Bit cast to 32-bit vectors for MULUDQ
18367 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18368 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18369 A = DAG.getBitcast(MulVT, A);
18370 B = DAG.getBitcast(MulVT, B);
18371 Ahi = DAG.getBitcast(MulVT, Ahi);
18372 Bhi = DAG.getBitcast(MulVT, Bhi);
18374 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18375 // After shifting right const values the result may be all-zero.
18376 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18377 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18378 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18380 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18381 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18382 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18385 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18386 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18389 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18390 assert(Subtarget->isTargetWin64() && "Unexpected target");
18391 EVT VT = Op.getValueType();
18392 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18393 "Unexpected return type for lowering");
18397 switch (Op->getOpcode()) {
18398 default: llvm_unreachable("Unexpected request for libcall!");
18399 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18400 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18401 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18402 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18403 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18404 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18408 SDValue InChain = DAG.getEntryNode();
18410 TargetLowering::ArgListTy Args;
18411 TargetLowering::ArgListEntry Entry;
18412 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18413 EVT ArgVT = Op->getOperand(i).getValueType();
18414 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18415 "Unexpected argument type for lowering");
18416 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18417 Entry.Node = StackPtr;
18418 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18420 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18421 Entry.Ty = PointerType::get(ArgTy,0);
18422 Entry.isSExt = false;
18423 Entry.isZExt = false;
18424 Args.push_back(Entry);
18427 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18428 getPointerTy(DAG.getDataLayout()));
18430 TargetLowering::CallLoweringInfo CLI(DAG);
18431 CLI.setDebugLoc(dl).setChain(InChain)
18432 .setCallee(getLibcallCallingConv(LC),
18433 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18434 Callee, std::move(Args), 0)
18435 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18437 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18438 return DAG.getBitcast(VT, CallInfo.first);
18441 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18442 SelectionDAG &DAG) {
18443 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18444 MVT VT = Op0.getSimpleValueType();
18447 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18448 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18450 // PMULxD operations multiply each even value (starting at 0) of LHS with
18451 // the related value of RHS and produce a widen result.
18452 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18453 // => <2 x i64> <ae|cg>
18455 // In other word, to have all the results, we need to perform two PMULxD:
18456 // 1. one with the even values.
18457 // 2. one with the odd values.
18458 // To achieve #2, with need to place the odd values at an even position.
18460 // Place the odd value at an even position (basically, shift all values 1
18461 // step to the left):
18462 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18463 // <a|b|c|d> => <b|undef|d|undef>
18464 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18465 // <e|f|g|h> => <f|undef|h|undef>
18466 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18468 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18470 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18471 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18473 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18474 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18475 // => <2 x i64> <ae|cg>
18476 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18477 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18478 // => <2 x i64> <bf|dh>
18479 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18481 // Shuffle it back into the right order.
18482 SDValue Highs, Lows;
18483 if (VT == MVT::v8i32) {
18484 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18485 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18486 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18487 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18489 const int HighMask[] = {1, 5, 3, 7};
18490 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18491 const int LowMask[] = {0, 4, 2, 6};
18492 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18495 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18496 // unsigned multiply.
18497 if (IsSigned && !Subtarget->hasSSE41()) {
18498 SDValue ShAmt = DAG.getConstant(
18500 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18501 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18502 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18503 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18504 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18506 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18507 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18510 // The first result of MUL_LOHI is actually the low value, followed by the
18512 SDValue Ops[] = {Lows, Highs};
18513 return DAG.getMergeValues(Ops, dl);
18516 // Return true if the required (according to Opcode) shift-imm form is natively
18517 // supported by the Subtarget
18518 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18520 if (VT.getScalarSizeInBits() < 16)
18523 if (VT.is512BitVector() &&
18524 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18527 bool LShift = VT.is128BitVector() ||
18528 (VT.is256BitVector() && Subtarget->hasInt256());
18530 bool AShift = LShift && (Subtarget->hasVLX() ||
18531 (VT != MVT::v2i64 && VT != MVT::v4i64));
18532 return (Opcode == ISD::SRA) ? AShift : LShift;
18535 // The shift amount is a variable, but it is the same for all vector lanes.
18536 // These instructions are defined together with shift-immediate.
18538 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18540 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18543 // Return true if the required (according to Opcode) variable-shift form is
18544 // natively supported by the Subtarget
18545 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18548 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18551 // vXi16 supported only on AVX-512, BWI
18552 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18555 if (VT.is512BitVector() || Subtarget->hasVLX())
18558 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18559 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18560 return (Opcode == ISD::SRA) ? AShift : LShift;
18563 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18564 const X86Subtarget *Subtarget) {
18565 MVT VT = Op.getSimpleValueType();
18567 SDValue R = Op.getOperand(0);
18568 SDValue Amt = Op.getOperand(1);
18570 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18571 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18573 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18574 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18575 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18576 SDValue Ex = DAG.getBitcast(ExVT, R);
18578 if (ShiftAmt >= 32) {
18579 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18581 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18582 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18583 ShiftAmt - 32, DAG);
18584 if (VT == MVT::v2i64)
18585 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18586 if (VT == MVT::v4i64)
18587 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18588 {9, 1, 11, 3, 13, 5, 15, 7});
18590 // SRA upper i32, SHL whole i64 and select lower i32.
18591 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18594 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18595 Lower = DAG.getBitcast(ExVT, Lower);
18596 if (VT == MVT::v2i64)
18597 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18598 if (VT == MVT::v4i64)
18599 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18600 {8, 1, 10, 3, 12, 5, 14, 7});
18602 return DAG.getBitcast(VT, Ex);
18605 // Optimize shl/srl/sra with constant shift amount.
18606 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18607 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18608 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18610 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18611 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18613 // i64 SRA needs to be performed as partial shifts.
18614 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18615 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18616 return ArithmeticShiftRight64(ShiftAmt);
18618 if (VT == MVT::v16i8 ||
18619 (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18620 VT == MVT::v64i8) {
18621 unsigned NumElts = VT.getVectorNumElements();
18622 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18624 // Simple i8 add case
18625 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18626 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18628 // ashr(R, 7) === cmp_slt(R, 0)
18629 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18630 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18631 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18634 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18635 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18638 if (Op.getOpcode() == ISD::SHL) {
18639 // Make a large shift.
18640 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18642 SHL = DAG.getBitcast(VT, SHL);
18643 // Zero out the rightmost bits.
18644 return DAG.getNode(ISD::AND, dl, VT, SHL,
18645 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18647 if (Op.getOpcode() == ISD::SRL) {
18648 // Make a large shift.
18649 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18651 SRL = DAG.getBitcast(VT, SRL);
18652 // Zero out the leftmost bits.
18653 return DAG.getNode(ISD::AND, dl, VT, SRL,
18654 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18656 if (Op.getOpcode() == ISD::SRA) {
18657 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18658 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18660 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18661 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18662 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18665 llvm_unreachable("Unknown shift opcode.");
18670 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18671 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18672 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18674 // Peek through any splat that was introduced for i64 shift vectorization.
18675 int SplatIndex = -1;
18676 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18677 if (SVN->isSplat()) {
18678 SplatIndex = SVN->getSplatIndex();
18679 Amt = Amt.getOperand(0);
18680 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18681 "Splat shuffle referencing second operand");
18684 if (Amt.getOpcode() != ISD::BITCAST ||
18685 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18688 Amt = Amt.getOperand(0);
18689 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18690 VT.getVectorNumElements();
18691 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18692 uint64_t ShiftAmt = 0;
18693 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18694 for (unsigned i = 0; i != Ratio; ++i) {
18695 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18699 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18702 // Check remaining shift amounts (if not a splat).
18703 if (SplatIndex < 0) {
18704 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18705 uint64_t ShAmt = 0;
18706 for (unsigned j = 0; j != Ratio; ++j) {
18707 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18711 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18713 if (ShAmt != ShiftAmt)
18718 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18719 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18721 if (Op.getOpcode() == ISD::SRA)
18722 return ArithmeticShiftRight64(ShiftAmt);
18728 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18729 const X86Subtarget* Subtarget) {
18730 MVT VT = Op.getSimpleValueType();
18732 SDValue R = Op.getOperand(0);
18733 SDValue Amt = Op.getOperand(1);
18735 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18736 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18738 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18739 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18741 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18743 MVT EltVT = VT.getVectorElementType();
18745 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18746 // Check if this build_vector node is doing a splat.
18747 // If so, then set BaseShAmt equal to the splat value.
18748 BaseShAmt = BV->getSplatValue();
18749 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18750 BaseShAmt = SDValue();
18752 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18753 Amt = Amt.getOperand(0);
18755 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18756 if (SVN && SVN->isSplat()) {
18757 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18758 SDValue InVec = Amt.getOperand(0);
18759 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18760 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18761 "Unexpected shuffle index found!");
18762 BaseShAmt = InVec.getOperand(SplatIdx);
18763 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18764 if (ConstantSDNode *C =
18765 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18766 if (C->getZExtValue() == SplatIdx)
18767 BaseShAmt = InVec.getOperand(1);
18772 // Avoid introducing an extract element from a shuffle.
18773 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18774 DAG.getIntPtrConstant(SplatIdx, dl));
18778 if (BaseShAmt.getNode()) {
18779 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18780 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18781 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18782 else if (EltVT.bitsLT(MVT::i32))
18783 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18785 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18789 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18790 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18791 Amt.getOpcode() == ISD::BITCAST &&
18792 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18793 Amt = Amt.getOperand(0);
18794 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18795 VT.getVectorNumElements();
18796 std::vector<SDValue> Vals(Ratio);
18797 for (unsigned i = 0; i != Ratio; ++i)
18798 Vals[i] = Amt.getOperand(i);
18799 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18800 for (unsigned j = 0; j != Ratio; ++j)
18801 if (Vals[j] != Amt.getOperand(i + j))
18805 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18806 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18811 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18812 SelectionDAG &DAG) {
18813 MVT VT = Op.getSimpleValueType();
18815 SDValue R = Op.getOperand(0);
18816 SDValue Amt = Op.getOperand(1);
18818 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18819 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18821 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18824 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18827 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18830 // XOP has 128-bit variable logical/arithmetic shifts.
18831 // +ve/-ve Amt = shift left/right.
18832 if (Subtarget->hasXOP() &&
18833 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18834 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18835 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18836 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18837 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18839 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18840 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18841 if (Op.getOpcode() == ISD::SRA)
18842 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18845 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18846 // shifts per-lane and then shuffle the partial results back together.
18847 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18848 // Splat the shift amounts so the scalar shifts above will catch it.
18849 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18850 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18851 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18852 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18853 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18856 // i64 vector arithmetic shift can be emulated with the transform:
18857 // M = lshr(SIGN_BIT, Amt)
18858 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18859 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18860 Op.getOpcode() == ISD::SRA) {
18861 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18862 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18863 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18864 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18865 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18869 // If possible, lower this packed shift into a vector multiply instead of
18870 // expanding it into a sequence of scalar shifts.
18871 // Do this only if the vector shift count is a constant build_vector.
18872 if (Op.getOpcode() == ISD::SHL &&
18873 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18874 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18875 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18876 SmallVector<SDValue, 8> Elts;
18877 MVT SVT = VT.getVectorElementType();
18878 unsigned SVTBits = SVT.getSizeInBits();
18879 APInt One(SVTBits, 1);
18880 unsigned NumElems = VT.getVectorNumElements();
18882 for (unsigned i=0; i !=NumElems; ++i) {
18883 SDValue Op = Amt->getOperand(i);
18884 if (Op->getOpcode() == ISD::UNDEF) {
18885 Elts.push_back(Op);
18889 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18890 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18891 uint64_t ShAmt = C.getZExtValue();
18892 if (ShAmt >= SVTBits) {
18893 Elts.push_back(DAG.getUNDEF(SVT));
18896 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18898 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18899 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18902 // Lower SHL with variable shift amount.
18903 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18904 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18906 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18907 DAG.getConstant(0x3f800000U, dl, VT));
18908 Op = DAG.getBitcast(MVT::v4f32, Op);
18909 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18910 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18913 // If possible, lower this shift as a sequence of two shifts by
18914 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18916 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18918 // Could be rewritten as:
18919 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18921 // The advantage is that the two shifts from the example would be
18922 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18923 // the vector shift into four scalar shifts plus four pairs of vector
18925 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18926 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18927 unsigned TargetOpcode = X86ISD::MOVSS;
18928 bool CanBeSimplified;
18929 // The splat value for the first packed shift (the 'X' from the example).
18930 SDValue Amt1 = Amt->getOperand(0);
18931 // The splat value for the second packed shift (the 'Y' from the example).
18932 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18933 Amt->getOperand(2);
18935 // See if it is possible to replace this node with a sequence of
18936 // two shifts followed by a MOVSS/MOVSD
18937 if (VT == MVT::v4i32) {
18938 // Check if it is legal to use a MOVSS.
18939 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18940 Amt2 == Amt->getOperand(3);
18941 if (!CanBeSimplified) {
18942 // Otherwise, check if we can still simplify this node using a MOVSD.
18943 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18944 Amt->getOperand(2) == Amt->getOperand(3);
18945 TargetOpcode = X86ISD::MOVSD;
18946 Amt2 = Amt->getOperand(2);
18949 // Do similar checks for the case where the machine value type
18951 CanBeSimplified = Amt1 == Amt->getOperand(1);
18952 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18953 CanBeSimplified = Amt2 == Amt->getOperand(i);
18955 if (!CanBeSimplified) {
18956 TargetOpcode = X86ISD::MOVSD;
18957 CanBeSimplified = true;
18958 Amt2 = Amt->getOperand(4);
18959 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18960 CanBeSimplified = Amt1 == Amt->getOperand(i);
18961 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18962 CanBeSimplified = Amt2 == Amt->getOperand(j);
18966 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18967 isa<ConstantSDNode>(Amt2)) {
18968 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18969 MVT CastVT = MVT::v4i32;
18971 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18972 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18974 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18975 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18976 if (TargetOpcode == X86ISD::MOVSD)
18977 CastVT = MVT::v2i64;
18978 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18979 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18980 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18982 return DAG.getBitcast(VT, Result);
18986 // v4i32 Non Uniform Shifts.
18987 // If the shift amount is constant we can shift each lane using the SSE2
18988 // immediate shifts, else we need to zero-extend each lane to the lower i64
18989 // and shift using the SSE2 variable shifts.
18990 // The separate results can then be blended together.
18991 if (VT == MVT::v4i32) {
18992 unsigned Opc = Op.getOpcode();
18993 SDValue Amt0, Amt1, Amt2, Amt3;
18994 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18995 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18996 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18997 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18998 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
19000 // ISD::SHL is handled above but we include it here for completeness.
19003 llvm_unreachable("Unknown target vector shift node");
19005 Opc = X86ISD::VSHL;
19008 Opc = X86ISD::VSRL;
19011 Opc = X86ISD::VSRA;
19014 // The SSE2 shifts use the lower i64 as the same shift amount for
19015 // all lanes and the upper i64 is ignored. These shuffle masks
19016 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
19017 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19018 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
19019 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
19020 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
19021 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
19024 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
19025 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
19026 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
19027 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
19028 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19029 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19030 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19033 if (VT == MVT::v16i8 ||
19034 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19035 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19036 unsigned ShiftOpcode = Op->getOpcode();
19038 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19039 // On SSE41 targets we make use of the fact that VSELECT lowers
19040 // to PBLENDVB which selects bytes based just on the sign bit.
19041 if (Subtarget->hasSSE41()) {
19042 V0 = DAG.getBitcast(VT, V0);
19043 V1 = DAG.getBitcast(VT, V1);
19044 Sel = DAG.getBitcast(VT, Sel);
19045 return DAG.getBitcast(SelVT,
19046 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19048 // On pre-SSE41 targets we test for the sign bit by comparing to
19049 // zero - a negative value will set all bits of the lanes to true
19050 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19051 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19052 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19053 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19056 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19057 // We can safely do this using i16 shifts as we're only interested in
19058 // the 3 lower bits of each byte.
19059 Amt = DAG.getBitcast(ExtVT, Amt);
19060 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19061 Amt = DAG.getBitcast(VT, Amt);
19063 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19064 // r = VSELECT(r, shift(r, 4), a);
19066 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19067 R = SignBitSelect(VT, Amt, M, R);
19070 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19072 // r = VSELECT(r, shift(r, 2), a);
19073 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19074 R = SignBitSelect(VT, Amt, M, R);
19077 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19079 // return VSELECT(r, shift(r, 1), a);
19080 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19081 R = SignBitSelect(VT, Amt, M, R);
19085 if (Op->getOpcode() == ISD::SRA) {
19086 // For SRA we need to unpack each byte to the higher byte of a i16 vector
19087 // so we can correctly sign extend. We don't care what happens to the
19089 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19090 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19091 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19092 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19093 ALo = DAG.getBitcast(ExtVT, ALo);
19094 AHi = DAG.getBitcast(ExtVT, AHi);
19095 RLo = DAG.getBitcast(ExtVT, RLo);
19096 RHi = DAG.getBitcast(ExtVT, RHi);
19098 // r = VSELECT(r, shift(r, 4), a);
19099 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19100 DAG.getConstant(4, dl, ExtVT));
19101 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19102 DAG.getConstant(4, dl, ExtVT));
19103 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19104 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19107 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19108 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19110 // r = VSELECT(r, shift(r, 2), a);
19111 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19112 DAG.getConstant(2, dl, ExtVT));
19113 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19114 DAG.getConstant(2, dl, ExtVT));
19115 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19116 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19119 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19120 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19122 // r = VSELECT(r, shift(r, 1), a);
19123 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19124 DAG.getConstant(1, dl, ExtVT));
19125 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19126 DAG.getConstant(1, dl, ExtVT));
19127 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19128 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19130 // Logical shift the result back to the lower byte, leaving a zero upper
19132 // meaning that we can safely pack with PACKUSWB.
19134 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19136 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19137 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19141 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19142 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19143 // solution better.
19144 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19145 MVT ExtVT = MVT::v8i32;
19147 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19148 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19149 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19150 return DAG.getNode(ISD::TRUNCATE, dl, VT,
19151 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19154 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19155 MVT ExtVT = MVT::v8i32;
19156 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19157 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19158 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19159 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19160 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19161 ALo = DAG.getBitcast(ExtVT, ALo);
19162 AHi = DAG.getBitcast(ExtVT, AHi);
19163 RLo = DAG.getBitcast(ExtVT, RLo);
19164 RHi = DAG.getBitcast(ExtVT, RHi);
19165 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19166 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19167 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19168 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19169 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19172 if (VT == MVT::v8i16) {
19173 unsigned ShiftOpcode = Op->getOpcode();
19175 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19176 // On SSE41 targets we make use of the fact that VSELECT lowers
19177 // to PBLENDVB which selects bytes based just on the sign bit.
19178 if (Subtarget->hasSSE41()) {
19179 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19180 V0 = DAG.getBitcast(ExtVT, V0);
19181 V1 = DAG.getBitcast(ExtVT, V1);
19182 Sel = DAG.getBitcast(ExtVT, Sel);
19183 return DAG.getBitcast(
19184 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19186 // On pre-SSE41 targets we splat the sign bit - a negative value will
19187 // set all bits of the lanes to true and VSELECT uses that in
19188 // its OR(AND(V0,C),AND(V1,~C)) lowering.
19190 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19191 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19194 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19195 if (Subtarget->hasSSE41()) {
19196 // On SSE41 targets we need to replicate the shift mask in both
19197 // bytes for PBLENDVB.
19200 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19201 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19203 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19206 // r = VSELECT(r, shift(r, 8), a);
19207 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19208 R = SignBitSelect(Amt, M, R);
19211 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19213 // r = VSELECT(r, shift(r, 4), a);
19214 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19215 R = SignBitSelect(Amt, M, R);
19218 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19220 // r = VSELECT(r, shift(r, 2), a);
19221 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19222 R = SignBitSelect(Amt, M, R);
19225 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19227 // return VSELECT(r, shift(r, 1), a);
19228 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19229 R = SignBitSelect(Amt, M, R);
19233 // Decompose 256-bit shifts into smaller 128-bit shifts.
19234 if (VT.is256BitVector()) {
19235 unsigned NumElems = VT.getVectorNumElements();
19236 MVT EltVT = VT.getVectorElementType();
19237 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19239 // Extract the two vectors
19240 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19241 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19243 // Recreate the shift amount vectors
19244 SDValue Amt1, Amt2;
19245 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19246 // Constant shift amount
19247 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19248 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19249 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19251 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19252 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19254 // Variable shift amount
19255 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19256 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19259 // Issue new vector shifts for the smaller types
19260 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19261 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19263 // Concatenate the result back
19264 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19270 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19271 SelectionDAG &DAG) {
19272 MVT VT = Op.getSimpleValueType();
19274 SDValue R = Op.getOperand(0);
19275 SDValue Amt = Op.getOperand(1);
19277 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19278 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19279 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19281 // XOP has 128-bit vector variable + immediate rotates.
19282 // +ve/-ve Amt = rotate left/right.
19284 // Split 256-bit integers.
19285 if (VT.is256BitVector())
19286 return Lower256IntArith(Op, DAG);
19288 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19290 // Attempt to rotate by immediate.
19291 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19292 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19293 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19294 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19295 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19296 DAG.getConstant(RotateAmt, DL, MVT::i8));
19300 // Use general rotate by variable (per-element).
19301 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19304 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19305 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19306 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19307 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19308 // has only one use.
19309 SDNode *N = Op.getNode();
19310 SDValue LHS = N->getOperand(0);
19311 SDValue RHS = N->getOperand(1);
19312 unsigned BaseOp = 0;
19315 switch (Op.getOpcode()) {
19316 default: llvm_unreachable("Unknown ovf instruction!");
19318 // A subtract of one will be selected as a INC. Note that INC doesn't
19319 // set CF, so we can't do this for UADDO.
19320 if (isOneConstant(RHS)) {
19321 BaseOp = X86ISD::INC;
19322 Cond = X86::COND_O;
19325 BaseOp = X86ISD::ADD;
19326 Cond = X86::COND_O;
19329 BaseOp = X86ISD::ADD;
19330 Cond = X86::COND_B;
19333 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19334 // set CF, so we can't do this for USUBO.
19335 if (isOneConstant(RHS)) {
19336 BaseOp = X86ISD::DEC;
19337 Cond = X86::COND_O;
19340 BaseOp = X86ISD::SUB;
19341 Cond = X86::COND_O;
19344 BaseOp = X86ISD::SUB;
19345 Cond = X86::COND_B;
19348 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19349 Cond = X86::COND_O;
19351 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19352 if (N->getValueType(0) == MVT::i8) {
19353 BaseOp = X86ISD::UMUL8;
19354 Cond = X86::COND_O;
19357 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19359 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19362 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19363 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19364 SDValue(Sum.getNode(), 2));
19366 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19370 // Also sets EFLAGS.
19371 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19372 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19375 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19376 DAG.getConstant(Cond, DL, MVT::i32),
19377 SDValue(Sum.getNode(), 1));
19379 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19382 /// Returns true if the operand type is exactly twice the native width, and
19383 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19384 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19385 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19386 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19387 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19390 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19391 else if (OpWidth == 128)
19392 return Subtarget->hasCmpxchg16b();
19397 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19398 return needsCmpXchgNb(SI->getValueOperand()->getType());
19401 // Note: this turns large loads into lock cmpxchg8b/16b.
19402 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19403 TargetLowering::AtomicExpansionKind
19404 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19405 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19406 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19407 : AtomicExpansionKind::None;
19410 TargetLowering::AtomicExpansionKind
19411 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19412 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19413 Type *MemType = AI->getType();
19415 // If the operand is too big, we must see if cmpxchg8/16b is available
19416 // and default to library calls otherwise.
19417 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19418 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19419 : AtomicExpansionKind::None;
19422 AtomicRMWInst::BinOp Op = AI->getOperation();
19425 llvm_unreachable("Unknown atomic operation");
19426 case AtomicRMWInst::Xchg:
19427 case AtomicRMWInst::Add:
19428 case AtomicRMWInst::Sub:
19429 // It's better to use xadd, xsub or xchg for these in all cases.
19430 return AtomicExpansionKind::None;
19431 case AtomicRMWInst::Or:
19432 case AtomicRMWInst::And:
19433 case AtomicRMWInst::Xor:
19434 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19435 // prefix to a normal instruction for these operations.
19436 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19437 : AtomicExpansionKind::None;
19438 case AtomicRMWInst::Nand:
19439 case AtomicRMWInst::Max:
19440 case AtomicRMWInst::Min:
19441 case AtomicRMWInst::UMax:
19442 case AtomicRMWInst::UMin:
19443 // These always require a non-trivial set of data operations on x86. We must
19444 // use a cmpxchg loop.
19445 return AtomicExpansionKind::CmpXChg;
19449 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19450 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19451 // no-sse2). There isn't any reason to disable it if the target processor
19453 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19457 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19458 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19459 Type *MemType = AI->getType();
19460 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19461 // there is no benefit in turning such RMWs into loads, and it is actually
19462 // harmful as it introduces a mfence.
19463 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19466 auto Builder = IRBuilder<>(AI);
19467 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19468 auto SynchScope = AI->getSynchScope();
19469 // We must restrict the ordering to avoid generating loads with Release or
19470 // ReleaseAcquire orderings.
19471 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19472 auto Ptr = AI->getPointerOperand();
19474 // Before the load we need a fence. Here is an example lifted from
19475 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19478 // x.store(1, relaxed);
19479 // r1 = y.fetch_add(0, release);
19481 // y.fetch_add(42, acquire);
19482 // r2 = x.load(relaxed);
19483 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19484 // lowered to just a load without a fence. A mfence flushes the store buffer,
19485 // making the optimization clearly correct.
19486 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19487 // otherwise, we might be able to be more aggressive on relaxed idempotent
19488 // rmw. In practice, they do not look useful, so we don't try to be
19489 // especially clever.
19490 if (SynchScope == SingleThread)
19491 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19492 // the IR level, so we must wrap it in an intrinsic.
19495 if (!hasMFENCE(*Subtarget))
19496 // FIXME: it might make sense to use a locked operation here but on a
19497 // different cache-line to prevent cache-line bouncing. In practice it
19498 // is probably a small win, and x86 processors without mfence are rare
19499 // enough that we do not bother.
19503 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19504 Builder.CreateCall(MFence, {});
19506 // Finally we can emit the atomic load.
19507 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19508 AI->getType()->getPrimitiveSizeInBits());
19509 Loaded->setAtomic(Order, SynchScope);
19510 AI->replaceAllUsesWith(Loaded);
19511 AI->eraseFromParent();
19515 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19516 SelectionDAG &DAG) {
19518 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19519 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19520 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19521 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19523 // The only fence that needs an instruction is a sequentially-consistent
19524 // cross-thread fence.
19525 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19526 if (hasMFENCE(*Subtarget))
19527 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19529 SDValue Chain = Op.getOperand(0);
19530 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19532 DAG.getRegister(X86::ESP, MVT::i32), // Base
19533 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19534 DAG.getRegister(0, MVT::i32), // Index
19535 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19536 DAG.getRegister(0, MVT::i32), // Segment.
19540 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19541 return SDValue(Res, 0);
19544 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19545 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19548 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19549 SelectionDAG &DAG) {
19550 MVT T = Op.getSimpleValueType();
19554 switch(T.SimpleTy) {
19555 default: llvm_unreachable("Invalid value type!");
19556 case MVT::i8: Reg = X86::AL; size = 1; break;
19557 case MVT::i16: Reg = X86::AX; size = 2; break;
19558 case MVT::i32: Reg = X86::EAX; size = 4; break;
19560 assert(Subtarget->is64Bit() && "Node not type legal!");
19561 Reg = X86::RAX; size = 8;
19564 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19565 Op.getOperand(2), SDValue());
19566 SDValue Ops[] = { cpIn.getValue(0),
19569 DAG.getTargetConstant(size, DL, MVT::i8),
19570 cpIn.getValue(1) };
19571 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19572 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19573 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19577 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19578 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19579 MVT::i32, cpOut.getValue(2));
19580 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19581 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19584 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19585 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19586 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19590 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19591 SelectionDAG &DAG) {
19592 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19593 MVT DstVT = Op.getSimpleValueType();
19595 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19596 SrcVT == MVT::i64) {
19597 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19598 if (DstVT != MVT::f64)
19599 // This conversion needs to be expanded.
19602 SDValue Op0 = Op->getOperand(0);
19603 SmallVector<SDValue, 16> Elts;
19607 if (SrcVT.isVector()) {
19608 NumElts = SrcVT.getVectorNumElements();
19609 SVT = SrcVT.getVectorElementType();
19611 // Widen the vector in input in the case of MVT::v2i32.
19612 // Example: from MVT::v2i32 to MVT::v4i32.
19613 for (unsigned i = 0, e = NumElts; i != e; ++i)
19614 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19615 DAG.getIntPtrConstant(i, dl)));
19617 assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19618 "Unexpected source type in LowerBITCAST");
19619 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19620 DAG.getIntPtrConstant(0, dl)));
19621 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19622 DAG.getIntPtrConstant(1, dl)));
19626 // Explicitly mark the extra elements as Undef.
19627 Elts.append(NumElts, DAG.getUNDEF(SVT));
19629 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19630 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19631 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19633 DAG.getIntPtrConstant(0, dl));
19636 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19637 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19638 assert((DstVT == MVT::i64 ||
19639 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19640 "Unexpected custom BITCAST");
19641 // i64 <=> MMX conversions are Legal.
19642 if (SrcVT==MVT::i64 && DstVT.isVector())
19644 if (DstVT==MVT::i64 && SrcVT.isVector())
19646 // MMX <=> MMX conversions are Legal.
19647 if (SrcVT.isVector() && DstVT.isVector())
19649 // All other conversions need to be expanded.
19653 /// Compute the horizontal sum of bytes in V for the elements of VT.
19655 /// Requires V to be a byte vector and VT to be an integer vector type with
19656 /// wider elements than V's type. The width of the elements of VT determines
19657 /// how many bytes of V are summed horizontally to produce each element of the
19659 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19660 const X86Subtarget *Subtarget,
19661 SelectionDAG &DAG) {
19663 MVT ByteVecVT = V.getSimpleValueType();
19664 MVT EltVT = VT.getVectorElementType();
19665 int NumElts = VT.getVectorNumElements();
19666 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19667 "Expected value to have byte element type.");
19668 assert(EltVT != MVT::i8 &&
19669 "Horizontal byte sum only makes sense for wider elements!");
19670 unsigned VecSize = VT.getSizeInBits();
19671 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19673 // PSADBW instruction horizontally add all bytes and leave the result in i64
19674 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19675 if (EltVT == MVT::i64) {
19676 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19677 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19678 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19679 return DAG.getBitcast(VT, V);
19682 if (EltVT == MVT::i32) {
19683 // We unpack the low half and high half into i32s interleaved with zeros so
19684 // that we can use PSADBW to horizontally sum them. The most useful part of
19685 // this is that it lines up the results of two PSADBW instructions to be
19686 // two v2i64 vectors which concatenated are the 4 population counts. We can
19687 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19688 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19689 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19690 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19692 // Do the horizontal sums into two v2i64s.
19693 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19694 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19695 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19696 DAG.getBitcast(ByteVecVT, Low), Zeros);
19697 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19698 DAG.getBitcast(ByteVecVT, High), Zeros);
19700 // Merge them together.
19701 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19702 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19703 DAG.getBitcast(ShortVecVT, Low),
19704 DAG.getBitcast(ShortVecVT, High));
19706 return DAG.getBitcast(VT, V);
19709 // The only element type left is i16.
19710 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19712 // To obtain pop count for each i16 element starting from the pop count for
19713 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19714 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19715 // directly supported.
19716 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19717 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19718 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19719 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19720 DAG.getBitcast(ByteVecVT, V));
19721 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19724 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19725 const X86Subtarget *Subtarget,
19726 SelectionDAG &DAG) {
19727 MVT VT = Op.getSimpleValueType();
19728 MVT EltVT = VT.getVectorElementType();
19729 unsigned VecSize = VT.getSizeInBits();
19731 // Implement a lookup table in register by using an algorithm based on:
19732 // http://wm.ite.pl/articles/sse-popcount.html
19734 // The general idea is that every lower byte nibble in the input vector is an
19735 // index into a in-register pre-computed pop count table. We then split up the
19736 // input vector in two new ones: (1) a vector with only the shifted-right
19737 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19738 // masked out higher ones) for each byte. PSHUB is used separately with both
19739 // to index the in-register table. Next, both are added and the result is a
19740 // i8 vector where each element contains the pop count for input byte.
19742 // To obtain the pop count for elements != i8, we follow up with the same
19743 // approach and use additional tricks as described below.
19745 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19746 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19747 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19748 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19750 int NumByteElts = VecSize / 8;
19751 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19752 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19753 SmallVector<SDValue, 16> LUTVec;
19754 for (int i = 0; i < NumByteElts; ++i)
19755 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19756 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19757 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19758 DAG.getConstant(0x0F, DL, MVT::i8));
19759 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19762 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19763 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19764 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19767 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19769 // The input vector is used as the shuffle mask that index elements into the
19770 // LUT. After counting low and high nibbles, add the vector to obtain the
19771 // final pop count per i8 element.
19772 SDValue HighPopCnt =
19773 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19774 SDValue LowPopCnt =
19775 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19776 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19778 if (EltVT == MVT::i8)
19781 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19784 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19785 const X86Subtarget *Subtarget,
19786 SelectionDAG &DAG) {
19787 MVT VT = Op.getSimpleValueType();
19788 assert(VT.is128BitVector() &&
19789 "Only 128-bit vector bitmath lowering supported.");
19791 int VecSize = VT.getSizeInBits();
19792 MVT EltVT = VT.getVectorElementType();
19793 int Len = EltVT.getSizeInBits();
19795 // This is the vectorized version of the "best" algorithm from
19796 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19797 // with a minor tweak to use a series of adds + shifts instead of vector
19798 // multiplications. Implemented for all integer vector types. We only use
19799 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19800 // much faster, even faster than using native popcnt instructions.
19802 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19803 MVT VT = V.getSimpleValueType();
19804 SmallVector<SDValue, 32> Shifters(
19805 VT.getVectorNumElements(),
19806 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19807 return DAG.getNode(OpCode, DL, VT, V,
19808 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19810 auto GetMask = [&](SDValue V, APInt Mask) {
19811 MVT VT = V.getSimpleValueType();
19812 SmallVector<SDValue, 32> Masks(
19813 VT.getVectorNumElements(),
19814 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19815 return DAG.getNode(ISD::AND, DL, VT, V,
19816 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19819 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19820 // x86, so set the SRL type to have elements at least i16 wide. This is
19821 // correct because all of our SRLs are followed immediately by a mask anyways
19822 // that handles any bits that sneak into the high bits of the byte elements.
19823 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19827 // v = v - ((v >> 1) & 0x55555555...)
19829 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19830 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19831 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19833 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19834 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19835 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19836 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19837 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19839 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19840 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19841 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19842 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19844 // At this point, V contains the byte-wise population count, and we are
19845 // merely doing a horizontal sum if necessary to get the wider element
19847 if (EltVT == MVT::i8)
19850 return LowerHorizontalByteSum(
19851 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19855 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19856 SelectionDAG &DAG) {
19857 MVT VT = Op.getSimpleValueType();
19858 // FIXME: Need to add AVX-512 support here!
19859 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19860 "Unknown CTPOP type to handle");
19861 SDLoc DL(Op.getNode());
19862 SDValue Op0 = Op.getOperand(0);
19864 if (!Subtarget->hasSSSE3()) {
19865 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19866 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19867 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19870 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19871 unsigned NumElems = VT.getVectorNumElements();
19873 // Extract each 128-bit vector, compute pop count and concat the result.
19874 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19875 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19877 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19878 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19879 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19882 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19885 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19886 SelectionDAG &DAG) {
19887 assert(Op.getSimpleValueType().isVector() &&
19888 "We only do custom lowering for vector population count.");
19889 return LowerVectorCTPOP(Op, Subtarget, DAG);
19892 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19893 SDNode *Node = Op.getNode();
19895 EVT T = Node->getValueType(0);
19896 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19897 DAG.getConstant(0, dl, T), Node->getOperand(2));
19898 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19899 cast<AtomicSDNode>(Node)->getMemoryVT(),
19900 Node->getOperand(0),
19901 Node->getOperand(1), negOp,
19902 cast<AtomicSDNode>(Node)->getMemOperand(),
19903 cast<AtomicSDNode>(Node)->getOrdering(),
19904 cast<AtomicSDNode>(Node)->getSynchScope());
19907 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19908 SDNode *Node = Op.getNode();
19910 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19912 // Convert seq_cst store -> xchg
19913 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19914 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19915 // (The only way to get a 16-byte store is cmpxchg16b)
19916 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19917 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19918 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19919 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19920 cast<AtomicSDNode>(Node)->getMemoryVT(),
19921 Node->getOperand(0),
19922 Node->getOperand(1), Node->getOperand(2),
19923 cast<AtomicSDNode>(Node)->getMemOperand(),
19924 cast<AtomicSDNode>(Node)->getOrdering(),
19925 cast<AtomicSDNode>(Node)->getSynchScope());
19926 return Swap.getValue(1);
19928 // Other atomic stores have a simple pattern.
19932 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19933 MVT VT = Op.getNode()->getSimpleValueType(0);
19935 // Let legalize expand this if it isn't a legal type yet.
19936 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19939 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19942 bool ExtraOp = false;
19943 switch (Op.getOpcode()) {
19944 default: llvm_unreachable("Invalid code");
19945 case ISD::ADDC: Opc = X86ISD::ADD; break;
19946 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19947 case ISD::SUBC: Opc = X86ISD::SUB; break;
19948 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19952 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19954 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19955 Op.getOperand(1), Op.getOperand(2));
19958 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19959 SelectionDAG &DAG) {
19960 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19962 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19963 // which returns the values as { float, float } (in XMM0) or
19964 // { double, double } (which is returned in XMM0, XMM1).
19966 SDValue Arg = Op.getOperand(0);
19967 EVT ArgVT = Arg.getValueType();
19968 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19970 TargetLowering::ArgListTy Args;
19971 TargetLowering::ArgListEntry Entry;
19975 Entry.isSExt = false;
19976 Entry.isZExt = false;
19977 Args.push_back(Entry);
19979 bool isF64 = ArgVT == MVT::f64;
19980 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19981 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19982 // the results are returned via SRet in memory.
19983 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19986 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19988 Type *RetTy = isF64
19989 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19990 : (Type*)VectorType::get(ArgTy, 4);
19992 TargetLowering::CallLoweringInfo CLI(DAG);
19993 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19994 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19996 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19999 // Returned in xmm0 and xmm1.
20000 return CallResult.first;
20002 // Returned in bits 0:31 and 32:64 xmm0.
20003 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20004 CallResult.first, DAG.getIntPtrConstant(0, dl));
20005 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20006 CallResult.first, DAG.getIntPtrConstant(1, dl));
20007 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
20008 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
20011 /// Widen a vector input to a vector of NVT. The
20012 /// input vector must have the same element type as NVT.
20013 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
20014 bool FillWithZeroes = false) {
20015 // Check if InOp already has the right width.
20016 MVT InVT = InOp.getSimpleValueType();
20020 if (InOp.isUndef())
20021 return DAG.getUNDEF(NVT);
20023 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
20024 "input and widen element type must match");
20026 unsigned InNumElts = InVT.getVectorNumElements();
20027 unsigned WidenNumElts = NVT.getVectorNumElements();
20028 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20029 "Unexpected request for vector widening");
20031 EVT EltVT = NVT.getVectorElementType();
20034 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20035 InOp.getNumOperands() == 2) {
20036 SDValue N1 = InOp.getOperand(1);
20037 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20039 InOp = InOp.getOperand(0);
20040 InVT = InOp.getSimpleValueType();
20041 InNumElts = InVT.getVectorNumElements();
20044 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20045 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20046 SmallVector<SDValue, 16> Ops;
20047 for (unsigned i = 0; i < InNumElts; ++i)
20048 Ops.push_back(InOp.getOperand(i));
20050 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20051 DAG.getUNDEF(EltVT);
20052 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20053 Ops.push_back(FillVal);
20054 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20056 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20058 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20059 InOp, DAG.getIntPtrConstant(0, dl));
20062 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20063 SelectionDAG &DAG) {
20064 assert(Subtarget->hasAVX512() &&
20065 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20067 // X86 scatter kills mask register, so its type should be added to
20068 // the list of return values.
20069 // If the "scatter" has 2 return values, it is already handled.
20070 if (Op.getNode()->getNumValues() == 2)
20073 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20074 SDValue Src = N->getValue();
20075 MVT VT = Src.getSimpleValueType();
20076 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20079 SDValue NewScatter;
20080 SDValue Index = N->getIndex();
20081 SDValue Mask = N->getMask();
20082 SDValue Chain = N->getChain();
20083 SDValue BasePtr = N->getBasePtr();
20084 MVT MemVT = N->getMemoryVT().getSimpleVT();
20085 MVT IndexVT = Index.getSimpleValueType();
20086 MVT MaskVT = Mask.getSimpleValueType();
20088 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20089 // The v2i32 value was promoted to v2i64.
20090 // Now we "redo" the type legalizer's work and widen the original
20091 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20093 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20094 "Unexpected memory type");
20095 int ShuffleMask[] = {0, 2, -1, -1};
20096 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20097 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20098 // Now we have 4 elements instead of 2.
20099 // Expand the index.
20100 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20101 Index = ExtendToType(Index, NewIndexVT, DAG);
20103 // Expand the mask with zeroes
20104 // Mask may be <2 x i64> or <2 x i1> at this moment
20105 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20106 "Unexpected mask type");
20107 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20108 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20112 unsigned NumElts = VT.getVectorNumElements();
20113 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20114 !Index.getSimpleValueType().is512BitVector()) {
20115 // AVX512F supports only 512-bit vectors. Or data or index should
20116 // be 512 bit wide. If now the both index and data are 256-bit, but
20117 // the vector contains 8 elements, we just sign-extend the index
20118 if (IndexVT == MVT::v8i32)
20119 // Just extend index
20120 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20122 // The minimal number of elts in scatter is 8
20125 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20126 // Use original index here, do not modify the index twice
20127 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20128 if (IndexVT.getScalarType() == MVT::i32)
20129 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20132 // At this point we have promoted mask operand
20133 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20134 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20135 // Use the original mask here, do not modify the mask twice
20136 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20138 // The value that should be stored
20139 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20140 Src = ExtendToType(Src, NewVT, DAG);
20143 // If the mask is "wide" at this point - truncate it to i1 vector
20144 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20145 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20147 // The mask is killed by scatter, add it to the values
20148 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20149 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20150 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20151 N->getMemOperand());
20152 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20153 return SDValue(NewScatter.getNode(), 0);
20156 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20157 SelectionDAG &DAG) {
20159 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20160 MVT VT = Op.getSimpleValueType();
20161 SDValue Mask = N->getMask();
20164 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20165 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20166 // This operation is legal for targets with VLX, but without
20167 // VLX the vector should be widened to 512 bit
20168 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20169 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20170 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20171 SDValue Src0 = N->getSrc0();
20172 Src0 = ExtendToType(Src0, WideDataVT, DAG);
20173 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20174 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20175 N->getBasePtr(), Mask, Src0,
20176 N->getMemoryVT(), N->getMemOperand(),
20177 N->getExtensionType());
20179 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20180 NewLoad.getValue(0),
20181 DAG.getIntPtrConstant(0, dl));
20182 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20183 return DAG.getMergeValues(RetOps, dl);
20188 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20189 SelectionDAG &DAG) {
20190 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20191 SDValue DataToStore = N->getValue();
20192 MVT VT = DataToStore.getSimpleValueType();
20193 SDValue Mask = N->getMask();
20196 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20197 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20198 // This operation is legal for targets with VLX, but without
20199 // VLX the vector should be widened to 512 bit
20200 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20201 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20202 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20203 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20204 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20205 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20206 Mask, N->getMemoryVT(), N->getMemOperand(),
20207 N->isTruncatingStore());
20212 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20213 SelectionDAG &DAG) {
20214 assert(Subtarget->hasAVX512() &&
20215 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20217 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20219 MVT VT = Op.getSimpleValueType();
20220 SDValue Index = N->getIndex();
20221 SDValue Mask = N->getMask();
20222 SDValue Src0 = N->getValue();
20223 MVT IndexVT = Index.getSimpleValueType();
20224 MVT MaskVT = Mask.getSimpleValueType();
20226 unsigned NumElts = VT.getVectorNumElements();
20227 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20229 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20230 !Index.getSimpleValueType().is512BitVector()) {
20231 // AVX512F supports only 512-bit vectors. Or data or index should
20232 // be 512 bit wide. If now the both index and data are 256-bit, but
20233 // the vector contains 8 elements, we just sign-extend the index
20234 if (NumElts == 8) {
20235 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20236 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
20237 N->getOperand(3), Index };
20238 DAG.UpdateNodeOperands(N, Ops);
20242 // Minimal number of elements in Gather
20245 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20246 Index = ExtendToType(Index, NewIndexVT, DAG);
20247 if (IndexVT.getScalarType() == MVT::i32)
20248 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20251 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20252 // At this point we have promoted mask operand
20253 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20254 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20255 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20256 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20258 // The pass-thru value
20259 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20260 Src0 = ExtendToType(Src0, NewVT, DAG);
20262 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20263 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20264 N->getMemoryVT(), dl, Ops,
20265 N->getMemOperand());
20266 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20267 NewGather.getValue(0),
20268 DAG.getIntPtrConstant(0, dl));
20269 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20270 return DAG.getMergeValues(RetOps, dl);
20275 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20276 SelectionDAG &DAG) const {
20277 // TODO: Eventually, the lowering of these nodes should be informed by or
20278 // deferred to the GC strategy for the function in which they appear. For
20279 // now, however, they must be lowered to something. Since they are logically
20280 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20281 // require special handling for these nodes), lower them as literal NOOPs for
20283 SmallVector<SDValue, 2> Ops;
20285 Ops.push_back(Op.getOperand(0));
20286 if (Op->getGluedNode())
20287 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20290 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20291 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20296 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20297 SelectionDAG &DAG) const {
20298 // TODO: Eventually, the lowering of these nodes should be informed by or
20299 // deferred to the GC strategy for the function in which they appear. For
20300 // now, however, they must be lowered to something. Since they are logically
20301 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20302 // require special handling for these nodes), lower them as literal NOOPs for
20304 SmallVector<SDValue, 2> Ops;
20306 Ops.push_back(Op.getOperand(0));
20307 if (Op->getGluedNode())
20308 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20311 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20312 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20317 /// LowerOperation - Provide custom lowering hooks for some operations.
20319 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20320 switch (Op.getOpcode()) {
20321 default: llvm_unreachable("Should not custom lower this!");
20322 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20323 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20324 return LowerCMP_SWAP(Op, Subtarget, DAG);
20325 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
20326 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
20327 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
20328 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
20329 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20330 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
20331 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
20332 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20333 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
20334 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20335 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20336 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
20337 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
20338 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
20339 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
20340 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
20341 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
20342 case ISD::SHL_PARTS:
20343 case ISD::SRA_PARTS:
20344 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
20345 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
20346 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
20347 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
20348 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
20349 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20350 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
20351 case ISD::SIGN_EXTEND_VECTOR_INREG:
20352 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20353 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
20354 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
20355 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
20356 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
20358 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
20359 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
20360 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
20361 case ISD::SETCC: return LowerSETCC(Op, DAG);
20362 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
20363 case ISD::SELECT: return LowerSELECT(Op, DAG);
20364 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
20365 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
20366 case ISD::VASTART: return LowerVASTART(Op, DAG);
20367 case ISD::VAARG: return LowerVAARG(Op, DAG);
20368 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
20369 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20370 case ISD::INTRINSIC_VOID:
20371 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20372 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
20373 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
20374 case ISD::FRAME_TO_ARGS_OFFSET:
20375 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20376 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20377 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
20378 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
20379 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
20380 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
20381 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
20382 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
20383 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
20384 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20386 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
20387 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20388 case ISD::UMUL_LOHI:
20389 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20390 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20393 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20399 case ISD::UMULO: return LowerXALUO(Op, DAG);
20400 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20401 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20405 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20406 case ISD::ADD: return LowerADD(Op, DAG);
20407 case ISD::SUB: return LowerSUB(Op, DAG);
20411 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20412 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20413 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20414 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20415 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20416 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20417 case ISD::GC_TRANSITION_START:
20418 return LowerGC_TRANSITION_START(Op, DAG);
20419 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20423 /// ReplaceNodeResults - Replace a node with an illegal result type
20424 /// with a new node built out of custom code.
20425 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20426 SmallVectorImpl<SDValue>&Results,
20427 SelectionDAG &DAG) const {
20429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20430 switch (N->getOpcode()) {
20432 llvm_unreachable("Do not know how to custom type legalize this operation!");
20433 case X86ISD::AVG: {
20434 // Legalize types for X86ISD::AVG by expanding vectors.
20435 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20437 auto InVT = N->getValueType(0);
20438 auto InVTSize = InVT.getSizeInBits();
20439 const unsigned RegSize =
20440 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20441 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20442 "512-bit vector requires AVX512");
20443 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20444 "256-bit vector requires AVX2");
20446 auto ElemVT = InVT.getVectorElementType();
20447 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20448 RegSize / ElemVT.getSizeInBits());
20449 assert(RegSize % InVT.getSizeInBits() == 0);
20450 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20452 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20453 Ops[0] = N->getOperand(0);
20454 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20455 Ops[0] = N->getOperand(1);
20456 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20458 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20459 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20460 DAG.getIntPtrConstant(0, dl)));
20463 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20464 case X86ISD::FMINC:
20466 case X86ISD::FMAXC:
20467 case X86ISD::FMAX: {
20468 EVT VT = N->getValueType(0);
20469 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20470 SDValue UNDEF = DAG.getUNDEF(VT);
20471 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20472 N->getOperand(0), UNDEF);
20473 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20474 N->getOperand(1), UNDEF);
20475 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20478 case ISD::SIGN_EXTEND_INREG:
20483 // We don't want to expand or promote these.
20490 case ISD::UDIVREM: {
20491 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20492 Results.push_back(V);
20495 case ISD::FP_TO_SINT:
20496 case ISD::FP_TO_UINT: {
20497 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20499 std::pair<SDValue,SDValue> Vals =
20500 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20501 SDValue FIST = Vals.first, StackSlot = Vals.second;
20502 if (FIST.getNode()) {
20503 EVT VT = N->getValueType(0);
20504 // Return a load from the stack slot.
20505 if (StackSlot.getNode())
20506 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20507 MachinePointerInfo(),
20508 false, false, false, 0));
20510 Results.push_back(FIST);
20514 case ISD::UINT_TO_FP: {
20515 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20516 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20517 N->getValueType(0) != MVT::v2f32)
20519 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20521 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20523 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20524 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20525 DAG.getBitcast(MVT::v2i64, VBias));
20526 Or = DAG.getBitcast(MVT::v2f64, Or);
20527 // TODO: Are there any fast-math-flags to propagate here?
20528 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20529 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20532 case ISD::FP_ROUND: {
20533 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20535 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20536 Results.push_back(V);
20539 case ISD::FP_EXTEND: {
20540 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20541 // No other ValueType for FP_EXTEND should reach this point.
20542 assert(N->getValueType(0) == MVT::v2f32 &&
20543 "Do not know how to legalize this Node");
20546 case ISD::INTRINSIC_W_CHAIN: {
20547 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20549 default : llvm_unreachable("Do not know how to custom type "
20550 "legalize this intrinsic operation!");
20551 case Intrinsic::x86_rdtsc:
20552 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20554 case Intrinsic::x86_rdtscp:
20555 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20557 case Intrinsic::x86_rdpmc:
20558 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20561 case ISD::INTRINSIC_WO_CHAIN: {
20562 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20563 Results.push_back(V);
20566 case ISD::READCYCLECOUNTER: {
20567 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20570 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20571 EVT T = N->getValueType(0);
20572 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20573 bool Regs64bit = T == MVT::i128;
20574 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20575 SDValue cpInL, cpInH;
20576 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20577 DAG.getConstant(0, dl, HalfT));
20578 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20579 DAG.getConstant(1, dl, HalfT));
20580 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20581 Regs64bit ? X86::RAX : X86::EAX,
20583 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20584 Regs64bit ? X86::RDX : X86::EDX,
20585 cpInH, cpInL.getValue(1));
20586 SDValue swapInL, swapInH;
20587 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20588 DAG.getConstant(0, dl, HalfT));
20589 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20590 DAG.getConstant(1, dl, HalfT));
20591 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20592 Regs64bit ? X86::RBX : X86::EBX,
20593 swapInL, cpInH.getValue(1));
20594 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20595 Regs64bit ? X86::RCX : X86::ECX,
20596 swapInH, swapInL.getValue(1));
20597 SDValue Ops[] = { swapInH.getValue(0),
20599 swapInH.getValue(1) };
20600 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20601 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20602 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20603 X86ISD::LCMPXCHG8_DAG;
20604 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20605 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20606 Regs64bit ? X86::RAX : X86::EAX,
20607 HalfT, Result.getValue(1));
20608 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20609 Regs64bit ? X86::RDX : X86::EDX,
20610 HalfT, cpOutL.getValue(2));
20611 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20613 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20614 MVT::i32, cpOutH.getValue(2));
20616 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20617 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20618 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20620 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20621 Results.push_back(Success);
20622 Results.push_back(EFLAGS.getValue(1));
20625 case ISD::ATOMIC_SWAP:
20626 case ISD::ATOMIC_LOAD_ADD:
20627 case ISD::ATOMIC_LOAD_SUB:
20628 case ISD::ATOMIC_LOAD_AND:
20629 case ISD::ATOMIC_LOAD_OR:
20630 case ISD::ATOMIC_LOAD_XOR:
20631 case ISD::ATOMIC_LOAD_NAND:
20632 case ISD::ATOMIC_LOAD_MIN:
20633 case ISD::ATOMIC_LOAD_MAX:
20634 case ISD::ATOMIC_LOAD_UMIN:
20635 case ISD::ATOMIC_LOAD_UMAX:
20636 case ISD::ATOMIC_LOAD: {
20637 // Delegate to generic TypeLegalization. Situations we can really handle
20638 // should have already been dealt with by AtomicExpandPass.cpp.
20641 case ISD::BITCAST: {
20642 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20643 EVT DstVT = N->getValueType(0);
20644 EVT SrcVT = N->getOperand(0)->getValueType(0);
20646 if (SrcVT != MVT::f64 ||
20647 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20650 unsigned NumElts = DstVT.getVectorNumElements();
20651 EVT SVT = DstVT.getVectorElementType();
20652 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20653 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20654 MVT::v2f64, N->getOperand(0));
20655 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20657 if (ExperimentalVectorWideningLegalization) {
20658 // If we are legalizing vectors by widening, we already have the desired
20659 // legal vector type, just return it.
20660 Results.push_back(ToVecInt);
20664 SmallVector<SDValue, 8> Elts;
20665 for (unsigned i = 0, e = NumElts; i != e; ++i)
20666 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20667 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20669 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20674 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20675 switch ((X86ISD::NodeType)Opcode) {
20676 case X86ISD::FIRST_NUMBER: break;
20677 case X86ISD::BSF: return "X86ISD::BSF";
20678 case X86ISD::BSR: return "X86ISD::BSR";
20679 case X86ISD::SHLD: return "X86ISD::SHLD";
20680 case X86ISD::SHRD: return "X86ISD::SHRD";
20681 case X86ISD::FAND: return "X86ISD::FAND";
20682 case X86ISD::FANDN: return "X86ISD::FANDN";
20683 case X86ISD::FOR: return "X86ISD::FOR";
20684 case X86ISD::FXOR: return "X86ISD::FXOR";
20685 case X86ISD::FILD: return "X86ISD::FILD";
20686 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20687 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20688 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20689 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20690 case X86ISD::FLD: return "X86ISD::FLD";
20691 case X86ISD::FST: return "X86ISD::FST";
20692 case X86ISD::CALL: return "X86ISD::CALL";
20693 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20694 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20695 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20696 case X86ISD::BT: return "X86ISD::BT";
20697 case X86ISD::CMP: return "X86ISD::CMP";
20698 case X86ISD::COMI: return "X86ISD::COMI";
20699 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20700 case X86ISD::CMPM: return "X86ISD::CMPM";
20701 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20702 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20703 case X86ISD::SETCC: return "X86ISD::SETCC";
20704 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20705 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20706 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20707 case X86ISD::CMOV: return "X86ISD::CMOV";
20708 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20709 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20710 case X86ISD::IRET: return "X86ISD::IRET";
20711 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20712 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20713 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20714 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20715 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20716 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20717 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20718 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20719 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20720 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20721 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20722 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20723 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20724 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20725 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20726 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20727 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20728 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20729 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20730 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20731 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20732 case X86ISD::HADD: return "X86ISD::HADD";
20733 case X86ISD::HSUB: return "X86ISD::HSUB";
20734 case X86ISD::FHADD: return "X86ISD::FHADD";
20735 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20736 case X86ISD::ABS: return "X86ISD::ABS";
20737 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20738 case X86ISD::FMAX: return "X86ISD::FMAX";
20739 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20740 case X86ISD::FMIN: return "X86ISD::FMIN";
20741 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20742 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20743 case X86ISD::FMINC: return "X86ISD::FMINC";
20744 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20745 case X86ISD::FRCP: return "X86ISD::FRCP";
20746 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20747 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20748 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20749 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20750 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20751 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20752 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20753 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20754 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20755 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20756 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20757 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20758 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20759 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20760 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20761 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20762 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20763 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20764 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20765 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20766 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20767 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20768 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20769 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20770 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20771 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20772 case X86ISD::CVT2MASK: return "X86ISD::CVT2MASK";
20773 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20774 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20775 case X86ISD::VSHL: return "X86ISD::VSHL";
20776 case X86ISD::VSRL: return "X86ISD::VSRL";
20777 case X86ISD::VSRA: return "X86ISD::VSRA";
20778 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20779 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20780 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20781 case X86ISD::VROTLI: return "X86ISD::VROTLI";
20782 case X86ISD::VROTRI: return "X86ISD::VROTRI";
20783 case X86ISD::CMPP: return "X86ISD::CMPP";
20784 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20785 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20786 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20787 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20788 case X86ISD::ADD: return "X86ISD::ADD";
20789 case X86ISD::SUB: return "X86ISD::SUB";
20790 case X86ISD::ADC: return "X86ISD::ADC";
20791 case X86ISD::SBB: return "X86ISD::SBB";
20792 case X86ISD::SMUL: return "X86ISD::SMUL";
20793 case X86ISD::UMUL: return "X86ISD::UMUL";
20794 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20795 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20796 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20797 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20798 case X86ISD::INC: return "X86ISD::INC";
20799 case X86ISD::DEC: return "X86ISD::DEC";
20800 case X86ISD::OR: return "X86ISD::OR";
20801 case X86ISD::XOR: return "X86ISD::XOR";
20802 case X86ISD::AND: return "X86ISD::AND";
20803 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20804 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20805 case X86ISD::PTEST: return "X86ISD::PTEST";
20806 case X86ISD::TESTP: return "X86ISD::TESTP";
20807 case X86ISD::TESTM: return "X86ISD::TESTM";
20808 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20809 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20810 case X86ISD::KTEST: return "X86ISD::KTEST";
20811 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20812 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20813 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20814 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20815 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20816 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20817 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20818 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20819 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20820 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20821 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20822 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20823 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20824 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20825 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20826 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20827 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20828 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20829 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20830 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20831 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20832 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20833 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20834 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20835 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20836 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20837 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20838 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20839 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20840 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20841 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20842 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20843 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20844 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20845 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20846 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20847 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20848 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20849 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20850 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20851 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20852 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20853 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20854 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20855 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20856 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20857 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20858 case X86ISD::SAHF: return "X86ISD::SAHF";
20859 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20860 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20861 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20862 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20863 case X86ISD::VPROT: return "X86ISD::VPROT";
20864 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20865 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20866 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20867 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20868 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20869 case X86ISD::FMADD: return "X86ISD::FMADD";
20870 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20871 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20872 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20873 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20874 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20875 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20876 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20877 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20878 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20879 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20880 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20881 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20882 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20883 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20884 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20885 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20886 case X86ISD::XTEST: return "X86ISD::XTEST";
20887 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20888 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20889 case X86ISD::SELECT: return "X86ISD::SELECT";
20890 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20891 case X86ISD::RCP28: return "X86ISD::RCP28";
20892 case X86ISD::EXP2: return "X86ISD::EXP2";
20893 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20894 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20895 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20896 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20897 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20898 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20899 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20900 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20901 case X86ISD::ADDS: return "X86ISD::ADDS";
20902 case X86ISD::SUBS: return "X86ISD::SUBS";
20903 case X86ISD::AVG: return "X86ISD::AVG";
20904 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20905 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20906 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20907 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20908 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20909 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20910 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20915 // isLegalAddressingMode - Return true if the addressing mode represented
20916 // by AM is legal for this target, for a load/store of the specified type.
20917 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20918 const AddrMode &AM, Type *Ty,
20919 unsigned AS) const {
20920 // X86 supports extremely general addressing modes.
20921 CodeModel::Model M = getTargetMachine().getCodeModel();
20922 Reloc::Model R = getTargetMachine().getRelocationModel();
20924 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20925 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20930 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20932 // If a reference to this global requires an extra load, we can't fold it.
20933 if (isGlobalStubReference(GVFlags))
20936 // If BaseGV requires a register for the PIC base, we cannot also have a
20937 // BaseReg specified.
20938 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20941 // If lower 4G is not available, then we must use rip-relative addressing.
20942 if ((M != CodeModel::Small || R != Reloc::Static) &&
20943 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20947 switch (AM.Scale) {
20953 // These scales always work.
20958 // These scales are formed with basereg+scalereg. Only accept if there is
20963 default: // Other stuff never works.
20970 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20971 unsigned Bits = Ty->getScalarSizeInBits();
20973 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20974 // particularly cheaper than those without.
20978 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20979 // variable shifts just as cheap as scalar ones.
20980 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20983 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20984 // fully general vector.
20988 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20989 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20991 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20992 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20993 return NumBits1 > NumBits2;
20996 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20997 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21000 if (!isTypeLegal(EVT::getEVT(Ty1)))
21003 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
21005 // Assuming the caller doesn't have a zeroext or signext return parameter,
21006 // truncation all the way down to i1 is valid.
21010 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
21011 return isInt<32>(Imm);
21014 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
21015 // Can also use sub to handle negated immediates.
21016 return isInt<32>(Imm);
21019 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
21020 if (!VT1.isInteger() || !VT2.isInteger())
21022 unsigned NumBits1 = VT1.getSizeInBits();
21023 unsigned NumBits2 = VT2.getSizeInBits();
21024 return NumBits1 > NumBits2;
21027 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
21028 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21029 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
21032 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21033 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21034 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21037 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21038 EVT VT1 = Val.getValueType();
21039 if (isZExtFree(VT1, VT2))
21042 if (Val.getOpcode() != ISD::LOAD)
21045 if (!VT1.isSimple() || !VT1.isInteger() ||
21046 !VT2.isSimple() || !VT2.isInteger())
21049 switch (VT1.getSimpleVT().SimpleTy) {
21054 // X86 has 8, 16, and 32-bit zero-extending loads.
21061 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21064 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21065 if (!Subtarget->hasAnyFMA())
21068 VT = VT.getScalarType();
21070 if (!VT.isSimple())
21073 switch (VT.getSimpleVT().SimpleTy) {
21084 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21085 // i16 instructions are longer (0x66 prefix) and potentially slower.
21086 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21089 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21090 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21091 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21092 /// are assumed to be legal.
21094 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21096 if (!VT.isSimple())
21099 // Not for i1 vectors
21100 if (VT.getSimpleVT().getScalarType() == MVT::i1)
21103 // Very little shuffling can be done for 64-bit vectors right now.
21104 if (VT.getSimpleVT().getSizeInBits() == 64)
21107 // We only care that the types being shuffled are legal. The lowering can
21108 // handle any possible shuffle mask that results.
21109 return isTypeLegal(VT.getSimpleVT());
21113 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21115 // Just delegate to the generic legality, clear masks aren't special.
21116 return isShuffleMaskLegal(Mask, VT);
21119 //===----------------------------------------------------------------------===//
21120 // X86 Scheduler Hooks
21121 //===----------------------------------------------------------------------===//
21123 /// Utility function to emit xbegin specifying the start of an RTM region.
21124 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21125 const TargetInstrInfo *TII) {
21126 DebugLoc DL = MI->getDebugLoc();
21128 const BasicBlock *BB = MBB->getBasicBlock();
21129 MachineFunction::iterator I = ++MBB->getIterator();
21131 // For the v = xbegin(), we generate
21142 MachineBasicBlock *thisMBB = MBB;
21143 MachineFunction *MF = MBB->getParent();
21144 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21145 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21146 MF->insert(I, mainMBB);
21147 MF->insert(I, sinkMBB);
21149 // Transfer the remainder of BB and its successor edges to sinkMBB.
21150 sinkMBB->splice(sinkMBB->begin(), MBB,
21151 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21152 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21156 // # fallthrough to mainMBB
21157 // # abortion to sinkMBB
21158 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21159 thisMBB->addSuccessor(mainMBB);
21160 thisMBB->addSuccessor(sinkMBB);
21164 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21165 mainMBB->addSuccessor(sinkMBB);
21168 // EAX is live into the sinkMBB
21169 sinkMBB->addLiveIn(X86::EAX);
21170 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21171 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21174 MI->eraseFromParent();
21178 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21179 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21180 // in the .td file.
21181 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21182 const TargetInstrInfo *TII) {
21184 switch (MI->getOpcode()) {
21185 default: llvm_unreachable("illegal opcode!");
21186 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
21187 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21188 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
21189 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21190 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
21191 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21192 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
21193 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21196 DebugLoc dl = MI->getDebugLoc();
21197 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21199 unsigned NumArgs = MI->getNumOperands();
21200 for (unsigned i = 1; i < NumArgs; ++i) {
21201 MachineOperand &Op = MI->getOperand(i);
21202 if (!(Op.isReg() && Op.isImplicit()))
21203 MIB.addOperand(Op);
21205 if (MI->hasOneMemOperand())
21206 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21208 BuildMI(*BB, MI, dl,
21209 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21210 .addReg(X86::XMM0);
21212 MI->eraseFromParent();
21216 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21217 // defs in an instruction pattern
21218 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21219 const TargetInstrInfo *TII) {
21221 switch (MI->getOpcode()) {
21222 default: llvm_unreachable("illegal opcode!");
21223 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
21224 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21225 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
21226 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21227 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
21228 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21229 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
21230 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21233 DebugLoc dl = MI->getDebugLoc();
21234 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21236 unsigned NumArgs = MI->getNumOperands(); // remove the results
21237 for (unsigned i = 1; i < NumArgs; ++i) {
21238 MachineOperand &Op = MI->getOperand(i);
21239 if (!(Op.isReg() && Op.isImplicit()))
21240 MIB.addOperand(Op);
21242 if (MI->hasOneMemOperand())
21243 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21245 BuildMI(*BB, MI, dl,
21246 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21249 MI->eraseFromParent();
21253 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21254 const X86Subtarget *Subtarget) {
21255 DebugLoc dl = MI->getDebugLoc();
21256 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21258 // insert input VAL into EAX
21259 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21260 .addReg(MI->getOperand(0).getReg());
21261 // insert zero to ECX
21262 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21265 // insert zero to EDX
21266 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21269 // insert WRPKRU instruction
21270 BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21272 MI->eraseFromParent(); // The pseudo is gone now.
21276 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21277 const X86Subtarget *Subtarget) {
21278 DebugLoc dl = MI->getDebugLoc();
21279 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21281 // insert zero to ECX
21282 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21285 // insert RDPKRU instruction
21286 BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21287 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21290 MI->eraseFromParent(); // The pseudo is gone now.
21294 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21295 const X86Subtarget *Subtarget) {
21296 DebugLoc dl = MI->getDebugLoc();
21297 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21298 // Address into RAX/EAX, other two args into ECX, EDX.
21299 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21300 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21301 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21302 for (int i = 0; i < X86::AddrNumOperands; ++i)
21303 MIB.addOperand(MI->getOperand(i));
21305 unsigned ValOps = X86::AddrNumOperands;
21306 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21307 .addReg(MI->getOperand(ValOps).getReg());
21308 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21309 .addReg(MI->getOperand(ValOps+1).getReg());
21311 // The instruction doesn't actually take any operands though.
21312 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21314 MI->eraseFromParent(); // The pseudo is gone now.
21318 MachineBasicBlock *
21319 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21320 MachineBasicBlock *MBB) const {
21321 // Emit va_arg instruction on X86-64.
21323 // Operands to this pseudo-instruction:
21324 // 0 ) Output : destination address (reg)
21325 // 1-5) Input : va_list address (addr, i64mem)
21326 // 6 ) ArgSize : Size (in bytes) of vararg type
21327 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21328 // 8 ) Align : Alignment of type
21329 // 9 ) EFLAGS (implicit-def)
21331 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21332 static_assert(X86::AddrNumOperands == 5,
21333 "VAARG_64 assumes 5 address operands");
21335 unsigned DestReg = MI->getOperand(0).getReg();
21336 MachineOperand &Base = MI->getOperand(1);
21337 MachineOperand &Scale = MI->getOperand(2);
21338 MachineOperand &Index = MI->getOperand(3);
21339 MachineOperand &Disp = MI->getOperand(4);
21340 MachineOperand &Segment = MI->getOperand(5);
21341 unsigned ArgSize = MI->getOperand(6).getImm();
21342 unsigned ArgMode = MI->getOperand(7).getImm();
21343 unsigned Align = MI->getOperand(8).getImm();
21345 // Memory Reference
21346 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21347 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21348 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21350 // Machine Information
21351 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21352 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21353 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21354 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21355 DebugLoc DL = MI->getDebugLoc();
21357 // struct va_list {
21360 // i64 overflow_area (address)
21361 // i64 reg_save_area (address)
21363 // sizeof(va_list) = 24
21364 // alignment(va_list) = 8
21366 unsigned TotalNumIntRegs = 6;
21367 unsigned TotalNumXMMRegs = 8;
21368 bool UseGPOffset = (ArgMode == 1);
21369 bool UseFPOffset = (ArgMode == 2);
21370 unsigned MaxOffset = TotalNumIntRegs * 8 +
21371 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21373 /* Align ArgSize to a multiple of 8 */
21374 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21375 bool NeedsAlign = (Align > 8);
21377 MachineBasicBlock *thisMBB = MBB;
21378 MachineBasicBlock *overflowMBB;
21379 MachineBasicBlock *offsetMBB;
21380 MachineBasicBlock *endMBB;
21382 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
21383 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
21384 unsigned OffsetReg = 0;
21386 if (!UseGPOffset && !UseFPOffset) {
21387 // If we only pull from the overflow region, we don't create a branch.
21388 // We don't need to alter control flow.
21389 OffsetDestReg = 0; // unused
21390 OverflowDestReg = DestReg;
21392 offsetMBB = nullptr;
21393 overflowMBB = thisMBB;
21396 // First emit code to check if gp_offset (or fp_offset) is below the bound.
21397 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21398 // If not, pull from overflow_area. (branch to overflowMBB)
21403 // offsetMBB overflowMBB
21408 // Registers for the PHI in endMBB
21409 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21410 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21412 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21413 MachineFunction *MF = MBB->getParent();
21414 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21415 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21416 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21418 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21420 // Insert the new basic blocks
21421 MF->insert(MBBIter, offsetMBB);
21422 MF->insert(MBBIter, overflowMBB);
21423 MF->insert(MBBIter, endMBB);
21425 // Transfer the remainder of MBB and its successor edges to endMBB.
21426 endMBB->splice(endMBB->begin(), thisMBB,
21427 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21428 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21430 // Make offsetMBB and overflowMBB successors of thisMBB
21431 thisMBB->addSuccessor(offsetMBB);
21432 thisMBB->addSuccessor(overflowMBB);
21434 // endMBB is a successor of both offsetMBB and overflowMBB
21435 offsetMBB->addSuccessor(endMBB);
21436 overflowMBB->addSuccessor(endMBB);
21438 // Load the offset value into a register
21439 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21440 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21444 .addDisp(Disp, UseFPOffset ? 4 : 0)
21445 .addOperand(Segment)
21446 .setMemRefs(MMOBegin, MMOEnd);
21448 // Check if there is enough room left to pull this argument.
21449 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21451 .addImm(MaxOffset + 8 - ArgSizeA8);
21453 // Branch to "overflowMBB" if offset >= max
21454 // Fall through to "offsetMBB" otherwise
21455 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21456 .addMBB(overflowMBB);
21459 // In offsetMBB, emit code to use the reg_save_area.
21461 assert(OffsetReg != 0);
21463 // Read the reg_save_area address.
21464 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21465 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21470 .addOperand(Segment)
21471 .setMemRefs(MMOBegin, MMOEnd);
21473 // Zero-extend the offset
21474 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21475 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21478 .addImm(X86::sub_32bit);
21480 // Add the offset to the reg_save_area to get the final address.
21481 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21482 .addReg(OffsetReg64)
21483 .addReg(RegSaveReg);
21485 // Compute the offset for the next argument
21486 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21487 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21489 .addImm(UseFPOffset ? 16 : 8);
21491 // Store it back into the va_list.
21492 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21496 .addDisp(Disp, UseFPOffset ? 4 : 0)
21497 .addOperand(Segment)
21498 .addReg(NextOffsetReg)
21499 .setMemRefs(MMOBegin, MMOEnd);
21502 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21507 // Emit code to use overflow area
21510 // Load the overflow_area address into a register.
21511 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21512 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21517 .addOperand(Segment)
21518 .setMemRefs(MMOBegin, MMOEnd);
21520 // If we need to align it, do so. Otherwise, just copy the address
21521 // to OverflowDestReg.
21523 // Align the overflow address
21524 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21525 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21527 // aligned_addr = (addr + (align-1)) & ~(align-1)
21528 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21529 .addReg(OverflowAddrReg)
21532 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21534 .addImm(~(uint64_t)(Align-1));
21536 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21537 .addReg(OverflowAddrReg);
21540 // Compute the next overflow address after this argument.
21541 // (the overflow address should be kept 8-byte aligned)
21542 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21543 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21544 .addReg(OverflowDestReg)
21545 .addImm(ArgSizeA8);
21547 // Store the new overflow address.
21548 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21553 .addOperand(Segment)
21554 .addReg(NextAddrReg)
21555 .setMemRefs(MMOBegin, MMOEnd);
21557 // If we branched, emit the PHI to the front of endMBB.
21559 BuildMI(*endMBB, endMBB->begin(), DL,
21560 TII->get(X86::PHI), DestReg)
21561 .addReg(OffsetDestReg).addMBB(offsetMBB)
21562 .addReg(OverflowDestReg).addMBB(overflowMBB);
21565 // Erase the pseudo instruction
21566 MI->eraseFromParent();
21571 MachineBasicBlock *
21572 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21574 MachineBasicBlock *MBB) const {
21575 // Emit code to save XMM registers to the stack. The ABI says that the
21576 // number of registers to save is given in %al, so it's theoretically
21577 // possible to do an indirect jump trick to avoid saving all of them,
21578 // however this code takes a simpler approach and just executes all
21579 // of the stores if %al is non-zero. It's less code, and it's probably
21580 // easier on the hardware branch predictor, and stores aren't all that
21581 // expensive anyway.
21583 // Create the new basic blocks. One block contains all the XMM stores,
21584 // and one block is the final destination regardless of whether any
21585 // stores were performed.
21586 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21587 MachineFunction *F = MBB->getParent();
21588 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21589 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21590 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21591 F->insert(MBBIter, XMMSaveMBB);
21592 F->insert(MBBIter, EndMBB);
21594 // Transfer the remainder of MBB and its successor edges to EndMBB.
21595 EndMBB->splice(EndMBB->begin(), MBB,
21596 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21597 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21599 // The original block will now fall through to the XMM save block.
21600 MBB->addSuccessor(XMMSaveMBB);
21601 // The XMMSaveMBB will fall through to the end block.
21602 XMMSaveMBB->addSuccessor(EndMBB);
21604 // Now add the instructions.
21605 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21606 DebugLoc DL = MI->getDebugLoc();
21608 unsigned CountReg = MI->getOperand(0).getReg();
21609 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21610 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21612 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21613 // If %al is 0, branch around the XMM save block.
21614 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21615 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21616 MBB->addSuccessor(EndMBB);
21619 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21620 // that was just emitted, but clearly shouldn't be "saved".
21621 assert((MI->getNumOperands() <= 3 ||
21622 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21623 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21624 && "Expected last argument to be EFLAGS");
21625 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21626 // In the XMM save block, save all the XMM argument registers.
21627 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21628 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21629 MachineMemOperand *MMO = F->getMachineMemOperand(
21630 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21631 MachineMemOperand::MOStore,
21632 /*Size=*/16, /*Align=*/16);
21633 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21634 .addFrameIndex(RegSaveFrameIndex)
21635 .addImm(/*Scale=*/1)
21636 .addReg(/*IndexReg=*/0)
21637 .addImm(/*Disp=*/Offset)
21638 .addReg(/*Segment=*/0)
21639 .addReg(MI->getOperand(i).getReg())
21640 .addMemOperand(MMO);
21643 MI->eraseFromParent(); // The pseudo instruction is gone now.
21648 // The EFLAGS operand of SelectItr might be missing a kill marker
21649 // because there were multiple uses of EFLAGS, and ISel didn't know
21650 // which to mark. Figure out whether SelectItr should have had a
21651 // kill marker, and set it if it should. Returns the correct kill
21653 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21654 MachineBasicBlock* BB,
21655 const TargetRegisterInfo* TRI) {
21656 // Scan forward through BB for a use/def of EFLAGS.
21657 MachineBasicBlock::iterator miI(std::next(SelectItr));
21658 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21659 const MachineInstr& mi = *miI;
21660 if (mi.readsRegister(X86::EFLAGS))
21662 if (mi.definesRegister(X86::EFLAGS))
21663 break; // Should have kill-flag - update below.
21666 // If we hit the end of the block, check whether EFLAGS is live into a
21668 if (miI == BB->end()) {
21669 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21670 sEnd = BB->succ_end();
21671 sItr != sEnd; ++sItr) {
21672 MachineBasicBlock* succ = *sItr;
21673 if (succ->isLiveIn(X86::EFLAGS))
21678 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21679 // out. SelectMI should have a kill flag on EFLAGS.
21680 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21684 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21685 // together with other CMOV pseudo-opcodes into a single basic-block with
21686 // conditional jump around it.
21687 static bool isCMOVPseudo(MachineInstr *MI) {
21688 switch (MI->getOpcode()) {
21689 case X86::CMOV_FR32:
21690 case X86::CMOV_FR64:
21691 case X86::CMOV_GR8:
21692 case X86::CMOV_GR16:
21693 case X86::CMOV_GR32:
21694 case X86::CMOV_RFP32:
21695 case X86::CMOV_RFP64:
21696 case X86::CMOV_RFP80:
21697 case X86::CMOV_V2F64:
21698 case X86::CMOV_V2I64:
21699 case X86::CMOV_V4F32:
21700 case X86::CMOV_V4F64:
21701 case X86::CMOV_V4I64:
21702 case X86::CMOV_V16F32:
21703 case X86::CMOV_V8F32:
21704 case X86::CMOV_V8F64:
21705 case X86::CMOV_V8I64:
21706 case X86::CMOV_V8I1:
21707 case X86::CMOV_V16I1:
21708 case X86::CMOV_V32I1:
21709 case X86::CMOV_V64I1:
21717 MachineBasicBlock *
21718 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21719 MachineBasicBlock *BB) const {
21720 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21721 DebugLoc DL = MI->getDebugLoc();
21723 // To "insert" a SELECT_CC instruction, we actually have to insert the
21724 // diamond control-flow pattern. The incoming instruction knows the
21725 // destination vreg to set, the condition code register to branch on, the
21726 // true/false values to select between, and a branch opcode to use.
21727 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21728 MachineFunction::iterator It = ++BB->getIterator();
21733 // cmpTY ccX, r1, r2
21735 // fallthrough --> copy0MBB
21736 MachineBasicBlock *thisMBB = BB;
21737 MachineFunction *F = BB->getParent();
21739 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21740 // as described above, by inserting a BB, and then making a PHI at the join
21741 // point to select the true and false operands of the CMOV in the PHI.
21743 // The code also handles two different cases of multiple CMOV opcodes
21747 // In this case, there are multiple CMOVs in a row, all which are based on
21748 // the same condition setting (or the exact opposite condition setting).
21749 // In this case we can lower all the CMOVs using a single inserted BB, and
21750 // then make a number of PHIs at the join point to model the CMOVs. The only
21751 // trickiness here, is that in a case like:
21753 // t2 = CMOV cond1 t1, f1
21754 // t3 = CMOV cond1 t2, f2
21756 // when rewriting this into PHIs, we have to perform some renaming on the
21757 // temps since you cannot have a PHI operand refer to a PHI result earlier
21758 // in the same block. The "simple" but wrong lowering would be:
21760 // t2 = PHI t1(BB1), f1(BB2)
21761 // t3 = PHI t2(BB1), f2(BB2)
21763 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21764 // renaming is to note that on the path through BB1, t2 is really just a
21765 // copy of t1, and do that renaming, properly generating:
21767 // t2 = PHI t1(BB1), f1(BB2)
21768 // t3 = PHI t1(BB1), f2(BB2)
21770 // Case 2, we lower cascaded CMOVs such as
21772 // (CMOV (CMOV F, T, cc1), T, cc2)
21774 // to two successives branches. For that, we look for another CMOV as the
21775 // following instruction.
21777 // Without this, we would add a PHI between the two jumps, which ends up
21778 // creating a few copies all around. For instance, for
21780 // (sitofp (zext (fcmp une)))
21782 // we would generate:
21784 // ucomiss %xmm1, %xmm0
21785 // movss <1.0f>, %xmm0
21786 // movaps %xmm0, %xmm1
21788 // xorps %xmm1, %xmm1
21791 // movaps %xmm1, %xmm0
21795 // because this custom-inserter would have generated:
21807 // A: X = ...; Y = ...
21809 // C: Z = PHI [X, A], [Y, B]
21811 // E: PHI [X, C], [Z, D]
21813 // If we lower both CMOVs in a single step, we can instead generate:
21825 // A: X = ...; Y = ...
21827 // E: PHI [X, A], [X, C], [Y, D]
21829 // Which, in our sitofp/fcmp example, gives us something like:
21831 // ucomiss %xmm1, %xmm0
21832 // movss <1.0f>, %xmm0
21835 // xorps %xmm0, %xmm0
21839 MachineInstr *CascadedCMOV = nullptr;
21840 MachineInstr *LastCMOV = MI;
21841 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21842 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21843 MachineBasicBlock::iterator NextMIIt =
21844 std::next(MachineBasicBlock::iterator(MI));
21846 // Check for case 1, where there are multiple CMOVs with the same condition
21847 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21848 // number of jumps the most.
21850 if (isCMOVPseudo(MI)) {
21851 // See if we have a string of CMOVS with the same condition.
21852 while (NextMIIt != BB->end() &&
21853 isCMOVPseudo(NextMIIt) &&
21854 (NextMIIt->getOperand(3).getImm() == CC ||
21855 NextMIIt->getOperand(3).getImm() == OppCC)) {
21856 LastCMOV = &*NextMIIt;
21861 // This checks for case 2, but only do this if we didn't already find
21862 // case 1, as indicated by LastCMOV == MI.
21863 if (LastCMOV == MI &&
21864 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21865 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21866 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg() &&
21867 NextMIIt->getOperand(1).isKill()) {
21868 CascadedCMOV = &*NextMIIt;
21871 MachineBasicBlock *jcc1MBB = nullptr;
21873 // If we have a cascaded CMOV, we lower it to two successive branches to
21874 // the same block. EFLAGS is used by both, so mark it as live in the second.
21875 if (CascadedCMOV) {
21876 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21877 F->insert(It, jcc1MBB);
21878 jcc1MBB->addLiveIn(X86::EFLAGS);
21881 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21882 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21883 F->insert(It, copy0MBB);
21884 F->insert(It, sinkMBB);
21886 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21887 // live into the sink and copy blocks.
21888 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21890 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21891 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21892 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21893 copy0MBB->addLiveIn(X86::EFLAGS);
21894 sinkMBB->addLiveIn(X86::EFLAGS);
21897 // Transfer the remainder of BB and its successor edges to sinkMBB.
21898 sinkMBB->splice(sinkMBB->begin(), BB,
21899 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21900 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21902 // Add the true and fallthrough blocks as its successors.
21903 if (CascadedCMOV) {
21904 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21905 BB->addSuccessor(jcc1MBB);
21907 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21908 // jump to the sinkMBB.
21909 jcc1MBB->addSuccessor(copy0MBB);
21910 jcc1MBB->addSuccessor(sinkMBB);
21912 BB->addSuccessor(copy0MBB);
21915 // The true block target of the first (or only) branch is always sinkMBB.
21916 BB->addSuccessor(sinkMBB);
21918 // Create the conditional branch instruction.
21919 unsigned Opc = X86::GetCondBranchFromCond(CC);
21920 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21922 if (CascadedCMOV) {
21923 unsigned Opc2 = X86::GetCondBranchFromCond(
21924 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21925 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21929 // %FalseValue = ...
21930 // # fallthrough to sinkMBB
21931 copy0MBB->addSuccessor(sinkMBB);
21934 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21936 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21937 MachineBasicBlock::iterator MIItEnd =
21938 std::next(MachineBasicBlock::iterator(LastCMOV));
21939 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21940 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21941 MachineInstrBuilder MIB;
21943 // As we are creating the PHIs, we have to be careful if there is more than
21944 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21945 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21946 // That also means that PHI construction must work forward from earlier to
21947 // later, and that the code must maintain a mapping from earlier PHI's
21948 // destination registers, and the registers that went into the PHI.
21950 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21951 unsigned DestReg = MIIt->getOperand(0).getReg();
21952 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21953 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21955 // If this CMOV we are generating is the opposite condition from
21956 // the jump we generated, then we have to swap the operands for the
21957 // PHI that is going to be generated.
21958 if (MIIt->getOperand(3).getImm() == OppCC)
21959 std::swap(Op1Reg, Op2Reg);
21961 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21962 Op1Reg = RegRewriteTable[Op1Reg].first;
21964 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21965 Op2Reg = RegRewriteTable[Op2Reg].second;
21967 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21968 TII->get(X86::PHI), DestReg)
21969 .addReg(Op1Reg).addMBB(copy0MBB)
21970 .addReg(Op2Reg).addMBB(thisMBB);
21972 // Add this PHI to the rewrite table.
21973 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21976 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21977 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21978 if (CascadedCMOV) {
21979 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21980 // Copy the PHI result to the register defined by the second CMOV.
21981 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21982 DL, TII->get(TargetOpcode::COPY),
21983 CascadedCMOV->getOperand(0).getReg())
21984 .addReg(MI->getOperand(0).getReg());
21985 CascadedCMOV->eraseFromParent();
21988 // Now remove the CMOV(s).
21989 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21990 (MIIt++)->eraseFromParent();
21995 MachineBasicBlock *
21996 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21997 MachineBasicBlock *BB) const {
21998 // Combine the following atomic floating-point modification pattern:
21999 // a.store(reg OP a.load(acquire), release)
22000 // Transform them into:
22001 // OPss (%gpr), %xmm
22002 // movss %xmm, (%gpr)
22003 // Or sd equivalent for 64-bit operations.
22005 switch (MI->getOpcode()) {
22006 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
22007 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
22008 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
22010 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22011 DebugLoc DL = MI->getDebugLoc();
22012 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
22013 MachineOperand MSrc = MI->getOperand(0);
22014 unsigned VSrc = MI->getOperand(5).getReg();
22015 const MachineOperand &Disp = MI->getOperand(3);
22016 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
22017 bool hasDisp = Disp.isGlobal() || Disp.isImm();
22018 if (hasDisp && MSrc.isReg())
22019 MSrc.setIsKill(false);
22020 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
22021 .addOperand(/*Base=*/MSrc)
22022 .addImm(/*Scale=*/1)
22023 .addReg(/*Index=*/0)
22024 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22026 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
22027 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
22029 .addOperand(/*Base=*/MSrc)
22030 .addImm(/*Scale=*/1)
22031 .addReg(/*Index=*/0)
22032 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22033 .addReg(/*Segment=*/0);
22034 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22035 MI->eraseFromParent(); // The pseudo instruction is gone now.
22039 MachineBasicBlock *
22040 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22041 MachineBasicBlock *BB) const {
22042 MachineFunction *MF = BB->getParent();
22043 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22044 DebugLoc DL = MI->getDebugLoc();
22045 const BasicBlock *LLVM_BB = BB->getBasicBlock();
22047 assert(MF->shouldSplitStack());
22049 const bool Is64Bit = Subtarget->is64Bit();
22050 const bool IsLP64 = Subtarget->isTarget64BitLP64();
22052 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22053 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22056 // ... [Till the alloca]
22057 // If stacklet is not large enough, jump to mallocMBB
22060 // Allocate by subtracting from RSP
22061 // Jump to continueMBB
22064 // Allocate by call to runtime
22068 // [rest of original BB]
22071 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22072 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22073 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22075 MachineRegisterInfo &MRI = MF->getRegInfo();
22076 const TargetRegisterClass *AddrRegClass =
22077 getRegClassFor(getPointerTy(MF->getDataLayout()));
22079 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22080 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22081 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22082 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22083 sizeVReg = MI->getOperand(1).getReg(),
22084 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22086 MachineFunction::iterator MBBIter = ++BB->getIterator();
22088 MF->insert(MBBIter, bumpMBB);
22089 MF->insert(MBBIter, mallocMBB);
22090 MF->insert(MBBIter, continueMBB);
22092 continueMBB->splice(continueMBB->begin(), BB,
22093 std::next(MachineBasicBlock::iterator(MI)), BB->end());
22094 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22096 // Add code to the main basic block to check if the stack limit has been hit,
22097 // and if so, jump to mallocMBB otherwise to bumpMBB.
22098 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22099 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22100 .addReg(tmpSPVReg).addReg(sizeVReg);
22101 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22102 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22103 .addReg(SPLimitVReg);
22104 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22106 // bumpMBB simply decreases the stack pointer, since we know the current
22107 // stacklet has enough space.
22108 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22109 .addReg(SPLimitVReg);
22110 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22111 .addReg(SPLimitVReg);
22112 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22114 // Calls into a routine in libgcc to allocate more space from the heap.
22115 const uint32_t *RegMask =
22116 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22118 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22120 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22121 .addExternalSymbol("__morestack_allocate_stack_space")
22122 .addRegMask(RegMask)
22123 .addReg(X86::RDI, RegState::Implicit)
22124 .addReg(X86::RAX, RegState::ImplicitDefine);
22125 } else if (Is64Bit) {
22126 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22128 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22129 .addExternalSymbol("__morestack_allocate_stack_space")
22130 .addRegMask(RegMask)
22131 .addReg(X86::EDI, RegState::Implicit)
22132 .addReg(X86::EAX, RegState::ImplicitDefine);
22134 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22136 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22137 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22138 .addExternalSymbol("__morestack_allocate_stack_space")
22139 .addRegMask(RegMask)
22140 .addReg(X86::EAX, RegState::ImplicitDefine);
22144 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22147 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22148 .addReg(IsLP64 ? X86::RAX : X86::EAX);
22149 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22151 // Set up the CFG correctly.
22152 BB->addSuccessor(bumpMBB);
22153 BB->addSuccessor(mallocMBB);
22154 mallocMBB->addSuccessor(continueMBB);
22155 bumpMBB->addSuccessor(continueMBB);
22157 // Take care of the PHI nodes.
22158 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22159 MI->getOperand(0).getReg())
22160 .addReg(mallocPtrVReg).addMBB(mallocMBB)
22161 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22163 // Delete the original pseudo instruction.
22164 MI->eraseFromParent();
22167 return continueMBB;
22170 MachineBasicBlock *
22171 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22172 MachineBasicBlock *BB) const {
22173 assert(!Subtarget->isTargetMachO());
22174 DebugLoc DL = MI->getDebugLoc();
22175 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22176 *BB->getParent(), *BB, MI, DL, false);
22177 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22178 MI->eraseFromParent(); // The pseudo instruction is gone now.
22182 MachineBasicBlock *
22183 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22184 MachineBasicBlock *BB) const {
22185 MachineFunction *MF = BB->getParent();
22186 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22187 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22188 DebugLoc DL = MI->getDebugLoc();
22190 assert(!isAsynchronousEHPersonality(
22191 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22192 "SEH does not use catchret!");
22194 // Only 32-bit EH needs to worry about manually restoring stack pointers.
22195 if (!Subtarget->is32Bit())
22198 // C++ EH creates a new target block to hold the restore code, and wires up
22199 // the new block to the return destination with a normal JMP_4.
22200 MachineBasicBlock *RestoreMBB =
22201 MF->CreateMachineBasicBlock(BB->getBasicBlock());
22202 assert(BB->succ_size() == 1);
22203 MF->insert(std::next(BB->getIterator()), RestoreMBB);
22204 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22205 BB->addSuccessor(RestoreMBB);
22206 MI->getOperand(0).setMBB(RestoreMBB);
22208 auto RestoreMBBI = RestoreMBB->begin();
22209 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22210 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22214 MachineBasicBlock *
22215 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22216 MachineBasicBlock *BB) const {
22217 MachineFunction *MF = BB->getParent();
22218 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22219 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22220 // Only 32-bit SEH requires special handling for catchpad.
22221 if (IsSEH && Subtarget->is32Bit()) {
22222 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22223 DebugLoc DL = MI->getDebugLoc();
22224 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22226 MI->eraseFromParent();
22230 MachineBasicBlock *
22231 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22232 MachineBasicBlock *BB) const {
22233 // This is pretty easy. We're taking the value that we received from
22234 // our load from the relocation, sticking it in either RDI (x86-64)
22235 // or EAX and doing an indirect call. The return value will then
22236 // be in the normal return register.
22237 MachineFunction *F = BB->getParent();
22238 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22239 DebugLoc DL = MI->getDebugLoc();
22241 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22242 assert(MI->getOperand(3).isGlobal() && "This should be a global");
22244 // Get a register mask for the lowered call.
22245 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22246 // proper register mask.
22247 const uint32_t *RegMask =
22248 Subtarget->is64Bit() ?
22249 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22250 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22251 if (Subtarget->is64Bit()) {
22252 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22253 TII->get(X86::MOV64rm), X86::RDI)
22255 .addImm(0).addReg(0)
22256 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22257 MI->getOperand(3).getTargetFlags())
22259 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22260 addDirectMem(MIB, X86::RDI);
22261 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22262 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22263 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22264 TII->get(X86::MOV32rm), X86::EAX)
22266 .addImm(0).addReg(0)
22267 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22268 MI->getOperand(3).getTargetFlags())
22270 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22271 addDirectMem(MIB, X86::EAX);
22272 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22274 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22275 TII->get(X86::MOV32rm), X86::EAX)
22276 .addReg(TII->getGlobalBaseReg(F))
22277 .addImm(0).addReg(0)
22278 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22279 MI->getOperand(3).getTargetFlags())
22281 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22282 addDirectMem(MIB, X86::EAX);
22283 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22286 MI->eraseFromParent(); // The pseudo instruction is gone now.
22290 MachineBasicBlock *
22291 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22292 MachineBasicBlock *MBB) const {
22293 DebugLoc DL = MI->getDebugLoc();
22294 MachineFunction *MF = MBB->getParent();
22295 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22296 MachineRegisterInfo &MRI = MF->getRegInfo();
22298 const BasicBlock *BB = MBB->getBasicBlock();
22299 MachineFunction::iterator I = ++MBB->getIterator();
22301 // Memory Reference
22302 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22303 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22306 unsigned MemOpndSlot = 0;
22308 unsigned CurOp = 0;
22310 DstReg = MI->getOperand(CurOp++).getReg();
22311 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22312 assert(RC->hasType(MVT::i32) && "Invalid destination!");
22313 unsigned mainDstReg = MRI.createVirtualRegister(RC);
22314 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22316 MemOpndSlot = CurOp;
22318 MVT PVT = getPointerTy(MF->getDataLayout());
22319 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22320 "Invalid Pointer Size!");
22322 // For v = setjmp(buf), we generate
22325 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22326 // SjLjSetup restoreMBB
22332 // v = phi(main, restore)
22335 // if base pointer being used, load it from frame
22338 MachineBasicBlock *thisMBB = MBB;
22339 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22340 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22341 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22342 MF->insert(I, mainMBB);
22343 MF->insert(I, sinkMBB);
22344 MF->push_back(restoreMBB);
22345 restoreMBB->setHasAddressTaken();
22347 MachineInstrBuilder MIB;
22349 // Transfer the remainder of BB and its successor edges to sinkMBB.
22350 sinkMBB->splice(sinkMBB->begin(), MBB,
22351 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22352 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22355 unsigned PtrStoreOpc = 0;
22356 unsigned LabelReg = 0;
22357 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22358 Reloc::Model RM = MF->getTarget().getRelocationModel();
22359 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22360 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22362 // Prepare IP either in reg or imm.
22363 if (!UseImmLabel) {
22364 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22365 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22366 LabelReg = MRI.createVirtualRegister(PtrRC);
22367 if (Subtarget->is64Bit()) {
22368 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22372 .addMBB(restoreMBB)
22375 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22376 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22377 .addReg(XII->getGlobalBaseReg(MF))
22380 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22384 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22386 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22387 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22388 if (i == X86::AddrDisp)
22389 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22391 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22394 MIB.addReg(LabelReg);
22396 MIB.addMBB(restoreMBB);
22397 MIB.setMemRefs(MMOBegin, MMOEnd);
22399 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22400 .addMBB(restoreMBB);
22402 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22403 MIB.addRegMask(RegInfo->getNoPreservedMask());
22404 thisMBB->addSuccessor(mainMBB);
22405 thisMBB->addSuccessor(restoreMBB);
22409 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22410 mainMBB->addSuccessor(sinkMBB);
22413 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22414 TII->get(X86::PHI), DstReg)
22415 .addReg(mainDstReg).addMBB(mainMBB)
22416 .addReg(restoreDstReg).addMBB(restoreMBB);
22419 if (RegInfo->hasBasePointer(*MF)) {
22420 const bool Uses64BitFramePtr =
22421 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22422 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22423 X86FI->setRestoreBasePointer(MF);
22424 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22425 unsigned BasePtr = RegInfo->getBaseRegister();
22426 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22427 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22428 FramePtr, true, X86FI->getRestoreBasePointerOffset())
22429 .setMIFlag(MachineInstr::FrameSetup);
22431 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22432 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22433 restoreMBB->addSuccessor(sinkMBB);
22435 MI->eraseFromParent();
22439 MachineBasicBlock *
22440 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22441 MachineBasicBlock *MBB) const {
22442 DebugLoc DL = MI->getDebugLoc();
22443 MachineFunction *MF = MBB->getParent();
22444 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22445 MachineRegisterInfo &MRI = MF->getRegInfo();
22447 // Memory Reference
22448 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22449 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22451 MVT PVT = getPointerTy(MF->getDataLayout());
22452 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22453 "Invalid Pointer Size!");
22455 const TargetRegisterClass *RC =
22456 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22457 unsigned Tmp = MRI.createVirtualRegister(RC);
22458 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22459 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22460 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22461 unsigned SP = RegInfo->getStackRegister();
22463 MachineInstrBuilder MIB;
22465 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22466 const int64_t SPOffset = 2 * PVT.getStoreSize();
22468 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22469 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22472 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22473 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22474 MIB.addOperand(MI->getOperand(i));
22475 MIB.setMemRefs(MMOBegin, MMOEnd);
22477 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22478 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22479 if (i == X86::AddrDisp)
22480 MIB.addDisp(MI->getOperand(i), LabelOffset);
22482 MIB.addOperand(MI->getOperand(i));
22484 MIB.setMemRefs(MMOBegin, MMOEnd);
22486 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22487 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22488 if (i == X86::AddrDisp)
22489 MIB.addDisp(MI->getOperand(i), SPOffset);
22491 MIB.addOperand(MI->getOperand(i));
22493 MIB.setMemRefs(MMOBegin, MMOEnd);
22495 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22497 MI->eraseFromParent();
22501 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22502 // accumulator loops. Writing back to the accumulator allows the coalescer
22503 // to remove extra copies in the loop.
22504 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22505 MachineBasicBlock *
22506 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22507 MachineBasicBlock *MBB) const {
22508 MachineOperand &AddendOp = MI->getOperand(3);
22510 // Bail out early if the addend isn't a register - we can't switch these.
22511 if (!AddendOp.isReg())
22514 MachineFunction &MF = *MBB->getParent();
22515 MachineRegisterInfo &MRI = MF.getRegInfo();
22517 // Check whether the addend is defined by a PHI:
22518 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22519 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22520 if (!AddendDef.isPHI())
22523 // Look for the following pattern:
22525 // %addend = phi [%entry, 0], [%loop, %result]
22527 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22531 // %addend = phi [%entry, 0], [%loop, %result]
22533 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22535 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22536 assert(AddendDef.getOperand(i).isReg());
22537 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22538 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22539 if (&PHISrcInst == MI) {
22540 // Found a matching instruction.
22541 unsigned NewFMAOpc = 0;
22542 switch (MI->getOpcode()) {
22543 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22544 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22545 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22546 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22547 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22548 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22549 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22550 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22551 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22552 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22553 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22554 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22555 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22556 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22557 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22558 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22559 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22560 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22561 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22562 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22564 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22565 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22566 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22567 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22568 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22569 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22570 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22571 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22572 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22573 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22574 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22575 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22576 default: llvm_unreachable("Unrecognized FMA variant.");
22579 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22580 MachineInstrBuilder MIB =
22581 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22582 .addOperand(MI->getOperand(0))
22583 .addOperand(MI->getOperand(3))
22584 .addOperand(MI->getOperand(2))
22585 .addOperand(MI->getOperand(1));
22586 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22587 MI->eraseFromParent();
22594 MachineBasicBlock *
22595 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22596 MachineBasicBlock *BB) const {
22597 switch (MI->getOpcode()) {
22598 default: llvm_unreachable("Unexpected instr type to insert");
22599 case X86::TAILJMPd64:
22600 case X86::TAILJMPr64:
22601 case X86::TAILJMPm64:
22602 case X86::TAILJMPd64_REX:
22603 case X86::TAILJMPr64_REX:
22604 case X86::TAILJMPm64_REX:
22605 llvm_unreachable("TAILJMP64 would not be touched here.");
22606 case X86::TCRETURNdi64:
22607 case X86::TCRETURNri64:
22608 case X86::TCRETURNmi64:
22610 case X86::WIN_ALLOCA:
22611 return EmitLoweredWinAlloca(MI, BB);
22612 case X86::CATCHRET:
22613 return EmitLoweredCatchRet(MI, BB);
22614 case X86::CATCHPAD:
22615 return EmitLoweredCatchPad(MI, BB);
22616 case X86::SEG_ALLOCA_32:
22617 case X86::SEG_ALLOCA_64:
22618 return EmitLoweredSegAlloca(MI, BB);
22619 case X86::TLSCall_32:
22620 case X86::TLSCall_64:
22621 return EmitLoweredTLSCall(MI, BB);
22622 case X86::CMOV_FR32:
22623 case X86::CMOV_FR64:
22624 case X86::CMOV_FR128:
22625 case X86::CMOV_GR8:
22626 case X86::CMOV_GR16:
22627 case X86::CMOV_GR32:
22628 case X86::CMOV_RFP32:
22629 case X86::CMOV_RFP64:
22630 case X86::CMOV_RFP80:
22631 case X86::CMOV_V2F64:
22632 case X86::CMOV_V2I64:
22633 case X86::CMOV_V4F32:
22634 case X86::CMOV_V4F64:
22635 case X86::CMOV_V4I64:
22636 case X86::CMOV_V16F32:
22637 case X86::CMOV_V8F32:
22638 case X86::CMOV_V8F64:
22639 case X86::CMOV_V8I64:
22640 case X86::CMOV_V8I1:
22641 case X86::CMOV_V16I1:
22642 case X86::CMOV_V32I1:
22643 case X86::CMOV_V64I1:
22644 return EmitLoweredSelect(MI, BB);
22646 case X86::RDFLAGS32:
22647 case X86::RDFLAGS64: {
22648 DebugLoc DL = MI->getDebugLoc();
22649 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22651 MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22653 MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22654 BuildMI(*BB, MI, DL, TII->get(PushF));
22655 BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22657 MI->eraseFromParent(); // The pseudo is gone now.
22661 case X86::WRFLAGS32:
22662 case X86::WRFLAGS64: {
22663 DebugLoc DL = MI->getDebugLoc();
22664 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22666 MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22668 MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22669 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22670 BuildMI(*BB, MI, DL, TII->get(PopF));
22672 MI->eraseFromParent(); // The pseudo is gone now.
22676 case X86::RELEASE_FADD32mr:
22677 case X86::RELEASE_FADD64mr:
22678 return EmitLoweredAtomicFP(MI, BB);
22680 case X86::FP32_TO_INT16_IN_MEM:
22681 case X86::FP32_TO_INT32_IN_MEM:
22682 case X86::FP32_TO_INT64_IN_MEM:
22683 case X86::FP64_TO_INT16_IN_MEM:
22684 case X86::FP64_TO_INT32_IN_MEM:
22685 case X86::FP64_TO_INT64_IN_MEM:
22686 case X86::FP80_TO_INT16_IN_MEM:
22687 case X86::FP80_TO_INT32_IN_MEM:
22688 case X86::FP80_TO_INT64_IN_MEM: {
22689 MachineFunction *F = BB->getParent();
22690 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22691 DebugLoc DL = MI->getDebugLoc();
22693 // Change the floating point control register to use "round towards zero"
22694 // mode when truncating to an integer value.
22695 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22696 addFrameReference(BuildMI(*BB, MI, DL,
22697 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22699 // Load the old value of the high byte of the control word...
22701 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22702 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22705 // Set the high part to be round to zero...
22706 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22709 // Reload the modified control word now...
22710 addFrameReference(BuildMI(*BB, MI, DL,
22711 TII->get(X86::FLDCW16m)), CWFrameIdx);
22713 // Restore the memory image of control word to original value
22714 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22717 // Get the X86 opcode to use.
22719 switch (MI->getOpcode()) {
22720 default: llvm_unreachable("illegal opcode!");
22721 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22722 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22723 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22724 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22725 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22726 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22727 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22728 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22729 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22733 MachineOperand &Op = MI->getOperand(0);
22735 AM.BaseType = X86AddressMode::RegBase;
22736 AM.Base.Reg = Op.getReg();
22738 AM.BaseType = X86AddressMode::FrameIndexBase;
22739 AM.Base.FrameIndex = Op.getIndex();
22741 Op = MI->getOperand(1);
22743 AM.Scale = Op.getImm();
22744 Op = MI->getOperand(2);
22746 AM.IndexReg = Op.getImm();
22747 Op = MI->getOperand(3);
22748 if (Op.isGlobal()) {
22749 AM.GV = Op.getGlobal();
22751 AM.Disp = Op.getImm();
22753 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22754 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22756 // Reload the original control word now.
22757 addFrameReference(BuildMI(*BB, MI, DL,
22758 TII->get(X86::FLDCW16m)), CWFrameIdx);
22760 MI->eraseFromParent(); // The pseudo instruction is gone now.
22763 // String/text processing lowering.
22764 case X86::PCMPISTRM128REG:
22765 case X86::VPCMPISTRM128REG:
22766 case X86::PCMPISTRM128MEM:
22767 case X86::VPCMPISTRM128MEM:
22768 case X86::PCMPESTRM128REG:
22769 case X86::VPCMPESTRM128REG:
22770 case X86::PCMPESTRM128MEM:
22771 case X86::VPCMPESTRM128MEM:
22772 assert(Subtarget->hasSSE42() &&
22773 "Target must have SSE4.2 or AVX features enabled");
22774 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22776 // String/text processing lowering.
22777 case X86::PCMPISTRIREG:
22778 case X86::VPCMPISTRIREG:
22779 case X86::PCMPISTRIMEM:
22780 case X86::VPCMPISTRIMEM:
22781 case X86::PCMPESTRIREG:
22782 case X86::VPCMPESTRIREG:
22783 case X86::PCMPESTRIMEM:
22784 case X86::VPCMPESTRIMEM:
22785 assert(Subtarget->hasSSE42() &&
22786 "Target must have SSE4.2 or AVX features enabled");
22787 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22789 // Thread synchronization.
22791 return EmitMonitor(MI, BB, Subtarget);
22794 return EmitWRPKRU(MI, BB, Subtarget);
22796 return EmitRDPKRU(MI, BB, Subtarget);
22799 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22801 case X86::VASTART_SAVE_XMM_REGS:
22802 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22804 case X86::VAARG_64:
22805 return EmitVAARG64WithCustomInserter(MI, BB);
22807 case X86::EH_SjLj_SetJmp32:
22808 case X86::EH_SjLj_SetJmp64:
22809 return emitEHSjLjSetJmp(MI, BB);
22811 case X86::EH_SjLj_LongJmp32:
22812 case X86::EH_SjLj_LongJmp64:
22813 return emitEHSjLjLongJmp(MI, BB);
22815 case TargetOpcode::STATEPOINT:
22816 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22817 // this point in the process. We diverge later.
22818 return emitPatchPoint(MI, BB);
22820 case TargetOpcode::STACKMAP:
22821 case TargetOpcode::PATCHPOINT:
22822 return emitPatchPoint(MI, BB);
22824 case X86::VFMADDPDr213r:
22825 case X86::VFMADDPSr213r:
22826 case X86::VFMADDSDr213r:
22827 case X86::VFMADDSSr213r:
22828 case X86::VFMSUBPDr213r:
22829 case X86::VFMSUBPSr213r:
22830 case X86::VFMSUBSDr213r:
22831 case X86::VFMSUBSSr213r:
22832 case X86::VFNMADDPDr213r:
22833 case X86::VFNMADDPSr213r:
22834 case X86::VFNMADDSDr213r:
22835 case X86::VFNMADDSSr213r:
22836 case X86::VFNMSUBPDr213r:
22837 case X86::VFNMSUBPSr213r:
22838 case X86::VFNMSUBSDr213r:
22839 case X86::VFNMSUBSSr213r:
22840 case X86::VFMADDSUBPDr213r:
22841 case X86::VFMADDSUBPSr213r:
22842 case X86::VFMSUBADDPDr213r:
22843 case X86::VFMSUBADDPSr213r:
22844 case X86::VFMADDPDr213rY:
22845 case X86::VFMADDPSr213rY:
22846 case X86::VFMSUBPDr213rY:
22847 case X86::VFMSUBPSr213rY:
22848 case X86::VFNMADDPDr213rY:
22849 case X86::VFNMADDPSr213rY:
22850 case X86::VFNMSUBPDr213rY:
22851 case X86::VFNMSUBPSr213rY:
22852 case X86::VFMADDSUBPDr213rY:
22853 case X86::VFMADDSUBPSr213rY:
22854 case X86::VFMSUBADDPDr213rY:
22855 case X86::VFMSUBADDPSr213rY:
22856 return emitFMA3Instr(MI, BB);
22860 //===----------------------------------------------------------------------===//
22861 // X86 Optimization Hooks
22862 //===----------------------------------------------------------------------===//
22864 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22867 const SelectionDAG &DAG,
22868 unsigned Depth) const {
22869 unsigned BitWidth = KnownZero.getBitWidth();
22870 unsigned Opc = Op.getOpcode();
22871 assert((Opc >= ISD::BUILTIN_OP_END ||
22872 Opc == ISD::INTRINSIC_WO_CHAIN ||
22873 Opc == ISD::INTRINSIC_W_CHAIN ||
22874 Opc == ISD::INTRINSIC_VOID) &&
22875 "Should use MaskedValueIsZero if you don't know whether Op"
22876 " is a target node!");
22878 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22892 // These nodes' second result is a boolean.
22893 if (Op.getResNo() == 0)
22896 case X86ISD::SETCC:
22897 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22899 case ISD::INTRINSIC_WO_CHAIN: {
22900 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22901 unsigned NumLoBits = 0;
22904 case Intrinsic::x86_sse_movmsk_ps:
22905 case Intrinsic::x86_avx_movmsk_ps_256:
22906 case Intrinsic::x86_sse2_movmsk_pd:
22907 case Intrinsic::x86_avx_movmsk_pd_256:
22908 case Intrinsic::x86_mmx_pmovmskb:
22909 case Intrinsic::x86_sse2_pmovmskb_128:
22910 case Intrinsic::x86_avx2_pmovmskb: {
22911 // High bits of movmskp{s|d}, pmovmskb are known zero.
22913 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22914 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22915 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22916 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22917 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22918 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22919 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22920 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22922 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22931 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22933 const SelectionDAG &,
22934 unsigned Depth) const {
22935 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22936 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22937 return Op.getValueType().getScalarSizeInBits();
22943 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22944 /// node is a GlobalAddress + offset.
22945 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22946 const GlobalValue* &GA,
22947 int64_t &Offset) const {
22948 if (N->getOpcode() == X86ISD::Wrapper) {
22949 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22950 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22951 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22955 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22958 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22959 /// FIXME: This could be expanded to support 512 bit vectors as well.
22960 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22961 TargetLowering::DAGCombinerInfo &DCI,
22962 const X86Subtarget* Subtarget) {
22964 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22965 SDValue V1 = SVOp->getOperand(0);
22966 SDValue V2 = SVOp->getOperand(1);
22967 MVT VT = SVOp->getSimpleValueType(0);
22968 unsigned NumElems = VT.getVectorNumElements();
22970 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22971 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22975 // V UNDEF BUILD_VECTOR UNDEF
22977 // CONCAT_VECTOR CONCAT_VECTOR
22980 // RESULT: V + zero extended
22982 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22983 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22984 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22987 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22990 // To match the shuffle mask, the first half of the mask should
22991 // be exactly the first vector, and all the rest a splat with the
22992 // first element of the second one.
22993 for (unsigned i = 0; i != NumElems/2; ++i)
22994 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22995 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22998 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22999 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
23000 if (Ld->hasNUsesOfValue(1, 0)) {
23001 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
23002 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
23004 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
23006 Ld->getPointerInfo(),
23007 Ld->getAlignment(),
23008 false/*isVolatile*/, true/*ReadMem*/,
23009 false/*WriteMem*/);
23011 // Make sure the newly-created LOAD is in the same position as Ld in
23012 // terms of dependency. We create a TokenFactor for Ld and ResNode,
23013 // and update uses of Ld's output chain to use the TokenFactor.
23014 if (Ld->hasAnyUseOfValue(1)) {
23015 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23016 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
23017 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
23018 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
23019 SDValue(ResNode.getNode(), 1));
23022 return DAG.getBitcast(VT, ResNode);
23026 // Emit a zeroed vector and insert the desired subvector on its
23028 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
23029 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
23030 return DCI.CombineTo(N, InsV);
23036 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23039 /// This is the leaf of the recursive combinine below. When we have found some
23040 /// chain of single-use x86 shuffle instructions and accumulated the combined
23041 /// shuffle mask represented by them, this will try to pattern match that mask
23042 /// into either a single instruction if there is a special purpose instruction
23043 /// for this operation, or into a PSHUFB instruction which is a fully general
23044 /// instruction but should only be used to replace chains over a certain depth.
23045 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23046 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23047 TargetLowering::DAGCombinerInfo &DCI,
23048 const X86Subtarget *Subtarget) {
23049 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23051 // Find the operand that enters the chain. Note that multiple uses are OK
23052 // here, we're not going to remove the operand we find.
23053 SDValue Input = Op.getOperand(0);
23054 while (Input.getOpcode() == ISD::BITCAST)
23055 Input = Input.getOperand(0);
23057 MVT VT = Input.getSimpleValueType();
23058 MVT RootVT = Root.getSimpleValueType();
23061 if (Mask.size() == 1) {
23062 int Index = Mask[0];
23063 assert((Index >= 0 || Index == SM_SentinelUndef ||
23064 Index == SM_SentinelZero) &&
23065 "Invalid shuffle index found!");
23067 // We may end up with an accumulated mask of size 1 as a result of
23068 // widening of shuffle operands (see function canWidenShuffleElements).
23069 // If the only shuffle index is equal to SM_SentinelZero then propagate
23070 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23071 // mask, and therefore the entire chain of shuffles can be folded away.
23072 if (Index == SM_SentinelZero)
23073 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23075 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23080 // Use the float domain if the operand type is a floating point type.
23081 bool FloatDomain = VT.isFloatingPoint();
23083 // For floating point shuffles, we don't have free copies in the shuffle
23084 // instructions or the ability to load as part of the instruction, so
23085 // canonicalize their shuffles to UNPCK or MOV variants.
23087 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23088 // vectors because it can have a load folded into it that UNPCK cannot. This
23089 // doesn't preclude something switching to the shorter encoding post-RA.
23091 // FIXME: Should teach these routines about AVX vector widths.
23092 if (FloatDomain && VT.is128BitVector()) {
23093 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23094 bool Lo = Mask.equals({0, 0});
23097 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23098 // is no slower than UNPCKLPD but has the option to fold the input operand
23099 // into even an unaligned memory load.
23100 if (Lo && Subtarget->hasSSE3()) {
23101 Shuffle = X86ISD::MOVDDUP;
23102 ShuffleVT = MVT::v2f64;
23104 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23105 // than the UNPCK variants.
23106 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23107 ShuffleVT = MVT::v4f32;
23109 if (Depth == 1 && Root->getOpcode() == Shuffle)
23110 return false; // Nothing to do!
23111 Op = DAG.getBitcast(ShuffleVT, Input);
23112 DCI.AddToWorklist(Op.getNode());
23113 if (Shuffle == X86ISD::MOVDDUP)
23114 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23116 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23117 DCI.AddToWorklist(Op.getNode());
23118 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23122 if (Subtarget->hasSSE3() &&
23123 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23124 bool Lo = Mask.equals({0, 0, 2, 2});
23125 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23126 MVT ShuffleVT = MVT::v4f32;
23127 if (Depth == 1 && Root->getOpcode() == Shuffle)
23128 return false; // Nothing to do!
23129 Op = DAG.getBitcast(ShuffleVT, Input);
23130 DCI.AddToWorklist(Op.getNode());
23131 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23132 DCI.AddToWorklist(Op.getNode());
23133 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23137 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23138 bool Lo = Mask.equals({0, 0, 1, 1});
23139 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23140 MVT ShuffleVT = MVT::v4f32;
23141 if (Depth == 1 && Root->getOpcode() == Shuffle)
23142 return false; // Nothing to do!
23143 Op = DAG.getBitcast(ShuffleVT, Input);
23144 DCI.AddToWorklist(Op.getNode());
23145 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23146 DCI.AddToWorklist(Op.getNode());
23147 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23153 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23154 // variants as none of these have single-instruction variants that are
23155 // superior to the UNPCK formulation.
23156 if (!FloatDomain && VT.is128BitVector() &&
23157 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23158 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23159 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23161 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23162 bool Lo = Mask[0] == 0;
23163 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23164 if (Depth == 1 && Root->getOpcode() == Shuffle)
23165 return false; // Nothing to do!
23167 switch (Mask.size()) {
23169 ShuffleVT = MVT::v8i16;
23172 ShuffleVT = MVT::v16i8;
23175 llvm_unreachable("Impossible mask size!");
23177 Op = DAG.getBitcast(ShuffleVT, Input);
23178 DCI.AddToWorklist(Op.getNode());
23179 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23180 DCI.AddToWorklist(Op.getNode());
23181 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23186 // Don't try to re-form single instruction chains under any circumstances now
23187 // that we've done encoding canonicalization for them.
23191 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23192 // can replace them with a single PSHUFB instruction profitably. Intel's
23193 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23194 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23195 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23196 SmallVector<SDValue, 16> PSHUFBMask;
23197 int NumBytes = VT.getSizeInBits() / 8;
23198 int Ratio = NumBytes / Mask.size();
23199 for (int i = 0; i < NumBytes; ++i) {
23200 if (Mask[i / Ratio] == SM_SentinelUndef) {
23201 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23204 int M = Mask[i / Ratio] != SM_SentinelZero
23205 ? Ratio * Mask[i / Ratio] + i % Ratio
23207 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23209 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23210 Op = DAG.getBitcast(ByteVT, Input);
23211 DCI.AddToWorklist(Op.getNode());
23212 SDValue PSHUFBMaskOp =
23213 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23214 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23215 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23216 DCI.AddToWorklist(Op.getNode());
23217 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23222 // Failed to find any combines.
23226 /// \brief Fully generic combining of x86 shuffle instructions.
23228 /// This should be the last combine run over the x86 shuffle instructions. Once
23229 /// they have been fully optimized, this will recursively consider all chains
23230 /// of single-use shuffle instructions, build a generic model of the cumulative
23231 /// shuffle operation, and check for simpler instructions which implement this
23232 /// operation. We use this primarily for two purposes:
23234 /// 1) Collapse generic shuffles to specialized single instructions when
23235 /// equivalent. In most cases, this is just an encoding size win, but
23236 /// sometimes we will collapse multiple generic shuffles into a single
23237 /// special-purpose shuffle.
23238 /// 2) Look for sequences of shuffle instructions with 3 or more total
23239 /// instructions, and replace them with the slightly more expensive SSSE3
23240 /// PSHUFB instruction if available. We do this as the last combining step
23241 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
23242 /// a suitable short sequence of other instructions. The PHUFB will either
23243 /// use a register or have to read from memory and so is slightly (but only
23244 /// slightly) more expensive than the other shuffle instructions.
23246 /// Because this is inherently a quadratic operation (for each shuffle in
23247 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23248 /// This should never be an issue in practice as the shuffle lowering doesn't
23249 /// produce sequences of more than 8 instructions.
23251 /// FIXME: We will currently miss some cases where the redundant shuffling
23252 /// would simplify under the threshold for PSHUFB formation because of
23253 /// combine-ordering. To fix this, we should do the redundant instruction
23254 /// combining in this recursive walk.
23255 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23256 ArrayRef<int> RootMask,
23257 int Depth, bool HasPSHUFB,
23259 TargetLowering::DAGCombinerInfo &DCI,
23260 const X86Subtarget *Subtarget) {
23261 // Bound the depth of our recursive combine because this is ultimately
23262 // quadratic in nature.
23266 // Directly rip through bitcasts to find the underlying operand.
23267 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23268 Op = Op.getOperand(0);
23270 MVT VT = Op.getSimpleValueType();
23271 if (!VT.isVector())
23272 return false; // Bail if we hit a non-vector.
23274 assert(Root.getSimpleValueType().isVector() &&
23275 "Shuffles operate on vector types!");
23276 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23277 "Can only combine shuffles of the same vector register size.");
23279 if (!isTargetShuffle(Op.getOpcode()))
23281 SmallVector<int, 16> OpMask;
23283 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23284 // We only can combine unary shuffles which we can decode the mask for.
23285 if (!HaveMask || !IsUnary)
23288 assert(VT.getVectorNumElements() == OpMask.size() &&
23289 "Different mask size from vector size!");
23290 assert(((RootMask.size() > OpMask.size() &&
23291 RootMask.size() % OpMask.size() == 0) ||
23292 (OpMask.size() > RootMask.size() &&
23293 OpMask.size() % RootMask.size() == 0) ||
23294 OpMask.size() == RootMask.size()) &&
23295 "The smaller number of elements must divide the larger.");
23296 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23297 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23298 assert(((RootRatio == 1 && OpRatio == 1) ||
23299 (RootRatio == 1) != (OpRatio == 1)) &&
23300 "Must not have a ratio for both incoming and op masks!");
23302 SmallVector<int, 16> Mask;
23303 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23305 // Merge this shuffle operation's mask into our accumulated mask. Note that
23306 // this shuffle's mask will be the first applied to the input, followed by the
23307 // root mask to get us all the way to the root value arrangement. The reason
23308 // for this order is that we are recursing up the operation chain.
23309 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23310 int RootIdx = i / RootRatio;
23311 if (RootMask[RootIdx] < 0) {
23312 // This is a zero or undef lane, we're done.
23313 Mask.push_back(RootMask[RootIdx]);
23317 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23318 int OpIdx = RootMaskedIdx / OpRatio;
23319 if (OpMask[OpIdx] < 0) {
23320 // The incoming lanes are zero or undef, it doesn't matter which ones we
23322 Mask.push_back(OpMask[OpIdx]);
23326 // Ok, we have non-zero lanes, map them through.
23327 Mask.push_back(OpMask[OpIdx] * OpRatio +
23328 RootMaskedIdx % OpRatio);
23331 // See if we can recurse into the operand to combine more things.
23332 switch (Op.getOpcode()) {
23333 case X86ISD::PSHUFB:
23335 case X86ISD::PSHUFD:
23336 case X86ISD::PSHUFHW:
23337 case X86ISD::PSHUFLW:
23338 if (Op.getOperand(0).hasOneUse() &&
23339 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23340 HasPSHUFB, DAG, DCI, Subtarget))
23344 case X86ISD::UNPCKL:
23345 case X86ISD::UNPCKH:
23346 assert(Op.getOperand(0) == Op.getOperand(1) &&
23347 "We only combine unary shuffles!");
23348 // We can't check for single use, we have to check that this shuffle is the
23350 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23351 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23352 HasPSHUFB, DAG, DCI, Subtarget))
23357 // Minor canonicalization of the accumulated shuffle mask to make it easier
23358 // to match below. All this does is detect masks with squential pairs of
23359 // elements, and shrink them to the half-width mask. It does this in a loop
23360 // so it will reduce the size of the mask to the minimal width mask which
23361 // performs an equivalent shuffle.
23362 SmallVector<int, 16> WidenedMask;
23363 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23364 Mask = std::move(WidenedMask);
23365 WidenedMask.clear();
23368 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23372 /// \brief Get the PSHUF-style mask from PSHUF node.
23374 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23375 /// PSHUF-style masks that can be reused with such instructions.
23376 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23377 MVT VT = N.getSimpleValueType();
23378 SmallVector<int, 4> Mask;
23380 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23384 // If we have more than 128-bits, only the low 128-bits of shuffle mask
23385 // matter. Check that the upper masks are repeats and remove them.
23386 if (VT.getSizeInBits() > 128) {
23387 int LaneElts = 128 / VT.getScalarSizeInBits();
23389 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23390 for (int j = 0; j < LaneElts; ++j)
23391 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23392 "Mask doesn't repeat in high 128-bit lanes!");
23394 Mask.resize(LaneElts);
23397 switch (N.getOpcode()) {
23398 case X86ISD::PSHUFD:
23400 case X86ISD::PSHUFLW:
23403 case X86ISD::PSHUFHW:
23404 Mask.erase(Mask.begin(), Mask.begin() + 4);
23405 for (int &M : Mask)
23409 llvm_unreachable("No valid shuffle instruction found!");
23413 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23415 /// We walk up the chain and look for a combinable shuffle, skipping over
23416 /// shuffles that we could hoist this shuffle's transformation past without
23417 /// altering anything.
23419 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23421 TargetLowering::DAGCombinerInfo &DCI) {
23422 assert(N.getOpcode() == X86ISD::PSHUFD &&
23423 "Called with something other than an x86 128-bit half shuffle!");
23426 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23427 // of the shuffles in the chain so that we can form a fresh chain to replace
23429 SmallVector<SDValue, 8> Chain;
23430 SDValue V = N.getOperand(0);
23431 for (; V.hasOneUse(); V = V.getOperand(0)) {
23432 switch (V.getOpcode()) {
23434 return SDValue(); // Nothing combined!
23437 // Skip bitcasts as we always know the type for the target specific
23441 case X86ISD::PSHUFD:
23442 // Found another dword shuffle.
23445 case X86ISD::PSHUFLW:
23446 // Check that the low words (being shuffled) are the identity in the
23447 // dword shuffle, and the high words are self-contained.
23448 if (Mask[0] != 0 || Mask[1] != 1 ||
23449 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23452 Chain.push_back(V);
23455 case X86ISD::PSHUFHW:
23456 // Check that the high words (being shuffled) are the identity in the
23457 // dword shuffle, and the low words are self-contained.
23458 if (Mask[2] != 2 || Mask[3] != 3 ||
23459 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23462 Chain.push_back(V);
23465 case X86ISD::UNPCKL:
23466 case X86ISD::UNPCKH:
23467 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23468 // shuffle into a preceding word shuffle.
23469 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23470 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23473 // Search for a half-shuffle which we can combine with.
23474 unsigned CombineOp =
23475 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23476 if (V.getOperand(0) != V.getOperand(1) ||
23477 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23479 Chain.push_back(V);
23480 V = V.getOperand(0);
23482 switch (V.getOpcode()) {
23484 return SDValue(); // Nothing to combine.
23486 case X86ISD::PSHUFLW:
23487 case X86ISD::PSHUFHW:
23488 if (V.getOpcode() == CombineOp)
23491 Chain.push_back(V);
23495 V = V.getOperand(0);
23499 } while (V.hasOneUse());
23502 // Break out of the loop if we break out of the switch.
23506 if (!V.hasOneUse())
23507 // We fell out of the loop without finding a viable combining instruction.
23510 // Merge this node's mask and our incoming mask.
23511 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23512 for (int &M : Mask)
23514 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23515 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23517 // Rebuild the chain around this new shuffle.
23518 while (!Chain.empty()) {
23519 SDValue W = Chain.pop_back_val();
23521 if (V.getValueType() != W.getOperand(0).getValueType())
23522 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23524 switch (W.getOpcode()) {
23526 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23528 case X86ISD::UNPCKL:
23529 case X86ISD::UNPCKH:
23530 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23533 case X86ISD::PSHUFD:
23534 case X86ISD::PSHUFLW:
23535 case X86ISD::PSHUFHW:
23536 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23540 if (V.getValueType() != N.getValueType())
23541 V = DAG.getBitcast(N.getValueType(), V);
23543 // Return the new chain to replace N.
23547 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23550 /// We walk up the chain, skipping shuffles of the other half and looking
23551 /// through shuffles which switch halves trying to find a shuffle of the same
23552 /// pair of dwords.
23553 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23555 TargetLowering::DAGCombinerInfo &DCI) {
23557 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23558 "Called with something other than an x86 128-bit half shuffle!");
23560 unsigned CombineOpcode = N.getOpcode();
23562 // Walk up a single-use chain looking for a combinable shuffle.
23563 SDValue V = N.getOperand(0);
23564 for (; V.hasOneUse(); V = V.getOperand(0)) {
23565 switch (V.getOpcode()) {
23567 return false; // Nothing combined!
23570 // Skip bitcasts as we always know the type for the target specific
23574 case X86ISD::PSHUFLW:
23575 case X86ISD::PSHUFHW:
23576 if (V.getOpcode() == CombineOpcode)
23579 // Other-half shuffles are no-ops.
23582 // Break out of the loop if we break out of the switch.
23586 if (!V.hasOneUse())
23587 // We fell out of the loop without finding a viable combining instruction.
23590 // Combine away the bottom node as its shuffle will be accumulated into
23591 // a preceding shuffle.
23592 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23594 // Record the old value.
23597 // Merge this node's mask and our incoming mask (adjusted to account for all
23598 // the pshufd instructions encountered).
23599 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23600 for (int &M : Mask)
23602 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23603 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23605 // Check that the shuffles didn't cancel each other out. If not, we need to
23606 // combine to the new one.
23608 // Replace the combinable shuffle with the combined one, updating all users
23609 // so that we re-evaluate the chain here.
23610 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23615 /// \brief Try to combine x86 target specific shuffles.
23616 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23617 TargetLowering::DAGCombinerInfo &DCI,
23618 const X86Subtarget *Subtarget) {
23620 MVT VT = N.getSimpleValueType();
23621 SmallVector<int, 4> Mask;
23623 switch (N.getOpcode()) {
23624 case X86ISD::PSHUFD:
23625 case X86ISD::PSHUFLW:
23626 case X86ISD::PSHUFHW:
23627 Mask = getPSHUFShuffleMask(N);
23628 assert(Mask.size() == 4);
23630 case X86ISD::UNPCKL: {
23631 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23632 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23633 // moves upper half elements into the lower half part. For example:
23635 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23637 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23639 // will be combined to:
23641 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23643 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23644 // happen due to advanced instructions.
23645 if (!VT.is128BitVector())
23648 auto Op0 = N.getOperand(0);
23649 auto Op1 = N.getOperand(1);
23650 if (Op0.getOpcode() == ISD::UNDEF &&
23651 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23652 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23654 unsigned NumElts = VT.getVectorNumElements();
23655 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23656 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23659 auto ShufOp = Op1.getOperand(0);
23660 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23661 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23665 case X86ISD::BLENDI: {
23666 SDValue V0 = N->getOperand(0);
23667 SDValue V1 = N->getOperand(1);
23668 assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23669 "Unexpected input vector types");
23671 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23672 // operands and changing the mask to 1. This saves us a bunch of
23673 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23674 // x86InstrInfo knows how to commute this back after instruction selection
23675 // if it would help register allocation.
23677 // TODO: If optimizing for size or a processor that doesn't suffer from
23678 // partial register update stalls, this should be transformed into a MOVSD
23679 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23681 if (VT == MVT::v2f64)
23682 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23683 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23684 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23685 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23694 // Nuke no-op shuffles that show up after combining.
23695 if (isNoopShuffleMask(Mask))
23696 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23698 // Look for simplifications involving one or two shuffle instructions.
23699 SDValue V = N.getOperand(0);
23700 switch (N.getOpcode()) {
23703 case X86ISD::PSHUFLW:
23704 case X86ISD::PSHUFHW:
23705 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23707 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23708 return SDValue(); // We combined away this shuffle, so we're done.
23710 // See if this reduces to a PSHUFD which is no more expensive and can
23711 // combine with more operations. Note that it has to at least flip the
23712 // dwords as otherwise it would have been removed as a no-op.
23713 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23714 int DMask[] = {0, 1, 2, 3};
23715 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23716 DMask[DOffset + 0] = DOffset + 1;
23717 DMask[DOffset + 1] = DOffset + 0;
23718 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23719 V = DAG.getBitcast(DVT, V);
23720 DCI.AddToWorklist(V.getNode());
23721 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23722 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23723 DCI.AddToWorklist(V.getNode());
23724 return DAG.getBitcast(VT, V);
23727 // Look for shuffle patterns which can be implemented as a single unpack.
23728 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23729 // only works when we have a PSHUFD followed by two half-shuffles.
23730 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23731 (V.getOpcode() == X86ISD::PSHUFLW ||
23732 V.getOpcode() == X86ISD::PSHUFHW) &&
23733 V.getOpcode() != N.getOpcode() &&
23735 SDValue D = V.getOperand(0);
23736 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23737 D = D.getOperand(0);
23738 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23739 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23740 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23741 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23742 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23744 for (int i = 0; i < 4; ++i) {
23745 WordMask[i + NOffset] = Mask[i] + NOffset;
23746 WordMask[i + VOffset] = VMask[i] + VOffset;
23748 // Map the word mask through the DWord mask.
23750 for (int i = 0; i < 8; ++i)
23751 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23752 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23753 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23754 // We can replace all three shuffles with an unpack.
23755 V = DAG.getBitcast(VT, D.getOperand(0));
23756 DCI.AddToWorklist(V.getNode());
23757 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23766 case X86ISD::PSHUFD:
23767 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23776 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23778 /// We combine this directly on the abstract vector shuffle nodes so it is
23779 /// easier to generically match. We also insert dummy vector shuffle nodes for
23780 /// the operands which explicitly discard the lanes which are unused by this
23781 /// operation to try to flow through the rest of the combiner the fact that
23782 /// they're unused.
23783 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23784 SelectionDAG &DAG) {
23786 EVT VT = N->getValueType(0);
23787 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23788 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23791 // We only handle target-independent shuffles.
23792 // FIXME: It would be easy and harmless to use the target shuffle mask
23793 // extraction tool to support more.
23794 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23797 auto *SVN = cast<ShuffleVectorSDNode>(N);
23798 SmallVector<int, 8> Mask;
23799 for (int M : SVN->getMask())
23802 SDValue V1 = N->getOperand(0);
23803 SDValue V2 = N->getOperand(1);
23805 // We require the first shuffle operand to be the FSUB node, and the second to
23806 // be the FADD node.
23807 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23808 ShuffleVectorSDNode::commuteMask(Mask);
23810 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23813 // If there are other uses of these operations we can't fold them.
23814 if (!V1->hasOneUse() || !V2->hasOneUse())
23817 // Ensure that both operations have the same operands. Note that we can
23818 // commute the FADD operands.
23819 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23820 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23821 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23824 // We're looking for blends between FADD and FSUB nodes. We insist on these
23825 // nodes being lined up in a specific expected pattern.
23826 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23827 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23828 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23831 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23834 /// PerformShuffleCombine - Performs several different shuffle combines.
23835 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23836 TargetLowering::DAGCombinerInfo &DCI,
23837 const X86Subtarget *Subtarget) {
23839 SDValue N0 = N->getOperand(0);
23840 SDValue N1 = N->getOperand(1);
23841 EVT VT = N->getValueType(0);
23843 // Don't create instructions with illegal types after legalize types has run.
23844 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23845 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23848 // If we have legalized the vector types, look for blends of FADD and FSUB
23849 // nodes that we can fuse into an ADDSUB node.
23850 if (TLI.isTypeLegal(VT))
23851 if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23854 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23855 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23856 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23857 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23859 // During Type Legalization, when promoting illegal vector types,
23860 // the backend might introduce new shuffle dag nodes and bitcasts.
23862 // This code performs the following transformation:
23863 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23864 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23866 // We do this only if both the bitcast and the BINOP dag nodes have
23867 // one use. Also, perform this transformation only if the new binary
23868 // operation is legal. This is to avoid introducing dag nodes that
23869 // potentially need to be further expanded (or custom lowered) into a
23870 // less optimal sequence of dag nodes.
23871 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23872 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23873 N0.getOpcode() == ISD::BITCAST) {
23874 SDValue BC0 = N0.getOperand(0);
23875 EVT SVT = BC0.getValueType();
23876 unsigned Opcode = BC0.getOpcode();
23877 unsigned NumElts = VT.getVectorNumElements();
23879 if (BC0.hasOneUse() && SVT.isVector() &&
23880 SVT.getVectorNumElements() * 2 == NumElts &&
23881 TLI.isOperationLegal(Opcode, VT)) {
23882 bool CanFold = false;
23894 unsigned SVTNumElts = SVT.getVectorNumElements();
23895 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23896 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23897 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23898 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23899 CanFold = SVOp->getMaskElt(i) < 0;
23902 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23903 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23904 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23905 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23910 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23911 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23912 // consecutive, non-overlapping, and in the right order.
23913 SmallVector<SDValue, 16> Elts;
23914 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23915 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23917 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23920 if (isTargetShuffle(N->getOpcode())) {
23922 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23923 if (Shuffle.getNode())
23926 // Try recursively combining arbitrary sequences of x86 shuffle
23927 // instructions into higher-order shuffles. We do this after combining
23928 // specific PSHUF instruction sequences into their minimal form so that we
23929 // can evaluate how many specialized shuffle instructions are involved in
23930 // a particular chain.
23931 SmallVector<int, 1> NonceMask; // Just a placeholder.
23932 NonceMask.push_back(0);
23933 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23934 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23936 return SDValue(); // This routine will use CombineTo to replace N.
23942 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23943 /// specific shuffle of a load can be folded into a single element load.
23944 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23945 /// shuffles have been custom lowered so we need to handle those here.
23946 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23947 TargetLowering::DAGCombinerInfo &DCI) {
23948 if (DCI.isBeforeLegalizeOps())
23951 SDValue InVec = N->getOperand(0);
23952 SDValue EltNo = N->getOperand(1);
23953 EVT EltVT = N->getValueType(0);
23955 if (!isa<ConstantSDNode>(EltNo))
23958 EVT OriginalVT = InVec.getValueType();
23960 if (InVec.getOpcode() == ISD::BITCAST) {
23961 // Don't duplicate a load with other uses.
23962 if (!InVec.hasOneUse())
23964 EVT BCVT = InVec.getOperand(0).getValueType();
23965 if (!BCVT.isVector() ||
23966 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23968 InVec = InVec.getOperand(0);
23971 EVT CurrentVT = InVec.getValueType();
23973 if (!isTargetShuffle(InVec.getOpcode()))
23976 // Don't duplicate a load with other uses.
23977 if (!InVec.hasOneUse())
23980 SmallVector<int, 16> ShuffleMask;
23982 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23983 ShuffleMask, UnaryShuffle))
23986 // Select the input vector, guarding against out of range extract vector.
23987 unsigned NumElems = CurrentVT.getVectorNumElements();
23988 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23989 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
23991 if (Idx == SM_SentinelZero)
23992 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
23993 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
23994 if (Idx == SM_SentinelUndef)
23995 return DAG.getUNDEF(EltVT);
23997 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
23998 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23999 : InVec.getOperand(1);
24001 // If inputs to shuffle are the same for both ops, then allow 2 uses
24002 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
24003 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
24005 if (LdNode.getOpcode() == ISD::BITCAST) {
24006 // Don't duplicate a load with other uses.
24007 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
24010 AllowedUses = 1; // only allow 1 load use if we have a bitcast
24011 LdNode = LdNode.getOperand(0);
24014 if (!ISD::isNormalLoad(LdNode.getNode()))
24017 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
24019 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
24022 // If there's a bitcast before the shuffle, check if the load type and
24023 // alignment is valid.
24024 unsigned Align = LN0->getAlignment();
24025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24026 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
24027 EltVT.getTypeForEVT(*DAG.getContext()));
24029 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
24032 // All checks match so transform back to vector_shuffle so that DAG combiner
24033 // can finish the job
24036 // Create shuffle node taking into account the case that its a unary shuffle
24037 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24038 : InVec.getOperand(1);
24039 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24040 InVec.getOperand(0), Shuffle,
24042 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24043 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24047 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24048 const X86Subtarget *Subtarget) {
24049 SDValue N0 = N->getOperand(0);
24050 EVT VT = N->getValueType(0);
24052 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24053 // special and don't usually play with other vector types, it's better to
24054 // handle them early to be sure we emit efficient code by avoiding
24055 // store-load conversions.
24056 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24057 N0.getValueType() == MVT::v2i32 &&
24058 isNullConstant(N0.getOperand(1))) {
24059 SDValue N00 = N0->getOperand(0);
24060 if (N00.getValueType() == MVT::i32)
24061 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24064 // Convert a bitcasted integer logic operation that has one bitcasted
24065 // floating-point operand and one constant operand into a floating-point
24066 // logic operation. This may create a load of the constant, but that is
24067 // cheaper than materializing the constant in an integer register and
24068 // transferring it to an SSE register or transferring the SSE operand to
24069 // integer register and back.
24071 switch (N0.getOpcode()) {
24072 case ISD::AND: FPOpcode = X86ISD::FAND; break;
24073 case ISD::OR: FPOpcode = X86ISD::FOR; break;
24074 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24075 default: return SDValue();
24077 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24078 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24079 isa<ConstantSDNode>(N0.getOperand(1)) &&
24080 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24081 N0.getOperand(0).getOperand(0).getValueType() == VT) {
24082 SDValue N000 = N0.getOperand(0).getOperand(0);
24083 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24084 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24090 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24091 /// generation and convert it from being a bunch of shuffles and extracts
24092 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24093 /// storing the value and loading scalars back, while for x64 we should
24094 /// use 64-bit extracts and shifts.
24095 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24096 TargetLowering::DAGCombinerInfo &DCI) {
24097 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24100 SDValue InputVector = N->getOperand(0);
24101 SDLoc dl(InputVector);
24102 // Detect mmx to i32 conversion through a v2i32 elt extract.
24103 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24104 N->getValueType(0) == MVT::i32 &&
24105 InputVector.getValueType() == MVT::v2i32) {
24107 // The bitcast source is a direct mmx result.
24108 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24109 if (MMXSrc.getValueType() == MVT::x86mmx)
24110 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24111 N->getValueType(0),
24112 InputVector.getNode()->getOperand(0));
24114 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24115 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24116 MMXSrc.getValueType() == MVT::i64) {
24117 SDValue MMXSrcOp = MMXSrc.getOperand(0);
24118 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24119 MMXSrcOp.getValueType() == MVT::v1i64 &&
24120 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24121 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24122 N->getValueType(0), MMXSrcOp.getOperand(0));
24126 EVT VT = N->getValueType(0);
24128 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24129 InputVector.getOpcode() == ISD::BITCAST &&
24130 isa<ConstantSDNode>(InputVector.getOperand(0))) {
24131 uint64_t ExtractedElt =
24132 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24133 uint64_t InputValue =
24134 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24135 uint64_t Res = (InputValue >> ExtractedElt) & 1;
24136 return DAG.getConstant(Res, dl, MVT::i1);
24138 // Only operate on vectors of 4 elements, where the alternative shuffling
24139 // gets to be more expensive.
24140 if (InputVector.getValueType() != MVT::v4i32)
24143 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24144 // single use which is a sign-extend or zero-extend, and all elements are
24146 SmallVector<SDNode *, 4> Uses;
24147 unsigned ExtractedElements = 0;
24148 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24149 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24150 if (UI.getUse().getResNo() != InputVector.getResNo())
24153 SDNode *Extract = *UI;
24154 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24157 if (Extract->getValueType(0) != MVT::i32)
24159 if (!Extract->hasOneUse())
24161 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24162 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24164 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24167 // Record which element was extracted.
24168 ExtractedElements |=
24169 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24171 Uses.push_back(Extract);
24174 // If not all the elements were used, this may not be worthwhile.
24175 if (ExtractedElements != 15)
24178 // Ok, we've now decided to do the transformation.
24179 // If 64-bit shifts are legal, use the extract-shift sequence,
24180 // otherwise bounce the vector off the cache.
24181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24184 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24185 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24186 auto &DL = DAG.getDataLayout();
24187 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24188 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24189 DAG.getConstant(0, dl, VecIdxTy));
24190 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24191 DAG.getConstant(1, dl, VecIdxTy));
24193 SDValue ShAmt = DAG.getConstant(
24194 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24195 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24196 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24197 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24198 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24199 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24200 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24202 // Store the value to a temporary stack slot.
24203 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24204 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24205 MachinePointerInfo(), false, false, 0);
24207 EVT ElementType = InputVector.getValueType().getVectorElementType();
24208 unsigned EltSize = ElementType.getSizeInBits() / 8;
24210 // Replace each use (extract) with a load of the appropriate element.
24211 for (unsigned i = 0; i < 4; ++i) {
24212 uint64_t Offset = EltSize * i;
24213 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24214 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24216 SDValue ScalarAddr =
24217 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24219 // Load the scalar.
24220 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24221 ScalarAddr, MachinePointerInfo(),
24222 false, false, false, 0);
24227 // Replace the extracts
24228 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24229 UE = Uses.end(); UI != UE; ++UI) {
24230 SDNode *Extract = *UI;
24232 SDValue Idx = Extract->getOperand(1);
24233 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24234 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24237 // The replacement was made in place; don't return anything.
24242 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24243 const X86Subtarget *Subtarget) {
24245 SDValue Cond = N->getOperand(0);
24246 SDValue LHS = N->getOperand(1);
24247 SDValue RHS = N->getOperand(2);
24249 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24250 SDValue CondSrc = Cond->getOperand(0);
24251 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24252 Cond = CondSrc->getOperand(0);
24255 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24258 // A vselect where all conditions and data are constants can be optimized into
24259 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24260 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24261 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24264 unsigned MaskValue = 0;
24265 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24268 MVT VT = N->getSimpleValueType(0);
24269 unsigned NumElems = VT.getVectorNumElements();
24270 SmallVector<int, 8> ShuffleMask(NumElems, -1);
24271 for (unsigned i = 0; i < NumElems; ++i) {
24272 // Be sure we emit undef where we can.
24273 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24274 ShuffleMask[i] = -1;
24276 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24280 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24282 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24285 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24287 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24288 TargetLowering::DAGCombinerInfo &DCI,
24289 const X86Subtarget *Subtarget) {
24291 SDValue Cond = N->getOperand(0);
24292 // Get the LHS/RHS of the select.
24293 SDValue LHS = N->getOperand(1);
24294 SDValue RHS = N->getOperand(2);
24295 EVT VT = LHS.getValueType();
24296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24298 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24299 // instructions match the semantics of the common C idiom x<y?x:y but not
24300 // x<=y?x:y, because of how they handle negative zero (which can be
24301 // ignored in unsafe-math mode).
24302 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24303 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24304 VT != MVT::f80 && VT != MVT::f128 &&
24305 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24306 (Subtarget->hasSSE2() ||
24307 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24308 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24310 unsigned Opcode = 0;
24311 // Check for x CC y ? x : y.
24312 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24313 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24317 // Converting this to a min would handle NaNs incorrectly, and swapping
24318 // the operands would cause it to handle comparisons between positive
24319 // and negative zero incorrectly.
24320 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24321 if (!DAG.getTarget().Options.UnsafeFPMath &&
24322 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24324 std::swap(LHS, RHS);
24326 Opcode = X86ISD::FMIN;
24329 // Converting this to a min would handle comparisons between positive
24330 // and negative zero incorrectly.
24331 if (!DAG.getTarget().Options.UnsafeFPMath &&
24332 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24334 Opcode = X86ISD::FMIN;
24337 // Converting this to a min would handle both negative zeros and NaNs
24338 // incorrectly, but we can swap the operands to fix both.
24339 std::swap(LHS, RHS);
24343 Opcode = X86ISD::FMIN;
24347 // Converting this to a max would handle comparisons between positive
24348 // and negative zero incorrectly.
24349 if (!DAG.getTarget().Options.UnsafeFPMath &&
24350 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24352 Opcode = X86ISD::FMAX;
24355 // Converting this to a max would handle NaNs incorrectly, and swapping
24356 // the operands would cause it to handle comparisons between positive
24357 // and negative zero incorrectly.
24358 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24359 if (!DAG.getTarget().Options.UnsafeFPMath &&
24360 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24362 std::swap(LHS, RHS);
24364 Opcode = X86ISD::FMAX;
24367 // Converting this to a max would handle both negative zeros and NaNs
24368 // incorrectly, but we can swap the operands to fix both.
24369 std::swap(LHS, RHS);
24373 Opcode = X86ISD::FMAX;
24376 // Check for x CC y ? y : x -- a min/max with reversed arms.
24377 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24378 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24382 // Converting this to a min would handle comparisons between positive
24383 // and negative zero incorrectly, and swapping the operands would
24384 // cause it to handle NaNs incorrectly.
24385 if (!DAG.getTarget().Options.UnsafeFPMath &&
24386 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24387 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24389 std::swap(LHS, RHS);
24391 Opcode = X86ISD::FMIN;
24394 // Converting this to a min would handle NaNs incorrectly.
24395 if (!DAG.getTarget().Options.UnsafeFPMath &&
24396 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24398 Opcode = X86ISD::FMIN;
24401 // Converting this to a min would handle both negative zeros and NaNs
24402 // incorrectly, but we can swap the operands to fix both.
24403 std::swap(LHS, RHS);
24407 Opcode = X86ISD::FMIN;
24411 // Converting this to a max would handle NaNs incorrectly.
24412 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24414 Opcode = X86ISD::FMAX;
24417 // Converting this to a max would handle comparisons between positive
24418 // and negative zero incorrectly, and swapping the operands would
24419 // cause it to handle NaNs incorrectly.
24420 if (!DAG.getTarget().Options.UnsafeFPMath &&
24421 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24422 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24424 std::swap(LHS, RHS);
24426 Opcode = X86ISD::FMAX;
24429 // Converting this to a max would handle both negative zeros and NaNs
24430 // incorrectly, but we can swap the operands to fix both.
24431 std::swap(LHS, RHS);
24435 Opcode = X86ISD::FMAX;
24441 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24444 EVT CondVT = Cond.getValueType();
24445 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24446 CondVT.getVectorElementType() == MVT::i1) {
24447 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24448 // lowering on KNL. In this case we convert it to
24449 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24450 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24451 // Since SKX these selects have a proper lowering.
24452 EVT OpVT = LHS.getValueType();
24453 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24454 (OpVT.getVectorElementType() == MVT::i8 ||
24455 OpVT.getVectorElementType() == MVT::i16) &&
24456 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24457 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24458 DCI.AddToWorklist(Cond.getNode());
24459 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24462 // If this is a select between two integer constants, try to do some
24464 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24465 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24466 // Don't do this for crazy integer types.
24467 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24468 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24469 // so that TrueC (the true value) is larger than FalseC.
24470 bool NeedsCondInvert = false;
24472 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24473 // Efficiently invertible.
24474 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24475 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24476 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24477 NeedsCondInvert = true;
24478 std::swap(TrueC, FalseC);
24481 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24482 if (FalseC->getAPIntValue() == 0 &&
24483 TrueC->getAPIntValue().isPowerOf2()) {
24484 if (NeedsCondInvert) // Invert the condition if needed.
24485 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24486 DAG.getConstant(1, DL, Cond.getValueType()));
24488 // Zero extend the condition if needed.
24489 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24491 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24492 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24493 DAG.getConstant(ShAmt, DL, MVT::i8));
24496 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24497 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24498 if (NeedsCondInvert) // Invert the condition if needed.
24499 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24500 DAG.getConstant(1, DL, Cond.getValueType()));
24502 // Zero extend the condition if needed.
24503 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24504 FalseC->getValueType(0), Cond);
24505 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24506 SDValue(FalseC, 0));
24509 // Optimize cases that will turn into an LEA instruction. This requires
24510 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24511 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24512 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24513 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24515 bool isFastMultiplier = false;
24517 switch ((unsigned char)Diff) {
24519 case 1: // result = add base, cond
24520 case 2: // result = lea base( , cond*2)
24521 case 3: // result = lea base(cond, cond*2)
24522 case 4: // result = lea base( , cond*4)
24523 case 5: // result = lea base(cond, cond*4)
24524 case 8: // result = lea base( , cond*8)
24525 case 9: // result = lea base(cond, cond*8)
24526 isFastMultiplier = true;
24531 if (isFastMultiplier) {
24532 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24533 if (NeedsCondInvert) // Invert the condition if needed.
24534 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24535 DAG.getConstant(1, DL, Cond.getValueType()));
24537 // Zero extend the condition if needed.
24538 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24540 // Scale the condition by the difference.
24542 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24543 DAG.getConstant(Diff, DL,
24544 Cond.getValueType()));
24546 // Add the base if non-zero.
24547 if (FalseC->getAPIntValue() != 0)
24548 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24549 SDValue(FalseC, 0));
24556 // Canonicalize max and min:
24557 // (x > y) ? x : y -> (x >= y) ? x : y
24558 // (x < y) ? x : y -> (x <= y) ? x : y
24559 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24560 // the need for an extra compare
24561 // against zero. e.g.
24562 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24564 // testl %edi, %edi
24566 // cmovgl %edi, %eax
24570 // cmovsl %eax, %edi
24571 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24572 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24573 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24574 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24579 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24580 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24581 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24582 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24587 // Early exit check
24588 if (!TLI.isTypeLegal(VT))
24591 // Match VSELECTs into subs with unsigned saturation.
24592 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24593 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24594 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24595 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24596 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24598 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24599 // left side invert the predicate to simplify logic below.
24601 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24603 CC = ISD::getSetCCInverse(CC, true);
24604 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24608 if (Other.getNode() && Other->getNumOperands() == 2 &&
24609 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24610 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24611 SDValue CondRHS = Cond->getOperand(1);
24613 // Look for a general sub with unsigned saturation first.
24614 // x >= y ? x-y : 0 --> subus x, y
24615 // x > y ? x-y : 0 --> subus x, y
24616 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24617 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24618 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24620 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24621 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24622 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24623 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24624 // If the RHS is a constant we have to reverse the const
24625 // canonicalization.
24626 // x > C-1 ? x+-C : 0 --> subus x, C
24627 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24628 CondRHSConst->getAPIntValue() ==
24629 (-OpRHSConst->getAPIntValue() - 1))
24630 return DAG.getNode(
24631 X86ISD::SUBUS, DL, VT, OpLHS,
24632 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24634 // Another special case: If C was a sign bit, the sub has been
24635 // canonicalized into a xor.
24636 // FIXME: Would it be better to use computeKnownBits to determine
24637 // whether it's safe to decanonicalize the xor?
24638 // x s< 0 ? x^C : 0 --> subus x, C
24639 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24640 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24641 OpRHSConst->getAPIntValue().isSignBit())
24642 // Note that we have to rebuild the RHS constant here to ensure we
24643 // don't rely on particular values of undef lanes.
24644 return DAG.getNode(
24645 X86ISD::SUBUS, DL, VT, OpLHS,
24646 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24651 // Simplify vector selection if condition value type matches vselect
24653 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24654 assert(Cond.getValueType().isVector() &&
24655 "vector select expects a vector selector!");
24657 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24658 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24660 // Try invert the condition if true value is not all 1s and false value
24662 if (!TValIsAllOnes && !FValIsAllZeros &&
24663 // Check if the selector will be produced by CMPP*/PCMP*
24664 Cond.getOpcode() == ISD::SETCC &&
24665 // Check if SETCC has already been promoted
24666 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24668 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24669 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24671 if (TValIsAllZeros || FValIsAllOnes) {
24672 SDValue CC = Cond.getOperand(2);
24673 ISD::CondCode NewCC =
24674 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24675 Cond.getOperand(0).getValueType().isInteger());
24676 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24677 std::swap(LHS, RHS);
24678 TValIsAllOnes = FValIsAllOnes;
24679 FValIsAllZeros = TValIsAllZeros;
24683 if (TValIsAllOnes || FValIsAllZeros) {
24686 if (TValIsAllOnes && FValIsAllZeros)
24688 else if (TValIsAllOnes)
24690 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24691 else if (FValIsAllZeros)
24692 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24693 DAG.getBitcast(CondVT, LHS));
24695 return DAG.getBitcast(VT, Ret);
24699 // We should generate an X86ISD::BLENDI from a vselect if its argument
24700 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24701 // constants. This specific pattern gets generated when we split a
24702 // selector for a 512 bit vector in a machine without AVX512 (but with
24703 // 256-bit vectors), during legalization:
24705 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24707 // Iff we find this pattern and the build_vectors are built from
24708 // constants, we translate the vselect into a shuffle_vector that we
24709 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24710 if ((N->getOpcode() == ISD::VSELECT ||
24711 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24712 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24713 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24714 if (Shuffle.getNode())
24718 // If this is a *dynamic* select (non-constant condition) and we can match
24719 // this node with one of the variable blend instructions, restructure the
24720 // condition so that the blends can use the high bit of each element and use
24721 // SimplifyDemandedBits to simplify the condition operand.
24722 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24723 !DCI.isBeforeLegalize() &&
24724 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24725 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24727 // Don't optimize vector selects that map to mask-registers.
24731 // We can only handle the cases where VSELECT is directly legal on the
24732 // subtarget. We custom lower VSELECT nodes with constant conditions and
24733 // this makes it hard to see whether a dynamic VSELECT will correctly
24734 // lower, so we both check the operation's status and explicitly handle the
24735 // cases where a *dynamic* blend will fail even though a constant-condition
24736 // blend could be custom lowered.
24737 // FIXME: We should find a better way to handle this class of problems.
24738 // Potentially, we should combine constant-condition vselect nodes
24739 // pre-legalization into shuffles and not mark as many types as custom
24741 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24743 // FIXME: We don't support i16-element blends currently. We could and
24744 // should support them by making *all* the bits in the condition be set
24745 // rather than just the high bit and using an i8-element blend.
24746 if (VT.getVectorElementType() == MVT::i16)
24748 // Dynamic blending was only available from SSE4.1 onward.
24749 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24751 // Byte blends are only available in AVX2
24752 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24755 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24756 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24758 APInt KnownZero, KnownOne;
24759 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24760 DCI.isBeforeLegalizeOps());
24761 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24762 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24764 // If we changed the computation somewhere in the DAG, this change
24765 // will affect all users of Cond.
24766 // Make sure it is fine and update all the nodes so that we do not
24767 // use the generic VSELECT anymore. Otherwise, we may perform
24768 // wrong optimizations as we messed up with the actual expectation
24769 // for the vector boolean values.
24770 if (Cond != TLO.Old) {
24771 // Check all uses of that condition operand to check whether it will be
24772 // consumed by non-BLEND instructions, which may depend on all bits are
24774 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24776 if (I->getOpcode() != ISD::VSELECT)
24777 // TODO: Add other opcodes eventually lowered into BLEND.
24780 // Update all the users of the condition, before committing the change,
24781 // so that the VSELECT optimizations that expect the correct vector
24782 // boolean value will not be triggered.
24783 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24785 DAG.ReplaceAllUsesOfValueWith(
24787 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24788 Cond, I->getOperand(1), I->getOperand(2)));
24789 DCI.CommitTargetLoweringOpt(TLO);
24792 // At this point, only Cond is changed. Change the condition
24793 // just for N to keep the opportunity to optimize all other
24794 // users their own way.
24795 DAG.ReplaceAllUsesOfValueWith(
24797 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24798 TLO.New, N->getOperand(1), N->getOperand(2)));
24806 // Check whether a boolean test is testing a boolean value generated by
24807 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24810 // Simplify the following patterns:
24811 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24812 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24813 // to (Op EFLAGS Cond)
24815 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24816 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24817 // to (Op EFLAGS !Cond)
24819 // where Op could be BRCOND or CMOV.
24821 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24822 // Quit if not CMP and SUB with its value result used.
24823 if (Cmp.getOpcode() != X86ISD::CMP &&
24824 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24827 // Quit if not used as a boolean value.
24828 if (CC != X86::COND_E && CC != X86::COND_NE)
24831 // Check CMP operands. One of them should be 0 or 1 and the other should be
24832 // an SetCC or extended from it.
24833 SDValue Op1 = Cmp.getOperand(0);
24834 SDValue Op2 = Cmp.getOperand(1);
24837 const ConstantSDNode* C = nullptr;
24838 bool needOppositeCond = (CC == X86::COND_E);
24839 bool checkAgainstTrue = false; // Is it a comparison against 1?
24841 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24843 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24845 else // Quit if all operands are not constants.
24848 if (C->getZExtValue() == 1) {
24849 needOppositeCond = !needOppositeCond;
24850 checkAgainstTrue = true;
24851 } else if (C->getZExtValue() != 0)
24852 // Quit if the constant is neither 0 or 1.
24855 bool truncatedToBoolWithAnd = false;
24856 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24857 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24858 SetCC.getOpcode() == ISD::TRUNCATE ||
24859 SetCC.getOpcode() == ISD::AND) {
24860 if (SetCC.getOpcode() == ISD::AND) {
24862 if (isOneConstant(SetCC.getOperand(0)))
24864 if (isOneConstant(SetCC.getOperand(1)))
24868 SetCC = SetCC.getOperand(OpIdx);
24869 truncatedToBoolWithAnd = true;
24871 SetCC = SetCC.getOperand(0);
24874 switch (SetCC.getOpcode()) {
24875 case X86ISD::SETCC_CARRY:
24876 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24877 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24878 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24879 // truncated to i1 using 'and'.
24880 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24882 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24883 "Invalid use of SETCC_CARRY!");
24885 case X86ISD::SETCC:
24886 // Set the condition code or opposite one if necessary.
24887 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24888 if (needOppositeCond)
24889 CC = X86::GetOppositeBranchCondition(CC);
24890 return SetCC.getOperand(1);
24891 case X86ISD::CMOV: {
24892 // Check whether false/true value has canonical one, i.e. 0 or 1.
24893 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24894 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24895 // Quit if true value is not a constant.
24898 // Quit if false value is not a constant.
24900 SDValue Op = SetCC.getOperand(0);
24901 // Skip 'zext' or 'trunc' node.
24902 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24903 Op.getOpcode() == ISD::TRUNCATE)
24904 Op = Op.getOperand(0);
24905 // A special case for rdrand/rdseed, where 0 is set if false cond is
24907 if ((Op.getOpcode() != X86ISD::RDRAND &&
24908 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24911 // Quit if false value is not the constant 0 or 1.
24912 bool FValIsFalse = true;
24913 if (FVal && FVal->getZExtValue() != 0) {
24914 if (FVal->getZExtValue() != 1)
24916 // If FVal is 1, opposite cond is needed.
24917 needOppositeCond = !needOppositeCond;
24918 FValIsFalse = false;
24920 // Quit if TVal is not the constant opposite of FVal.
24921 if (FValIsFalse && TVal->getZExtValue() != 1)
24923 if (!FValIsFalse && TVal->getZExtValue() != 0)
24925 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24926 if (needOppositeCond)
24927 CC = X86::GetOppositeBranchCondition(CC);
24928 return SetCC.getOperand(3);
24935 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24937 /// (X86or (X86setcc) (X86setcc))
24938 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24939 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24940 X86::CondCode &CC1, SDValue &Flags,
24942 if (Cond->getOpcode() == X86ISD::CMP) {
24943 if (!isNullConstant(Cond->getOperand(1)))
24946 Cond = Cond->getOperand(0);
24951 SDValue SetCC0, SetCC1;
24952 switch (Cond->getOpcode()) {
24953 default: return false;
24960 SetCC0 = Cond->getOperand(0);
24961 SetCC1 = Cond->getOperand(1);
24965 // Make sure we have SETCC nodes, using the same flags value.
24966 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24967 SetCC1.getOpcode() != X86ISD::SETCC ||
24968 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24971 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24972 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24973 Flags = SetCC0->getOperand(1);
24977 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24978 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24979 TargetLowering::DAGCombinerInfo &DCI,
24980 const X86Subtarget *Subtarget) {
24983 // If the flag operand isn't dead, don't touch this CMOV.
24984 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24987 SDValue FalseOp = N->getOperand(0);
24988 SDValue TrueOp = N->getOperand(1);
24989 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24990 SDValue Cond = N->getOperand(3);
24992 if (CC == X86::COND_E || CC == X86::COND_NE) {
24993 switch (Cond.getOpcode()) {
24997 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24998 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24999 return (CC == X86::COND_E) ? FalseOp : TrueOp;
25005 Flags = checkBoolTestSetCCCombine(Cond, CC);
25006 if (Flags.getNode() &&
25007 // Extra check as FCMOV only supports a subset of X86 cond.
25008 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
25009 SDValue Ops[] = { FalseOp, TrueOp,
25010 DAG.getConstant(CC, DL, MVT::i8), Flags };
25011 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25014 // If this is a select between two integer constants, try to do some
25015 // optimizations. Note that the operands are ordered the opposite of SELECT
25017 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
25018 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
25019 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
25020 // larger than FalseC (the false value).
25021 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
25022 CC = X86::GetOppositeBranchCondition(CC);
25023 std::swap(TrueC, FalseC);
25024 std::swap(TrueOp, FalseOp);
25027 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
25028 // This is efficient for any integer data type (including i8/i16) and
25030 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
25031 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25032 DAG.getConstant(CC, DL, MVT::i8), Cond);
25034 // Zero extend the condition if needed.
25035 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25037 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25038 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25039 DAG.getConstant(ShAmt, DL, MVT::i8));
25040 if (N->getNumValues() == 2) // Dead flag value?
25041 return DCI.CombineTo(N, Cond, SDValue());
25045 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
25046 // for any integer data type, including i8/i16.
25047 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25048 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25049 DAG.getConstant(CC, DL, MVT::i8), Cond);
25051 // Zero extend the condition if needed.
25052 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25053 FalseC->getValueType(0), Cond);
25054 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25055 SDValue(FalseC, 0));
25057 if (N->getNumValues() == 2) // Dead flag value?
25058 return DCI.CombineTo(N, Cond, SDValue());
25062 // Optimize cases that will turn into an LEA instruction. This requires
25063 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25064 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25065 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25066 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25068 bool isFastMultiplier = false;
25070 switch ((unsigned char)Diff) {
25072 case 1: // result = add base, cond
25073 case 2: // result = lea base( , cond*2)
25074 case 3: // result = lea base(cond, cond*2)
25075 case 4: // result = lea base( , cond*4)
25076 case 5: // result = lea base(cond, cond*4)
25077 case 8: // result = lea base( , cond*8)
25078 case 9: // result = lea base(cond, cond*8)
25079 isFastMultiplier = true;
25084 if (isFastMultiplier) {
25085 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25086 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25087 DAG.getConstant(CC, DL, MVT::i8), Cond);
25088 // Zero extend the condition if needed.
25089 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25091 // Scale the condition by the difference.
25093 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25094 DAG.getConstant(Diff, DL, Cond.getValueType()));
25096 // Add the base if non-zero.
25097 if (FalseC->getAPIntValue() != 0)
25098 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25099 SDValue(FalseC, 0));
25100 if (N->getNumValues() == 2) // Dead flag value?
25101 return DCI.CombineTo(N, Cond, SDValue());
25108 // Handle these cases:
25109 // (select (x != c), e, c) -> select (x != c), e, x),
25110 // (select (x == c), c, e) -> select (x == c), x, e)
25111 // where the c is an integer constant, and the "select" is the combination
25112 // of CMOV and CMP.
25114 // The rationale for this change is that the conditional-move from a constant
25115 // needs two instructions, however, conditional-move from a register needs
25116 // only one instruction.
25118 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25119 // some instruction-combining opportunities. This opt needs to be
25120 // postponed as late as possible.
25122 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25123 // the DCI.xxxx conditions are provided to postpone the optimization as
25124 // late as possible.
25126 ConstantSDNode *CmpAgainst = nullptr;
25127 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25128 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25129 !isa<ConstantSDNode>(Cond.getOperand(0))) {
25131 if (CC == X86::COND_NE &&
25132 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25133 CC = X86::GetOppositeBranchCondition(CC);
25134 std::swap(TrueOp, FalseOp);
25137 if (CC == X86::COND_E &&
25138 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25139 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25140 DAG.getConstant(CC, DL, MVT::i8), Cond };
25141 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25146 // Fold and/or of setcc's to double CMOV:
25147 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25148 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25150 // This combine lets us generate:
25151 // cmovcc1 (jcc1 if we don't have CMOV)
25157 // cmovne (jne if we don't have CMOV)
25158 // When we can't use the CMOV instruction, it might increase branch
25160 // When we can use CMOV, or when there is no mispredict, this improves
25161 // throughput and reduces register pressure.
25163 if (CC == X86::COND_NE) {
25165 X86::CondCode CC0, CC1;
25167 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25169 std::swap(FalseOp, TrueOp);
25170 CC0 = X86::GetOppositeBranchCondition(CC0);
25171 CC1 = X86::GetOppositeBranchCondition(CC1);
25174 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25176 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25177 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25178 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25179 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25187 /// PerformMulCombine - Optimize a single multiply with constant into two
25188 /// in order to implement it with two cheaper instructions, e.g.
25189 /// LEA + SHL, LEA + LEA.
25190 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25191 TargetLowering::DAGCombinerInfo &DCI) {
25192 // An imul is usually smaller than the alternative sequence.
25193 if (DAG.getMachineFunction().getFunction()->optForMinSize())
25196 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25199 EVT VT = N->getValueType(0);
25200 if (VT != MVT::i64 && VT != MVT::i32)
25203 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25206 uint64_t MulAmt = C->getZExtValue();
25207 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25210 uint64_t MulAmt1 = 0;
25211 uint64_t MulAmt2 = 0;
25212 if ((MulAmt % 9) == 0) {
25214 MulAmt2 = MulAmt / 9;
25215 } else if ((MulAmt % 5) == 0) {
25217 MulAmt2 = MulAmt / 5;
25218 } else if ((MulAmt % 3) == 0) {
25220 MulAmt2 = MulAmt / 3;
25226 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25228 if (isPowerOf2_64(MulAmt2) &&
25229 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25230 // If second multiplifer is pow2, issue it first. We want the multiply by
25231 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25233 std::swap(MulAmt1, MulAmt2);
25235 if (isPowerOf2_64(MulAmt1))
25236 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25237 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25239 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25240 DAG.getConstant(MulAmt1, DL, VT));
25242 if (isPowerOf2_64(MulAmt2))
25243 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25244 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25246 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25247 DAG.getConstant(MulAmt2, DL, VT));
25251 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25252 && "Both cases that could cause potential overflows should have "
25253 "already been handled.");
25254 if (isPowerOf2_64(MulAmt - 1))
25255 // (mul x, 2^N + 1) => (add (shl x, N), x)
25256 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25257 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25258 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25261 else if (isPowerOf2_64(MulAmt + 1))
25262 // (mul x, 2^N - 1) => (sub (shl x, N), x)
25263 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25265 DAG.getConstant(Log2_64(MulAmt + 1),
25266 DL, MVT::i8)), N->getOperand(0));
25270 // Do not add new nodes to DAG combiner worklist.
25271 DCI.CombineTo(N, NewMul, false);
25276 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25277 SDValue N0 = N->getOperand(0);
25278 SDValue N1 = N->getOperand(1);
25279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25280 EVT VT = N0.getValueType();
25282 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25283 // since the result of setcc_c is all zero's or all ones.
25284 if (VT.isInteger() && !VT.isVector() &&
25285 N1C && N0.getOpcode() == ISD::AND &&
25286 N0.getOperand(1).getOpcode() == ISD::Constant) {
25287 SDValue N00 = N0.getOperand(0);
25288 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25289 APInt ShAmt = N1C->getAPIntValue();
25290 Mask = Mask.shl(ShAmt);
25291 bool MaskOK = false;
25292 // We can handle cases concerning bit-widening nodes containing setcc_c if
25293 // we carefully interrogate the mask to make sure we are semantics
25295 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25296 // of the underlying setcc_c operation if the setcc_c was zero extended.
25297 // Consider the following example:
25298 // zext(setcc_c) -> i32 0x0000FFFF
25299 // c1 -> i32 0x0000FFFF
25300 // c2 -> i32 0x00000001
25301 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25302 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
25303 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25305 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25306 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25308 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25309 N00.getOpcode() == ISD::ANY_EXTEND) &&
25310 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25311 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25313 if (MaskOK && Mask != 0) {
25315 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25319 // Hardware support for vector shifts is sparse which makes us scalarize the
25320 // vector operations in many cases. Also, on sandybridge ADD is faster than
25322 // (shl V, 1) -> add V,V
25323 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25324 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25325 assert(N0.getValueType().isVector() && "Invalid vector shift type");
25326 // We shift all of the values by one. In many cases we do not have
25327 // hardware support for this operation. This is better expressed as an ADD
25329 if (N1SplatC->getAPIntValue() == 1)
25330 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25336 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25337 SDValue N0 = N->getOperand(0);
25338 SDValue N1 = N->getOperand(1);
25339 EVT VT = N0.getValueType();
25340 unsigned Size = VT.getSizeInBits();
25342 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25343 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25344 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25345 // depending on sign of (SarConst - [56,48,32,24,16])
25347 // sexts in X86 are MOVs. The MOVs have the same code size
25348 // as above SHIFTs (only SHIFT on 1 has lower code size).
25349 // However the MOVs have 2 advantages to a SHIFT:
25350 // 1. MOVs can write to a register that differs from source
25351 // 2. MOVs accept memory operands
25353 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25354 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25355 N0.getOperand(1).getOpcode() != ISD::Constant)
25358 SDValue N00 = N0.getOperand(0);
25359 SDValue N01 = N0.getOperand(1);
25360 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25361 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25362 EVT CVT = N1.getValueType();
25364 if (SarConst.isNegative())
25367 for (MVT SVT : MVT::integer_valuetypes()) {
25368 unsigned ShiftSize = SVT.getSizeInBits();
25369 // skipping types without corresponding sext/zext and
25370 // ShlConst that is not one of [56,48,32,24,16]
25371 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25375 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25376 SarConst = SarConst - (Size - ShiftSize);
25379 else if (SarConst.isNegative())
25380 return DAG.getNode(ISD::SHL, DL, VT, NN,
25381 DAG.getConstant(-SarConst, DL, CVT));
25383 return DAG.getNode(ISD::SRA, DL, VT, NN,
25384 DAG.getConstant(SarConst, DL, CVT));
25389 /// \brief Returns a vector of 0s if the node in input is a vector logical
25390 /// shift by a constant amount which is known to be bigger than or equal
25391 /// to the vector element size in bits.
25392 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25393 const X86Subtarget *Subtarget) {
25394 EVT VT = N->getValueType(0);
25396 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25397 (!Subtarget->hasInt256() ||
25398 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25401 SDValue Amt = N->getOperand(1);
25403 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25404 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25405 APInt ShiftAmt = AmtSplat->getAPIntValue();
25406 unsigned MaxAmount =
25407 VT.getSimpleVT().getVectorElementType().getSizeInBits();
25409 // SSE2/AVX2 logical shifts always return a vector of 0s
25410 // if the shift amount is bigger than or equal to
25411 // the element size. The constant shift amount will be
25412 // encoded as a 8-bit immediate.
25413 if (ShiftAmt.trunc(8).uge(MaxAmount))
25414 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25420 /// PerformShiftCombine - Combine shifts.
25421 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25422 TargetLowering::DAGCombinerInfo &DCI,
25423 const X86Subtarget *Subtarget) {
25424 if (N->getOpcode() == ISD::SHL)
25425 if (SDValue V = PerformSHLCombine(N, DAG))
25428 if (N->getOpcode() == ISD::SRA)
25429 if (SDValue V = PerformSRACombine(N, DAG))
25432 // Try to fold this logical shift into a zero vector.
25433 if (N->getOpcode() != ISD::SRA)
25434 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25440 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
25441 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25442 // and friends. Likewise for OR -> CMPNEQSS.
25443 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25444 TargetLowering::DAGCombinerInfo &DCI,
25445 const X86Subtarget *Subtarget) {
25448 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25449 // we're requiring SSE2 for both.
25450 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25451 SDValue N0 = N->getOperand(0);
25452 SDValue N1 = N->getOperand(1);
25453 SDValue CMP0 = N0->getOperand(1);
25454 SDValue CMP1 = N1->getOperand(1);
25457 // The SETCCs should both refer to the same CMP.
25458 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25461 SDValue CMP00 = CMP0->getOperand(0);
25462 SDValue CMP01 = CMP0->getOperand(1);
25463 EVT VT = CMP00.getValueType();
25465 if (VT == MVT::f32 || VT == MVT::f64) {
25466 bool ExpectingFlags = false;
25467 // Check for any users that want flags:
25468 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25469 !ExpectingFlags && UI != UE; ++UI)
25470 switch (UI->getOpcode()) {
25475 ExpectingFlags = true;
25477 case ISD::CopyToReg:
25478 case ISD::SIGN_EXTEND:
25479 case ISD::ZERO_EXTEND:
25480 case ISD::ANY_EXTEND:
25484 if (!ExpectingFlags) {
25485 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25486 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25488 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25489 X86::CondCode tmp = cc0;
25494 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
25495 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25496 // FIXME: need symbolic constants for these magic numbers.
25497 // See X86ATTInstPrinter.cpp:printSSECC().
25498 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25499 if (Subtarget->hasAVX512()) {
25500 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25502 DAG.getConstant(x86cc, DL, MVT::i8));
25503 if (N->getValueType(0) != MVT::i1)
25504 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25508 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25509 CMP00.getValueType(), CMP00, CMP01,
25510 DAG.getConstant(x86cc, DL,
25513 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25514 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25516 if (is64BitFP && !Subtarget->is64Bit()) {
25517 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25518 // 64-bit integer, since that's not a legal type. Since
25519 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25520 // bits, but can do this little dance to extract the lowest 32 bits
25521 // and work with those going forward.
25522 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25524 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25525 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25526 Vector32, DAG.getIntPtrConstant(0, DL));
25530 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25531 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25532 DAG.getConstant(1, DL, IntVT));
25533 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25535 return OneBitOfTruth;
25543 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25544 /// so it can be folded inside ANDNP.
25545 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25546 EVT VT = N->getValueType(0);
25548 // Match direct AllOnes for 128 and 256-bit vectors
25549 if (ISD::isBuildVectorAllOnes(N))
25552 // Look through a bit convert.
25553 if (N->getOpcode() == ISD::BITCAST)
25554 N = N->getOperand(0).getNode();
25556 // Sometimes the operand may come from a insert_subvector building a 256-bit
25558 if (VT.is256BitVector() &&
25559 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25560 SDValue V1 = N->getOperand(0);
25561 SDValue V2 = N->getOperand(1);
25563 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25564 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25565 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25566 ISD::isBuildVectorAllOnes(V2.getNode()))
25573 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25574 // register. In most cases we actually compare or select YMM-sized registers
25575 // and mixing the two types creates horrible code. This method optimizes
25576 // some of the transition sequences.
25577 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25578 TargetLowering::DAGCombinerInfo &DCI,
25579 const X86Subtarget *Subtarget) {
25580 EVT VT = N->getValueType(0);
25581 if (!VT.is256BitVector())
25584 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25585 N->getOpcode() == ISD::ZERO_EXTEND ||
25586 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25588 SDValue Narrow = N->getOperand(0);
25589 EVT NarrowVT = Narrow->getValueType(0);
25590 if (!NarrowVT.is128BitVector())
25593 if (Narrow->getOpcode() != ISD::XOR &&
25594 Narrow->getOpcode() != ISD::AND &&
25595 Narrow->getOpcode() != ISD::OR)
25598 SDValue N0 = Narrow->getOperand(0);
25599 SDValue N1 = Narrow->getOperand(1);
25602 // The Left side has to be a trunc.
25603 if (N0.getOpcode() != ISD::TRUNCATE)
25606 // The type of the truncated inputs.
25607 EVT WideVT = N0->getOperand(0)->getValueType(0);
25611 // The right side has to be a 'trunc' or a constant vector.
25612 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25613 ConstantSDNode *RHSConstSplat = nullptr;
25614 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25615 RHSConstSplat = RHSBV->getConstantSplatNode();
25616 if (!RHSTrunc && !RHSConstSplat)
25619 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25621 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25624 // Set N0 and N1 to hold the inputs to the new wide operation.
25625 N0 = N0->getOperand(0);
25626 if (RHSConstSplat) {
25627 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25628 SDValue(RHSConstSplat, 0));
25629 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25630 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25631 } else if (RHSTrunc) {
25632 N1 = N1->getOperand(0);
25635 // Generate the wide operation.
25636 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25637 unsigned Opcode = N->getOpcode();
25639 case ISD::ANY_EXTEND:
25641 case ISD::ZERO_EXTEND: {
25642 unsigned InBits = NarrowVT.getScalarSizeInBits();
25643 APInt Mask = APInt::getAllOnesValue(InBits);
25644 Mask = Mask.zext(VT.getScalarSizeInBits());
25645 return DAG.getNode(ISD::AND, DL, VT,
25646 Op, DAG.getConstant(Mask, DL, VT));
25648 case ISD::SIGN_EXTEND:
25649 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25650 Op, DAG.getValueType(NarrowVT));
25652 llvm_unreachable("Unexpected opcode");
25656 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25657 TargetLowering::DAGCombinerInfo &DCI,
25658 const X86Subtarget *Subtarget) {
25659 SDValue N0 = N->getOperand(0);
25660 SDValue N1 = N->getOperand(1);
25663 // A vector zext_in_reg may be represented as a shuffle,
25664 // feeding into a bitcast (this represents anyext) feeding into
25665 // an and with a mask.
25666 // We'd like to try to combine that into a shuffle with zero
25667 // plus a bitcast, removing the and.
25668 if (N0.getOpcode() != ISD::BITCAST ||
25669 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25672 // The other side of the AND should be a splat of 2^C, where C
25673 // is the number of bits in the source type.
25674 if (N1.getOpcode() == ISD::BITCAST)
25675 N1 = N1.getOperand(0);
25676 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25678 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25680 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25681 EVT SrcType = Shuffle->getValueType(0);
25683 // We expect a single-source shuffle
25684 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25687 unsigned SrcSize = SrcType.getScalarSizeInBits();
25689 APInt SplatValue, SplatUndef;
25690 unsigned SplatBitSize;
25692 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25693 SplatBitSize, HasAnyUndefs))
25696 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25697 // Make sure the splat matches the mask we expect
25698 if (SplatBitSize > ResSize ||
25699 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25702 // Make sure the input and output size make sense
25703 if (SrcSize >= ResSize || ResSize % SrcSize)
25706 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25707 // The number of u's between each two values depends on the ratio between
25708 // the source and dest type.
25709 unsigned ZextRatio = ResSize / SrcSize;
25710 bool IsZext = true;
25711 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25712 if (i % ZextRatio) {
25713 if (Shuffle->getMaskElt(i) > 0) {
25719 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25720 // Expected element number
25730 // Ok, perform the transformation - replace the shuffle with
25731 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25732 // (instead of undef) where the k elements come from the zero vector.
25733 SmallVector<int, 8> Mask;
25734 unsigned NumElems = SrcType.getVectorNumElements();
25735 for (unsigned i = 0; i < NumElems; ++i)
25737 Mask.push_back(NumElems);
25739 Mask.push_back(i / ZextRatio);
25741 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25742 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25743 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25746 /// If both input operands of a logic op are being cast from floating point
25747 /// types, try to convert this into a floating point logic node to avoid
25748 /// unnecessary moves from SSE to integer registers.
25749 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25750 const X86Subtarget *Subtarget) {
25751 unsigned FPOpcode = ISD::DELETED_NODE;
25752 if (N->getOpcode() == ISD::AND)
25753 FPOpcode = X86ISD::FAND;
25754 else if (N->getOpcode() == ISD::OR)
25755 FPOpcode = X86ISD::FOR;
25756 else if (N->getOpcode() == ISD::XOR)
25757 FPOpcode = X86ISD::FXOR;
25759 assert(FPOpcode != ISD::DELETED_NODE &&
25760 "Unexpected input node for FP logic conversion");
25762 EVT VT = N->getValueType(0);
25763 SDValue N0 = N->getOperand(0);
25764 SDValue N1 = N->getOperand(1);
25766 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25767 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25768 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25769 SDValue N00 = N0.getOperand(0);
25770 SDValue N10 = N1.getOperand(0);
25771 EVT N00Type = N00.getValueType();
25772 EVT N10Type = N10.getValueType();
25773 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25774 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25775 return DAG.getBitcast(VT, FPLogic);
25781 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25782 TargetLowering::DAGCombinerInfo &DCI,
25783 const X86Subtarget *Subtarget) {
25784 if (DCI.isBeforeLegalizeOps())
25787 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25790 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25793 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25796 EVT VT = N->getValueType(0);
25797 SDValue N0 = N->getOperand(0);
25798 SDValue N1 = N->getOperand(1);
25801 // Create BEXTR instructions
25802 // BEXTR is ((X >> imm) & (2**size-1))
25803 if (VT == MVT::i32 || VT == MVT::i64) {
25804 // Check for BEXTR.
25805 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25806 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25807 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25808 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25809 if (MaskNode && ShiftNode) {
25810 uint64_t Mask = MaskNode->getZExtValue();
25811 uint64_t Shift = ShiftNode->getZExtValue();
25812 if (isMask_64(Mask)) {
25813 uint64_t MaskSize = countPopulation(Mask);
25814 if (Shift + MaskSize <= VT.getSizeInBits())
25815 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25816 DAG.getConstant(Shift | (MaskSize << 8), DL,
25825 // Want to form ANDNP nodes:
25826 // 1) In the hopes of then easily combining them with OR and AND nodes
25827 // to form PBLEND/PSIGN.
25828 // 2) To match ANDN packed intrinsics
25829 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25832 // Check LHS for vnot
25833 if (N0.getOpcode() == ISD::XOR &&
25834 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25835 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25836 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25838 // Check RHS for vnot
25839 if (N1.getOpcode() == ISD::XOR &&
25840 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25841 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25842 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25847 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25848 TargetLowering::DAGCombinerInfo &DCI,
25849 const X86Subtarget *Subtarget) {
25850 if (DCI.isBeforeLegalizeOps())
25853 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25856 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25859 SDValue N0 = N->getOperand(0);
25860 SDValue N1 = N->getOperand(1);
25861 EVT VT = N->getValueType(0);
25863 // look for psign/blend
25864 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25865 if (!Subtarget->hasSSSE3() ||
25866 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25869 // Canonicalize pandn to RHS
25870 if (N0.getOpcode() == X86ISD::ANDNP)
25872 // or (and (m, y), (pandn m, x))
25873 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25874 SDValue Mask = N1.getOperand(0);
25875 SDValue X = N1.getOperand(1);
25877 if (N0.getOperand(0) == Mask)
25878 Y = N0.getOperand(1);
25879 if (N0.getOperand(1) == Mask)
25880 Y = N0.getOperand(0);
25882 // Check to see if the mask appeared in both the AND and ANDNP and
25886 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25887 // Look through mask bitcast.
25888 if (Mask.getOpcode() == ISD::BITCAST)
25889 Mask = Mask.getOperand(0);
25890 if (X.getOpcode() == ISD::BITCAST)
25891 X = X.getOperand(0);
25892 if (Y.getOpcode() == ISD::BITCAST)
25893 Y = Y.getOperand(0);
25895 EVT MaskVT = Mask.getValueType();
25897 // Validate that the Mask operand is a vector sra node.
25898 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25899 // there is no psrai.b
25900 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25901 unsigned SraAmt = ~0;
25902 if (Mask.getOpcode() == ISD::SRA) {
25903 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25904 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25905 SraAmt = AmtConst->getZExtValue();
25906 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25907 SDValue SraC = Mask.getOperand(1);
25908 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25910 if ((SraAmt + 1) != EltBits)
25915 // Now we know we at least have a plendvb with the mask val. See if
25916 // we can form a psignb/w/d.
25917 // psign = x.type == y.type == mask.type && y = sub(0, x);
25918 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25919 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25920 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25921 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25922 "Unsupported VT for PSIGN");
25923 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25924 return DAG.getBitcast(VT, Mask);
25926 // PBLENDVB only available on SSE 4.1
25927 if (!Subtarget->hasSSE41())
25930 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25932 X = DAG.getBitcast(BlendVT, X);
25933 Y = DAG.getBitcast(BlendVT, Y);
25934 Mask = DAG.getBitcast(BlendVT, Mask);
25935 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25936 return DAG.getBitcast(VT, Mask);
25940 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25943 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25944 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25946 // SHLD/SHRD instructions have lower register pressure, but on some
25947 // platforms they have higher latency than the equivalent
25948 // series of shifts/or that would otherwise be generated.
25949 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25950 // have higher latencies and we are not optimizing for size.
25951 if (!OptForSize && Subtarget->isSHLDSlow())
25954 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25956 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25958 if (!N0.hasOneUse() || !N1.hasOneUse())
25961 SDValue ShAmt0 = N0.getOperand(1);
25962 if (ShAmt0.getValueType() != MVT::i8)
25964 SDValue ShAmt1 = N1.getOperand(1);
25965 if (ShAmt1.getValueType() != MVT::i8)
25967 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25968 ShAmt0 = ShAmt0.getOperand(0);
25969 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25970 ShAmt1 = ShAmt1.getOperand(0);
25973 unsigned Opc = X86ISD::SHLD;
25974 SDValue Op0 = N0.getOperand(0);
25975 SDValue Op1 = N1.getOperand(0);
25976 if (ShAmt0.getOpcode() == ISD::SUB) {
25977 Opc = X86ISD::SHRD;
25978 std::swap(Op0, Op1);
25979 std::swap(ShAmt0, ShAmt1);
25982 unsigned Bits = VT.getSizeInBits();
25983 if (ShAmt1.getOpcode() == ISD::SUB) {
25984 SDValue Sum = ShAmt1.getOperand(0);
25985 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25986 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25987 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25988 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25989 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25990 return DAG.getNode(Opc, DL, VT,
25992 DAG.getNode(ISD::TRUNCATE, DL,
25995 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25996 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25998 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25999 return DAG.getNode(Opc, DL, VT,
26000 N0.getOperand(0), N1.getOperand(0),
26001 DAG.getNode(ISD::TRUNCATE, DL,
26008 // Generate NEG and CMOV for integer abs.
26009 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
26010 EVT VT = N->getValueType(0);
26012 // Since X86 does not have CMOV for 8-bit integer, we don't convert
26013 // 8-bit integer abs to NEG and CMOV.
26014 if (VT.isInteger() && VT.getSizeInBits() == 8)
26017 SDValue N0 = N->getOperand(0);
26018 SDValue N1 = N->getOperand(1);
26021 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
26022 // and change it to SUB and CMOV.
26023 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
26024 N0.getOpcode() == ISD::ADD &&
26025 N0.getOperand(1) == N1 &&
26026 N1.getOpcode() == ISD::SRA &&
26027 N1.getOperand(0) == N0.getOperand(0))
26028 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
26029 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
26030 // Generate SUB & CMOV.
26031 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26032 DAG.getConstant(0, DL, VT), N0.getOperand(0));
26034 SDValue Ops[] = { N0.getOperand(0), Neg,
26035 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26036 SDValue(Neg.getNode(), 1) };
26037 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26042 // Try to turn tests against the signbit in the form of:
26043 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26046 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26047 // This is only worth doing if the output type is i8.
26048 if (N->getValueType(0) != MVT::i8)
26051 SDValue N0 = N->getOperand(0);
26052 SDValue N1 = N->getOperand(1);
26054 // We should be performing an xor against a truncated shift.
26055 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26058 // Make sure we are performing an xor against one.
26059 if (!isOneConstant(N1))
26062 // SetCC on x86 zero extends so only act on this if it's a logical shift.
26063 SDValue Shift = N0.getOperand(0);
26064 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26067 // Make sure we are truncating from one of i16, i32 or i64.
26068 EVT ShiftTy = Shift.getValueType();
26069 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26072 // Make sure the shift amount extracts the sign bit.
26073 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26074 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26077 // Create a greater-than comparison against -1.
26078 // N.B. Using SETGE against 0 works but we want a canonical looking
26079 // comparison, using SETGT matches up with what TranslateX86CC.
26081 SDValue ShiftOp = Shift.getOperand(0);
26082 EVT ShiftOpTy = ShiftOp.getValueType();
26083 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26084 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26088 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26089 TargetLowering::DAGCombinerInfo &DCI,
26090 const X86Subtarget *Subtarget) {
26091 if (DCI.isBeforeLegalizeOps())
26094 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26097 if (Subtarget->hasCMov())
26098 if (SDValue RV = performIntegerAbsCombine(N, DAG))
26101 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26107 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26108 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26109 /// X86ISD::AVG instruction.
26110 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26111 const X86Subtarget *Subtarget, SDLoc DL) {
26112 if (!VT.isVector() || !VT.isSimple())
26114 EVT InVT = In.getValueType();
26115 unsigned NumElems = VT.getVectorNumElements();
26117 EVT ScalarVT = VT.getVectorElementType();
26118 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26119 isPowerOf2_32(NumElems)))
26122 // InScalarVT is the intermediate type in AVG pattern and it should be greater
26123 // than the original input type (i8/i16).
26124 EVT InScalarVT = InVT.getVectorElementType();
26125 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26128 if (Subtarget->hasAVX512()) {
26129 if (VT.getSizeInBits() > 512)
26131 } else if (Subtarget->hasAVX2()) {
26132 if (VT.getSizeInBits() > 256)
26135 if (VT.getSizeInBits() > 128)
26139 // Detect the following pattern:
26141 // %1 = zext <N x i8> %a to <N x i32>
26142 // %2 = zext <N x i8> %b to <N x i32>
26143 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26144 // %4 = add nuw nsw <N x i32> %3, %2
26145 // %5 = lshr <N x i32> %N, <i32 1 x N>
26146 // %6 = trunc <N x i32> %5 to <N x i8>
26148 // In AVX512, the last instruction can also be a trunc store.
26150 if (In.getOpcode() != ISD::SRL)
26153 // A lambda checking the given SDValue is a constant vector and each element
26154 // is in the range [Min, Max].
26155 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26156 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26157 if (!BV || !BV->isConstant())
26159 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26160 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26163 uint64_t Val = C->getZExtValue();
26164 if (Val < Min || Val > Max)
26170 // Check if each element of the vector is left-shifted by one.
26171 auto LHS = In.getOperand(0);
26172 auto RHS = In.getOperand(1);
26173 if (!IsConstVectorInRange(RHS, 1, 1))
26175 if (LHS.getOpcode() != ISD::ADD)
26178 // Detect a pattern of a + b + 1 where the order doesn't matter.
26179 SDValue Operands[3];
26180 Operands[0] = LHS.getOperand(0);
26181 Operands[1] = LHS.getOperand(1);
26183 // Take care of the case when one of the operands is a constant vector whose
26184 // element is in the range [1, 256].
26185 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26186 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26187 Operands[0].getOperand(0).getValueType() == VT) {
26188 // The pattern is detected. Subtract one from the constant vector, then
26189 // demote it and emit X86ISD::AVG instruction.
26190 SDValue One = DAG.getConstant(1, DL, InScalarVT);
26191 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26192 SmallVector<SDValue, 8>(NumElems, One));
26193 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26194 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26195 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26199 if (Operands[0].getOpcode() == ISD::ADD)
26200 std::swap(Operands[0], Operands[1]);
26201 else if (Operands[1].getOpcode() != ISD::ADD)
26203 Operands[2] = Operands[1].getOperand(0);
26204 Operands[1] = Operands[1].getOperand(1);
26206 // Now we have three operands of two additions. Check that one of them is a
26207 // constant vector with ones, and the other two are promoted from i8/i16.
26208 for (int i = 0; i < 3; ++i) {
26209 if (!IsConstVectorInRange(Operands[i], 1, 1))
26211 std::swap(Operands[i], Operands[2]);
26213 // Check if Operands[0] and Operands[1] are results of type promotion.
26214 for (int j = 0; j < 2; ++j)
26215 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26216 Operands[j].getOperand(0).getValueType() != VT)
26219 // The pattern is detected, emit X86ISD::AVG instruction.
26220 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26221 Operands[1].getOperand(0));
26227 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26228 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26229 TargetLowering::DAGCombinerInfo &DCI,
26230 const X86Subtarget *Subtarget) {
26231 LoadSDNode *Ld = cast<LoadSDNode>(N);
26232 EVT RegVT = Ld->getValueType(0);
26233 EVT MemVT = Ld->getMemoryVT();
26235 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26237 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26238 // into two 16-byte operations.
26239 ISD::LoadExtType Ext = Ld->getExtensionType();
26241 unsigned AddressSpace = Ld->getAddressSpace();
26242 unsigned Alignment = Ld->getAlignment();
26243 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26244 Ext == ISD::NON_EXTLOAD &&
26245 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26246 AddressSpace, Alignment, &Fast) && !Fast) {
26247 unsigned NumElems = RegVT.getVectorNumElements();
26251 SDValue Ptr = Ld->getBasePtr();
26252 SDValue Increment =
26253 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26255 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26257 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26258 Ld->getPointerInfo(), Ld->isVolatile(),
26259 Ld->isNonTemporal(), Ld->isInvariant(),
26261 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26262 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26263 Ld->getPointerInfo(), Ld->isVolatile(),
26264 Ld->isNonTemporal(), Ld->isInvariant(),
26265 std::min(16U, Alignment));
26266 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26268 Load2.getValue(1));
26270 SDValue NewVec = DAG.getUNDEF(RegVT);
26271 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26272 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26273 return DCI.CombineTo(N, NewVec, TF, true);
26279 /// PerformMLOADCombine - Resolve extending loads
26280 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26281 TargetLowering::DAGCombinerInfo &DCI,
26282 const X86Subtarget *Subtarget) {
26283 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26284 if (Mld->getExtensionType() != ISD::SEXTLOAD)
26287 EVT VT = Mld->getValueType(0);
26288 unsigned NumElems = VT.getVectorNumElements();
26289 EVT LdVT = Mld->getMemoryVT();
26292 assert(LdVT != VT && "Cannot extend to the same type");
26293 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26294 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26295 // From, To sizes and ElemCount must be pow of two
26296 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26297 "Unexpected size for extending masked load");
26299 unsigned SizeRatio = ToSz / FromSz;
26300 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26302 // Create a type on which we perform the shuffle
26303 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26304 LdVT.getScalarType(), NumElems*SizeRatio);
26305 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26307 // Convert Src0 value
26308 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26309 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26310 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26311 for (unsigned i = 0; i != NumElems; ++i)
26312 ShuffleVec[i] = i * SizeRatio;
26314 // Can't shuffle using an illegal type.
26315 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26316 "WideVecVT should be legal");
26317 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26318 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26320 // Prepare the new mask
26322 SDValue Mask = Mld->getMask();
26323 if (Mask.getValueType() == VT) {
26324 // Mask and original value have the same type
26325 NewMask = DAG.getBitcast(WideVecVT, Mask);
26326 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26327 for (unsigned i = 0; i != NumElems; ++i)
26328 ShuffleVec[i] = i * SizeRatio;
26329 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26330 ShuffleVec[i] = NumElems * SizeRatio;
26331 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26332 DAG.getConstant(0, dl, WideVecVT),
26336 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26337 unsigned WidenNumElts = NumElems*SizeRatio;
26338 unsigned MaskNumElts = VT.getVectorNumElements();
26339 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26342 unsigned NumConcat = WidenNumElts / MaskNumElts;
26343 SmallVector<SDValue, 16> Ops(NumConcat);
26344 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26346 for (unsigned i = 1; i != NumConcat; ++i)
26349 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26352 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26353 Mld->getBasePtr(), NewMask, WideSrc0,
26354 Mld->getMemoryVT(), Mld->getMemOperand(),
26356 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26357 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26359 /// PerformMSTORECombine - Resolve truncating stores
26360 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26361 const X86Subtarget *Subtarget) {
26362 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26363 if (!Mst->isTruncatingStore())
26366 EVT VT = Mst->getValue().getValueType();
26367 unsigned NumElems = VT.getVectorNumElements();
26368 EVT StVT = Mst->getMemoryVT();
26371 assert(StVT != VT && "Cannot truncate to the same type");
26372 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26373 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26377 // The truncating store is legal in some cases. For example
26378 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26379 // are designated for truncate store.
26380 // In this case we don't need any further transformations.
26381 if (TLI.isTruncStoreLegal(VT, StVT))
26384 // From, To sizes and ElemCount must be pow of two
26385 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26386 "Unexpected size for truncating masked store");
26387 // We are going to use the original vector elt for storing.
26388 // Accumulated smaller vector elements must be a multiple of the store size.
26389 assert (((NumElems * FromSz) % ToSz) == 0 &&
26390 "Unexpected ratio for truncating masked store");
26392 unsigned SizeRatio = FromSz / ToSz;
26393 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26395 // Create a type on which we perform the shuffle
26396 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26397 StVT.getScalarType(), NumElems*SizeRatio);
26399 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26401 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26402 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26403 for (unsigned i = 0; i != NumElems; ++i)
26404 ShuffleVec[i] = i * SizeRatio;
26406 // Can't shuffle using an illegal type.
26407 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26408 "WideVecVT should be legal");
26410 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26411 DAG.getUNDEF(WideVecVT),
26415 SDValue Mask = Mst->getMask();
26416 if (Mask.getValueType() == VT) {
26417 // Mask and original value have the same type
26418 NewMask = DAG.getBitcast(WideVecVT, Mask);
26419 for (unsigned i = 0; i != NumElems; ++i)
26420 ShuffleVec[i] = i * SizeRatio;
26421 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26422 ShuffleVec[i] = NumElems*SizeRatio;
26423 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26424 DAG.getConstant(0, dl, WideVecVT),
26428 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26429 unsigned WidenNumElts = NumElems*SizeRatio;
26430 unsigned MaskNumElts = VT.getVectorNumElements();
26431 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26434 unsigned NumConcat = WidenNumElts / MaskNumElts;
26435 SmallVector<SDValue, 16> Ops(NumConcat);
26436 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26438 for (unsigned i = 1; i != NumConcat; ++i)
26441 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26444 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26445 Mst->getBasePtr(), NewMask, StVT,
26446 Mst->getMemOperand(), false);
26448 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26449 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26450 const X86Subtarget *Subtarget) {
26451 StoreSDNode *St = cast<StoreSDNode>(N);
26452 EVT VT = St->getValue().getValueType();
26453 EVT StVT = St->getMemoryVT();
26455 SDValue StoredVal = St->getOperand(1);
26456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26458 // If we are saving a concatenation of two XMM registers and 32-byte stores
26459 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26461 unsigned AddressSpace = St->getAddressSpace();
26462 unsigned Alignment = St->getAlignment();
26463 if (VT.is256BitVector() && StVT == VT &&
26464 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26465 AddressSpace, Alignment, &Fast) && !Fast) {
26466 unsigned NumElems = VT.getVectorNumElements();
26470 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26471 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26474 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26475 SDValue Ptr0 = St->getBasePtr();
26476 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26478 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26479 St->getPointerInfo(), St->isVolatile(),
26480 St->isNonTemporal(), Alignment);
26481 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26482 St->getPointerInfo(), St->isVolatile(),
26483 St->isNonTemporal(),
26484 std::min(16U, Alignment));
26485 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26488 // Optimize trunc store (of multiple scalars) to shuffle and store.
26489 // First, pack all of the elements in one place. Next, store to memory
26490 // in fewer chunks.
26491 if (St->isTruncatingStore() && VT.isVector()) {
26492 // Check if we can detect an AVG pattern from the truncation. If yes,
26493 // replace the trunc store by a normal store with the result of X86ISD::AVG
26496 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26498 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26499 St->getPointerInfo(), St->isVolatile(),
26500 St->isNonTemporal(), St->getAlignment());
26502 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26503 unsigned NumElems = VT.getVectorNumElements();
26504 assert(StVT != VT && "Cannot truncate to the same type");
26505 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26506 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26508 // The truncating store is legal in some cases. For example
26509 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26510 // are designated for truncate store.
26511 // In this case we don't need any further transformations.
26512 if (TLI.isTruncStoreLegal(VT, StVT))
26515 // From, To sizes and ElemCount must be pow of two
26516 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26517 // We are going to use the original vector elt for storing.
26518 // Accumulated smaller vector elements must be a multiple of the store size.
26519 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26521 unsigned SizeRatio = FromSz / ToSz;
26523 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26525 // Create a type on which we perform the shuffle
26526 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26527 StVT.getScalarType(), NumElems*SizeRatio);
26529 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26531 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26532 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26533 for (unsigned i = 0; i != NumElems; ++i)
26534 ShuffleVec[i] = i * SizeRatio;
26536 // Can't shuffle using an illegal type.
26537 if (!TLI.isTypeLegal(WideVecVT))
26540 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26541 DAG.getUNDEF(WideVecVT),
26543 // At this point all of the data is stored at the bottom of the
26544 // register. We now need to save it to mem.
26546 // Find the largest store unit
26547 MVT StoreType = MVT::i8;
26548 for (MVT Tp : MVT::integer_valuetypes()) {
26549 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26553 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26554 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26555 (64 <= NumElems * ToSz))
26556 StoreType = MVT::f64;
26558 // Bitcast the original vector into a vector of store-size units
26559 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26560 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26561 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26562 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26563 SmallVector<SDValue, 8> Chains;
26564 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26565 TLI.getPointerTy(DAG.getDataLayout()));
26566 SDValue Ptr = St->getBasePtr();
26568 // Perform one or more big stores into memory.
26569 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26570 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26571 StoreType, ShuffWide,
26572 DAG.getIntPtrConstant(i, dl));
26573 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26574 St->getPointerInfo(), St->isVolatile(),
26575 St->isNonTemporal(), St->getAlignment());
26576 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26577 Chains.push_back(Ch);
26580 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26583 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26584 // the FP state in cases where an emms may be missing.
26585 // A preferable solution to the general problem is to figure out the right
26586 // places to insert EMMS. This qualifies as a quick hack.
26588 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26589 if (VT.getSizeInBits() != 64)
26592 const Function *F = DAG.getMachineFunction().getFunction();
26593 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26595 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26596 if ((VT.isVector() ||
26597 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26598 isa<LoadSDNode>(St->getValue()) &&
26599 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26600 St->getChain().hasOneUse() && !St->isVolatile()) {
26601 SDNode* LdVal = St->getValue().getNode();
26602 LoadSDNode *Ld = nullptr;
26603 int TokenFactorIndex = -1;
26604 SmallVector<SDValue, 8> Ops;
26605 SDNode* ChainVal = St->getChain().getNode();
26606 // Must be a store of a load. We currently handle two cases: the load
26607 // is a direct child, and it's under an intervening TokenFactor. It is
26608 // possible to dig deeper under nested TokenFactors.
26609 if (ChainVal == LdVal)
26610 Ld = cast<LoadSDNode>(St->getChain());
26611 else if (St->getValue().hasOneUse() &&
26612 ChainVal->getOpcode() == ISD::TokenFactor) {
26613 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26614 if (ChainVal->getOperand(i).getNode() == LdVal) {
26615 TokenFactorIndex = i;
26616 Ld = cast<LoadSDNode>(St->getValue());
26618 Ops.push_back(ChainVal->getOperand(i));
26622 if (!Ld || !ISD::isNormalLoad(Ld))
26625 // If this is not the MMX case, i.e. we are just turning i64 load/store
26626 // into f64 load/store, avoid the transformation if there are multiple
26627 // uses of the loaded value.
26628 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26633 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26634 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26636 if (Subtarget->is64Bit() || F64IsLegal) {
26637 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26638 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26639 Ld->getPointerInfo(), Ld->isVolatile(),
26640 Ld->isNonTemporal(), Ld->isInvariant(),
26641 Ld->getAlignment());
26642 SDValue NewChain = NewLd.getValue(1);
26643 if (TokenFactorIndex != -1) {
26644 Ops.push_back(NewChain);
26645 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26647 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26648 St->getPointerInfo(),
26649 St->isVolatile(), St->isNonTemporal(),
26650 St->getAlignment());
26653 // Otherwise, lower to two pairs of 32-bit loads / stores.
26654 SDValue LoAddr = Ld->getBasePtr();
26655 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26656 DAG.getConstant(4, LdDL, MVT::i32));
26658 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26659 Ld->getPointerInfo(),
26660 Ld->isVolatile(), Ld->isNonTemporal(),
26661 Ld->isInvariant(), Ld->getAlignment());
26662 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26663 Ld->getPointerInfo().getWithOffset(4),
26664 Ld->isVolatile(), Ld->isNonTemporal(),
26666 MinAlign(Ld->getAlignment(), 4));
26668 SDValue NewChain = LoLd.getValue(1);
26669 if (TokenFactorIndex != -1) {
26670 Ops.push_back(LoLd);
26671 Ops.push_back(HiLd);
26672 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26675 LoAddr = St->getBasePtr();
26676 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26677 DAG.getConstant(4, StDL, MVT::i32));
26679 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26680 St->getPointerInfo(),
26681 St->isVolatile(), St->isNonTemporal(),
26682 St->getAlignment());
26683 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26684 St->getPointerInfo().getWithOffset(4),
26686 St->isNonTemporal(),
26687 MinAlign(St->getAlignment(), 4));
26688 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26691 // This is similar to the above case, but here we handle a scalar 64-bit
26692 // integer store that is extracted from a vector on a 32-bit target.
26693 // If we have SSE2, then we can treat it like a floating-point double
26694 // to get past legalization. The execution dependencies fixup pass will
26695 // choose the optimal machine instruction for the store if this really is
26696 // an integer or v2f32 rather than an f64.
26697 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26698 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26699 SDValue OldExtract = St->getOperand(1);
26700 SDValue ExtOp0 = OldExtract.getOperand(0);
26701 unsigned VecSize = ExtOp0.getValueSizeInBits();
26702 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26703 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26704 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26705 BitCast, OldExtract.getOperand(1));
26706 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26707 St->getPointerInfo(), St->isVolatile(),
26708 St->isNonTemporal(), St->getAlignment());
26714 /// Return 'true' if this vector operation is "horizontal"
26715 /// and return the operands for the horizontal operation in LHS and RHS. A
26716 /// horizontal operation performs the binary operation on successive elements
26717 /// of its first operand, then on successive elements of its second operand,
26718 /// returning the resulting values in a vector. For example, if
26719 /// A = < float a0, float a1, float a2, float a3 >
26721 /// B = < float b0, float b1, float b2, float b3 >
26722 /// then the result of doing a horizontal operation on A and B is
26723 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26724 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26725 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26726 /// set to A, RHS to B, and the routine returns 'true'.
26727 /// Note that the binary operation should have the property that if one of the
26728 /// operands is UNDEF then the result is UNDEF.
26729 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26730 // Look for the following pattern: if
26731 // A = < float a0, float a1, float a2, float a3 >
26732 // B = < float b0, float b1, float b2, float b3 >
26734 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26735 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26736 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26737 // which is A horizontal-op B.
26739 // At least one of the operands should be a vector shuffle.
26740 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26741 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26744 MVT VT = LHS.getSimpleValueType();
26746 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26747 "Unsupported vector type for horizontal add/sub");
26749 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26750 // operate independently on 128-bit lanes.
26751 unsigned NumElts = VT.getVectorNumElements();
26752 unsigned NumLanes = VT.getSizeInBits()/128;
26753 unsigned NumLaneElts = NumElts / NumLanes;
26754 assert((NumLaneElts % 2 == 0) &&
26755 "Vector type should have an even number of elements in each lane");
26756 unsigned HalfLaneElts = NumLaneElts/2;
26758 // View LHS in the form
26759 // LHS = VECTOR_SHUFFLE A, B, LMask
26760 // If LHS is not a shuffle then pretend it is the shuffle
26761 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26762 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26765 SmallVector<int, 16> LMask(NumElts);
26766 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26767 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26768 A = LHS.getOperand(0);
26769 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26770 B = LHS.getOperand(1);
26771 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26772 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26774 if (LHS.getOpcode() != ISD::UNDEF)
26776 for (unsigned i = 0; i != NumElts; ++i)
26780 // Likewise, view RHS in the form
26781 // RHS = VECTOR_SHUFFLE C, D, RMask
26783 SmallVector<int, 16> RMask(NumElts);
26784 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26785 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26786 C = RHS.getOperand(0);
26787 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26788 D = RHS.getOperand(1);
26789 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26790 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26792 if (RHS.getOpcode() != ISD::UNDEF)
26794 for (unsigned i = 0; i != NumElts; ++i)
26798 // Check that the shuffles are both shuffling the same vectors.
26799 if (!(A == C && B == D) && !(A == D && B == C))
26802 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26803 if (!A.getNode() && !B.getNode())
26806 // If A and B occur in reverse order in RHS, then "swap" them (which means
26807 // rewriting the mask).
26809 ShuffleVectorSDNode::commuteMask(RMask);
26811 // At this point LHS and RHS are equivalent to
26812 // LHS = VECTOR_SHUFFLE A, B, LMask
26813 // RHS = VECTOR_SHUFFLE A, B, RMask
26814 // Check that the masks correspond to performing a horizontal operation.
26815 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26816 for (unsigned i = 0; i != NumLaneElts; ++i) {
26817 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26819 // Ignore any UNDEF components.
26820 if (LIdx < 0 || RIdx < 0 ||
26821 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26822 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26825 // Check that successive elements are being operated on. If not, this is
26826 // not a horizontal operation.
26827 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26828 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26829 if (!(LIdx == Index && RIdx == Index + 1) &&
26830 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26835 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26836 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26840 /// Do target-specific dag combines on floating point adds.
26841 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26842 const X86Subtarget *Subtarget) {
26843 EVT VT = N->getValueType(0);
26844 SDValue LHS = N->getOperand(0);
26845 SDValue RHS = N->getOperand(1);
26847 // Try to synthesize horizontal adds from adds of shuffles.
26848 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26849 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26850 isHorizontalBinOp(LHS, RHS, true))
26851 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26855 /// Do target-specific dag combines on floating point subs.
26856 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26857 const X86Subtarget *Subtarget) {
26858 EVT VT = N->getValueType(0);
26859 SDValue LHS = N->getOperand(0);
26860 SDValue RHS = N->getOperand(1);
26862 // Try to synthesize horizontal subs from subs of shuffles.
26863 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26864 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26865 isHorizontalBinOp(LHS, RHS, false))
26866 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26870 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26872 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26873 SmallVector<SDValue, 8> &Regs) {
26874 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26875 Regs[0].getValueType() == MVT::v2i64));
26876 EVT OutVT = N->getValueType(0);
26877 EVT OutSVT = OutVT.getVectorElementType();
26878 EVT InVT = Regs[0].getValueType();
26879 EVT InSVT = InVT.getVectorElementType();
26882 // First, use mask to unset all bits that won't appear in the result.
26883 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26884 "OutSVT can only be either i8 or i16.");
26886 DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26887 SDValue MaskVec = DAG.getNode(
26888 ISD::BUILD_VECTOR, DL, InVT,
26889 SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26890 for (auto &Reg : Regs)
26891 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26893 MVT UnpackedVT, PackedVT;
26894 if (OutSVT == MVT::i8) {
26895 UnpackedVT = MVT::v8i16;
26896 PackedVT = MVT::v16i8;
26898 UnpackedVT = MVT::v4i32;
26899 PackedVT = MVT::v8i16;
26902 // In each iteration, truncate the type by a half size.
26903 auto RegNum = Regs.size();
26904 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26905 j < e; j *= 2, RegNum /= 2) {
26906 for (unsigned i = 0; i < RegNum; i++)
26907 Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26908 for (unsigned i = 0; i < RegNum / 2; i++)
26909 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26913 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26914 // then extract a subvector as the result since v8i8 is not a legal type.
26915 if (OutVT == MVT::v8i8) {
26916 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26917 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26918 DAG.getIntPtrConstant(0, DL));
26920 } else if (RegNum > 1) {
26921 Regs.resize(RegNum);
26922 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26927 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26929 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26930 SmallVector<SDValue, 8> &Regs) {
26931 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26932 EVT OutVT = N->getValueType(0);
26935 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26936 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26937 for (auto &Reg : Regs) {
26938 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26939 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26942 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26943 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26946 if (Regs.size() > 2) {
26947 Regs.resize(Regs.size() / 2);
26948 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26953 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26954 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26955 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26956 /// element that is extracted from a vector and then truncated, and it is
26957 /// diffcult to do this optimization based on them.
26958 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26959 const X86Subtarget *Subtarget) {
26960 EVT OutVT = N->getValueType(0);
26961 if (!OutVT.isVector())
26964 SDValue In = N->getOperand(0);
26965 if (!In.getValueType().isSimple())
26968 EVT InVT = In.getValueType();
26969 unsigned NumElems = OutVT.getVectorNumElements();
26971 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26972 // SSE2, and we need to take care of it specially.
26973 // AVX512 provides vpmovdb.
26974 if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26977 EVT OutSVT = OutVT.getVectorElementType();
26978 EVT InSVT = InVT.getVectorElementType();
26979 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26980 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26984 // SSSE3's pshufb results in less instructions in the cases below.
26985 if (Subtarget->hasSSSE3() && NumElems == 8 &&
26986 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26987 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26992 // Split a long vector into vectors of legal type.
26993 unsigned RegNum = InVT.getSizeInBits() / 128;
26994 SmallVector<SDValue, 8> SubVec(RegNum);
26995 if (InSVT == MVT::i32) {
26996 for (unsigned i = 0; i < RegNum; i++)
26997 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26998 DAG.getIntPtrConstant(i * 4, DL));
27000 for (unsigned i = 0; i < RegNum; i++)
27001 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
27002 DAG.getIntPtrConstant(i * 2, DL));
27005 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
27006 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
27007 // truncate 2 x v4i32 to v8i16.
27008 if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
27009 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
27010 else if (InSVT == MVT::i32)
27011 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
27016 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
27017 const X86Subtarget *Subtarget) {
27018 // Try to detect AVG pattern first.
27019 SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
27020 Subtarget, SDLoc(N));
27024 return combineVectorTruncation(N, DAG, Subtarget);
27027 /// Do target-specific dag combines on floating point negations.
27028 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
27029 const X86Subtarget *Subtarget) {
27030 EVT VT = N->getValueType(0);
27031 EVT SVT = VT.getScalarType();
27032 SDValue Arg = N->getOperand(0);
27035 // Let legalize expand this if it isn't a legal type yet.
27036 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27039 // If we're negating a FMUL node on a target with FMA, then we can avoid the
27040 // use of a constant by performing (-0 - A*B) instead.
27041 // FIXME: Check rounding control flags as well once it becomes available.
27042 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27043 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27044 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27045 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27046 Arg.getOperand(1), Zero);
27049 // If we're negating a FMA node, then we can adjust the
27050 // instruction to include the extra negation.
27051 if (Arg.hasOneUse()) {
27052 switch (Arg.getOpcode()) {
27053 case X86ISD::FMADD:
27054 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27055 Arg.getOperand(1), Arg.getOperand(2));
27056 case X86ISD::FMSUB:
27057 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27058 Arg.getOperand(1), Arg.getOperand(2));
27059 case X86ISD::FNMADD:
27060 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27061 Arg.getOperand(1), Arg.getOperand(2));
27062 case X86ISD::FNMSUB:
27063 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27064 Arg.getOperand(1), Arg.getOperand(2));
27070 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27071 const X86Subtarget *Subtarget) {
27072 EVT VT = N->getValueType(0);
27073 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27074 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27075 // These logic operations may be executed in the integer domain.
27077 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27078 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27080 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27081 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27082 unsigned IntOpcode = 0;
27083 switch (N->getOpcode()) {
27084 default: llvm_unreachable("Unexpected FP logic op");
27085 case X86ISD::FOR: IntOpcode = ISD::OR; break;
27086 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27087 case X86ISD::FAND: IntOpcode = ISD::AND; break;
27088 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27090 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27091 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27095 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27096 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27097 const X86Subtarget *Subtarget) {
27098 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27100 // F[X]OR(0.0, x) -> x
27101 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27102 if (C->getValueAPF().isPosZero())
27103 return N->getOperand(1);
27105 // F[X]OR(x, 0.0) -> x
27106 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27107 if (C->getValueAPF().isPosZero())
27108 return N->getOperand(0);
27110 return lowerX86FPLogicOp(N, DAG, Subtarget);
27113 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27114 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27115 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27117 // Only perform optimizations if UnsafeMath is used.
27118 if (!DAG.getTarget().Options.UnsafeFPMath)
27121 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27122 // into FMINC and FMAXC, which are Commutative operations.
27123 unsigned NewOp = 0;
27124 switch (N->getOpcode()) {
27125 default: llvm_unreachable("unknown opcode");
27126 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
27127 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
27130 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27131 N->getOperand(0), N->getOperand(1));
27134 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27135 const X86Subtarget *Subtarget) {
27136 if (Subtarget->useSoftFloat())
27139 // TODO: Check for global or instruction-level "nnan". In that case, we
27140 // should be able to lower to FMAX/FMIN alone.
27141 // TODO: If an operand is already known to be a NaN or not a NaN, this
27142 // should be an optional swap and FMAX/FMIN.
27144 EVT VT = N->getValueType(0);
27145 if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27146 (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27147 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27150 // This takes at least 3 instructions, so favor a library call when operating
27151 // on a scalar and minimizing code size.
27152 if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27155 SDValue Op0 = N->getOperand(0);
27156 SDValue Op1 = N->getOperand(1);
27158 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27159 DAG.getDataLayout(), *DAG.getContext(), VT);
27161 // There are 4 possibilities involving NaN inputs, and these are the required
27165 // ----------------
27166 // Num | Max | Op0 |
27167 // Op0 ----------------
27168 // NaN | Op1 | NaN |
27169 // ----------------
27171 // The SSE FP max/min instructions were not designed for this case, but rather
27173 // Min = Op1 < Op0 ? Op1 : Op0
27174 // Max = Op1 > Op0 ? Op1 : Op0
27176 // So they always return Op0 if either input is a NaN. However, we can still
27177 // use those instructions for fmaxnum by selecting away a NaN input.
27179 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27180 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27181 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27182 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27184 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27185 // are NaN, the NaN value of Op1 is the result.
27186 auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27187 return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27190 /// Do target-specific dag combines on X86ISD::FAND nodes.
27191 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27192 const X86Subtarget *Subtarget) {
27193 // FAND(0.0, x) -> 0.0
27194 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27195 if (C->getValueAPF().isPosZero())
27196 return N->getOperand(0);
27198 // FAND(x, 0.0) -> 0.0
27199 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27200 if (C->getValueAPF().isPosZero())
27201 return N->getOperand(1);
27203 return lowerX86FPLogicOp(N, DAG, Subtarget);
27206 /// Do target-specific dag combines on X86ISD::FANDN nodes
27207 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27208 const X86Subtarget *Subtarget) {
27209 // FANDN(0.0, x) -> x
27210 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27211 if (C->getValueAPF().isPosZero())
27212 return N->getOperand(1);
27214 // FANDN(x, 0.0) -> 0.0
27215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27216 if (C->getValueAPF().isPosZero())
27217 return N->getOperand(1);
27219 return lowerX86FPLogicOp(N, DAG, Subtarget);
27222 static SDValue PerformBTCombine(SDNode *N,
27224 TargetLowering::DAGCombinerInfo &DCI) {
27225 // BT ignores high bits in the bit index operand.
27226 SDValue Op1 = N->getOperand(1);
27227 if (Op1.hasOneUse()) {
27228 unsigned BitWidth = Op1.getValueSizeInBits();
27229 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27230 APInt KnownZero, KnownOne;
27231 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27232 !DCI.isBeforeLegalizeOps());
27233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27234 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27235 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27236 DCI.CommitTargetLoweringOpt(TLO);
27241 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27242 SDValue Op = N->getOperand(0);
27243 if (Op.getOpcode() == ISD::BITCAST)
27244 Op = Op.getOperand(0);
27245 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27246 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27247 VT.getVectorElementType().getSizeInBits() ==
27248 OpVT.getVectorElementType().getSizeInBits()) {
27249 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27254 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27255 const X86Subtarget *Subtarget) {
27256 EVT VT = N->getValueType(0);
27257 if (!VT.isVector())
27260 SDValue N0 = N->getOperand(0);
27261 SDValue N1 = N->getOperand(1);
27262 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27265 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27266 // both SSE and AVX2 since there is no sign-extended shift right
27267 // operation on a vector with 64-bit elements.
27268 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27269 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27270 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27271 N0.getOpcode() == ISD::SIGN_EXTEND)) {
27272 SDValue N00 = N0.getOperand(0);
27274 // EXTLOAD has a better solution on AVX2,
27275 // it may be replaced with X86ISD::VSEXT node.
27276 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27277 if (!ISD::isNormalLoad(N00.getNode()))
27280 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27281 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27283 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27289 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27290 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27291 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27292 /// eliminate extend, add, and shift instructions.
27293 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27294 const X86Subtarget *Subtarget) {
27295 // TODO: This should be valid for other integer types.
27296 EVT VT = Sext->getValueType(0);
27297 if (VT != MVT::i64)
27300 // We need an 'add nsw' feeding into the 'sext'.
27301 SDValue Add = Sext->getOperand(0);
27302 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27305 // Having a constant operand to the 'add' ensures that we are not increasing
27306 // the instruction count because the constant is extended for free below.
27307 // A constant operand can also become the displacement field of an LEA.
27308 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27312 // Don't make the 'add' bigger if there's no hope of combining it with some
27313 // other 'add' or 'shl' instruction.
27314 // TODO: It may be profitable to generate simpler LEA instructions in place
27315 // of single 'add' instructions, but the cost model for selecting an LEA
27316 // currently has a high threshold.
27317 bool HasLEAPotential = false;
27318 for (auto *User : Sext->uses()) {
27319 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27320 HasLEAPotential = true;
27324 if (!HasLEAPotential)
27327 // Everything looks good, so pull the 'sext' ahead of the 'add'.
27328 int64_t AddConstant = AddOp1->getSExtValue();
27329 SDValue AddOp0 = Add.getOperand(0);
27330 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27331 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27333 // The wider add is guaranteed to not wrap because both operands are
27336 Flags.setNoSignedWrap(true);
27337 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27340 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27341 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27342 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27343 /// extends from AH (which we otherwise need to do contortions to access).
27344 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27345 SDValue N0 = N->getOperand(0);
27346 auto OpcodeN = N->getOpcode();
27347 auto OpcodeN0 = N0.getOpcode();
27348 if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27349 (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27352 EVT VT = N->getValueType(0);
27353 EVT InVT = N0.getValueType();
27354 if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27357 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27358 auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27359 : X86ISD::UDIVREM8_ZEXT_HREG;
27360 SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27362 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27363 return R.getValue(1);
27366 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27367 TargetLowering::DAGCombinerInfo &DCI,
27368 const X86Subtarget *Subtarget) {
27369 SDValue N0 = N->getOperand(0);
27370 EVT VT = N->getValueType(0);
27371 EVT SVT = VT.getScalarType();
27372 EVT InVT = N0.getValueType();
27373 EVT InSVT = InVT.getScalarType();
27376 if (SDValue DivRem8 = getDivRem8(N, DAG))
27379 if (!DCI.isBeforeLegalizeOps()) {
27380 if (InVT == MVT::i1) {
27381 SDValue Zero = DAG.getConstant(0, DL, VT);
27383 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27384 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27389 if (VT.isVector() && Subtarget->hasSSE2()) {
27390 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27391 EVT InVT = N.getValueType();
27392 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27393 Size / InVT.getScalarSizeInBits());
27394 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27395 DAG.getUNDEF(InVT));
27397 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27400 // If target-size is less than 128-bits, extend to a type that would extend
27401 // to 128 bits, extend that and extract the original target vector.
27402 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27403 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27404 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27405 unsigned Scale = 128 / VT.getSizeInBits();
27407 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27408 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27409 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27410 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27411 DAG.getIntPtrConstant(0, DL));
27414 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27415 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27416 if (VT.getSizeInBits() == 128 &&
27417 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27418 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27419 SDValue ExOp = ExtendVecSize(DL, N0, 128);
27420 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27423 // On pre-AVX2 targets, split into 128-bit nodes of
27424 // ISD::SIGN_EXTEND_VECTOR_INREG.
27425 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27426 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27427 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27428 unsigned NumVecs = VT.getSizeInBits() / 128;
27429 unsigned NumSubElts = 128 / SVT.getSizeInBits();
27430 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27431 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27433 SmallVector<SDValue, 8> Opnds;
27434 for (unsigned i = 0, Offset = 0; i != NumVecs;
27435 ++i, Offset += NumSubElts) {
27436 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27437 DAG.getIntPtrConstant(Offset, DL));
27438 SrcVec = ExtendVecSize(DL, SrcVec, 128);
27439 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27440 Opnds.push_back(SrcVec);
27442 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27446 if (Subtarget->hasAVX() && VT.is256BitVector())
27447 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27450 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27456 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27457 const X86Subtarget* Subtarget) {
27459 EVT VT = N->getValueType(0);
27461 // Let legalize expand this if it isn't a legal type yet.
27462 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27465 EVT ScalarVT = VT.getScalarType();
27466 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27469 SDValue A = N->getOperand(0);
27470 SDValue B = N->getOperand(1);
27471 SDValue C = N->getOperand(2);
27473 bool NegA = (A.getOpcode() == ISD::FNEG);
27474 bool NegB = (B.getOpcode() == ISD::FNEG);
27475 bool NegC = (C.getOpcode() == ISD::FNEG);
27477 // Negative multiplication when NegA xor NegB
27478 bool NegMul = (NegA != NegB);
27480 A = A.getOperand(0);
27482 B = B.getOperand(0);
27484 C = C.getOperand(0);
27488 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27490 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27492 return DAG.getNode(Opcode, dl, VT, A, B, C);
27495 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27496 TargetLowering::DAGCombinerInfo &DCI,
27497 const X86Subtarget *Subtarget) {
27498 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
27499 // (and (i32 x86isd::setcc_carry), 1)
27500 // This eliminates the zext. This transformation is necessary because
27501 // ISD::SETCC is always legalized to i8.
27503 SDValue N0 = N->getOperand(0);
27504 EVT VT = N->getValueType(0);
27506 if (N0.getOpcode() == ISD::AND &&
27508 N0.getOperand(0).hasOneUse()) {
27509 SDValue N00 = N0.getOperand(0);
27510 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27511 if (!isOneConstant(N0.getOperand(1)))
27513 return DAG.getNode(ISD::AND, dl, VT,
27514 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27515 N00.getOperand(0), N00.getOperand(1)),
27516 DAG.getConstant(1, dl, VT));
27520 if (N0.getOpcode() == ISD::TRUNCATE &&
27522 N0.getOperand(0).hasOneUse()) {
27523 SDValue N00 = N0.getOperand(0);
27524 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27525 return DAG.getNode(ISD::AND, dl, VT,
27526 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27527 N00.getOperand(0), N00.getOperand(1)),
27528 DAG.getConstant(1, dl, VT));
27532 if (VT.is256BitVector())
27533 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27536 if (SDValue DivRem8 = getDivRem8(N, DAG))
27542 // Optimize x == -y --> x+y == 0
27543 // x != -y --> x+y != 0
27544 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27545 const X86Subtarget* Subtarget) {
27546 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27547 SDValue LHS = N->getOperand(0);
27548 SDValue RHS = N->getOperand(1);
27549 EVT VT = N->getValueType(0);
27552 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27553 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27554 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27555 LHS.getOperand(1));
27556 return DAG.getSetCC(DL, N->getValueType(0), addV,
27557 DAG.getConstant(0, DL, addV.getValueType()), CC);
27559 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27560 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27561 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27562 RHS.getOperand(1));
27563 return DAG.getSetCC(DL, N->getValueType(0), addV,
27564 DAG.getConstant(0, DL, addV.getValueType()), CC);
27567 if (VT.getScalarType() == MVT::i1 &&
27568 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27570 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27571 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27572 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27574 if (!IsSEXT0 || !IsVZero1) {
27575 // Swap the operands and update the condition code.
27576 std::swap(LHS, RHS);
27577 CC = ISD::getSetCCSwappedOperands(CC);
27579 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27580 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27581 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27584 if (IsSEXT0 && IsVZero1) {
27585 assert(VT == LHS.getOperand(0).getValueType() &&
27586 "Uexpected operand type");
27587 if (CC == ISD::SETGT)
27588 return DAG.getConstant(0, DL, VT);
27589 if (CC == ISD::SETLE)
27590 return DAG.getConstant(1, DL, VT);
27591 if (CC == ISD::SETEQ || CC == ISD::SETGE)
27592 return DAG.getNOT(DL, LHS.getOperand(0), VT);
27594 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27595 "Unexpected condition code!");
27596 return LHS.getOperand(0);
27603 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27605 // Gather and Scatter instructions use k-registers for masks. The type of
27606 // the masks is v*i1. So the mask will be truncated anyway.
27607 // The SIGN_EXTEND_INREG my be dropped.
27608 SDValue Mask = N->getOperand(2);
27609 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27610 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27611 NewOps[2] = Mask.getOperand(0);
27612 DAG.UpdateNodeOperands(N, NewOps);
27617 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27618 // as "sbb reg,reg", since it can be extended without zext and produces
27619 // an all-ones bit which is more useful than 0/1 in some cases.
27620 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27623 return DAG.getNode(ISD::AND, DL, VT,
27624 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27625 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27627 DAG.getConstant(1, DL, VT));
27628 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27629 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27630 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27631 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27635 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27636 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27637 TargetLowering::DAGCombinerInfo &DCI,
27638 const X86Subtarget *Subtarget) {
27640 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27641 SDValue EFLAGS = N->getOperand(1);
27643 if (CC == X86::COND_A) {
27644 // Try to convert COND_A into COND_B in an attempt to facilitate
27645 // materializing "setb reg".
27647 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27648 // cannot take an immediate as its first operand.
27650 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27651 EFLAGS.getValueType().isInteger() &&
27652 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27653 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27654 EFLAGS.getNode()->getVTList(),
27655 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27656 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27657 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27661 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27662 // a zext and produces an all-ones bit which is more useful than 0/1 in some
27664 if (CC == X86::COND_B)
27665 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27667 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27668 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27669 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27675 // Optimize branch condition evaluation.
27677 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27678 TargetLowering::DAGCombinerInfo &DCI,
27679 const X86Subtarget *Subtarget) {
27681 SDValue Chain = N->getOperand(0);
27682 SDValue Dest = N->getOperand(1);
27683 SDValue EFLAGS = N->getOperand(3);
27684 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27686 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27687 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27688 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27695 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27696 SelectionDAG &DAG) {
27697 // Take advantage of vector comparisons producing 0 or -1 in each lane to
27698 // optimize away operation when it's from a constant.
27700 // The general transformation is:
27701 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27702 // AND(VECTOR_CMP(x,y), constant2)
27703 // constant2 = UNARYOP(constant)
27705 // Early exit if this isn't a vector operation, the operand of the
27706 // unary operation isn't a bitwise AND, or if the sizes of the operations
27707 // aren't the same.
27708 EVT VT = N->getValueType(0);
27709 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27710 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27711 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27714 // Now check that the other operand of the AND is a constant. We could
27715 // make the transformation for non-constant splats as well, but it's unclear
27716 // that would be a benefit as it would not eliminate any operations, just
27717 // perform one more step in scalar code before moving to the vector unit.
27718 if (BuildVectorSDNode *BV =
27719 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27720 // Bail out if the vector isn't a constant.
27721 if (!BV->isConstant())
27724 // Everything checks out. Build up the new and improved node.
27726 EVT IntVT = BV->getValueType(0);
27727 // Create a new constant of the appropriate type for the transformed
27729 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27730 // The AND node needs bitcasts to/from an integer vector type around it.
27731 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27732 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27733 N->getOperand(0)->getOperand(0), MaskConst);
27734 SDValue Res = DAG.getBitcast(VT, NewAnd);
27741 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27742 const X86Subtarget *Subtarget) {
27743 SDValue Op0 = N->getOperand(0);
27744 EVT VT = N->getValueType(0);
27745 EVT InVT = Op0.getValueType();
27746 EVT InSVT = InVT.getScalarType();
27747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27749 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27750 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27751 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27753 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27754 InVT.getVectorNumElements());
27755 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27757 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27758 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27760 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27766 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27767 const X86Subtarget *Subtarget) {
27768 // First try to optimize away the conversion entirely when it's
27769 // conditionally from a constant. Vectors only.
27770 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27773 // Now move on to more general possibilities.
27774 SDValue Op0 = N->getOperand(0);
27775 EVT VT = N->getValueType(0);
27776 EVT InVT = Op0.getValueType();
27777 EVT InSVT = InVT.getScalarType();
27779 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27780 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27781 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27783 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27784 InVT.getVectorNumElements());
27785 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27786 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27789 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27790 // a 32-bit target where SSE doesn't support i64->FP operations.
27791 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27792 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27793 EVT LdVT = Ld->getValueType(0);
27795 // This transformation is not supported if the result type is f16
27796 if (VT == MVT::f16)
27799 if (!Ld->isVolatile() && !VT.isVector() &&
27800 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27801 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27802 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27803 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27804 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27811 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27812 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27813 X86TargetLowering::DAGCombinerInfo &DCI) {
27814 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27815 // the result is either zero or one (depending on the input carry bit).
27816 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27817 if (X86::isZeroNode(N->getOperand(0)) &&
27818 X86::isZeroNode(N->getOperand(1)) &&
27819 // We don't have a good way to replace an EFLAGS use, so only do this when
27821 SDValue(N, 1).use_empty()) {
27823 EVT VT = N->getValueType(0);
27824 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27825 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27826 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27827 DAG.getConstant(X86::COND_B, DL,
27830 DAG.getConstant(1, DL, VT));
27831 return DCI.CombineTo(N, Res1, CarryOut);
27837 // fold (add Y, (sete X, 0)) -> adc 0, Y
27838 // (add Y, (setne X, 0)) -> sbb -1, Y
27839 // (sub (sete X, 0), Y) -> sbb 0, Y
27840 // (sub (setne X, 0), Y) -> adc -1, Y
27841 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27844 // Look through ZExts.
27845 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27846 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27849 SDValue SetCC = Ext.getOperand(0);
27850 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27853 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27854 if (CC != X86::COND_E && CC != X86::COND_NE)
27857 SDValue Cmp = SetCC.getOperand(1);
27858 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27859 !X86::isZeroNode(Cmp.getOperand(1)) ||
27860 !Cmp.getOperand(0).getValueType().isInteger())
27863 SDValue CmpOp0 = Cmp.getOperand(0);
27864 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27865 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27867 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27868 if (CC == X86::COND_NE)
27869 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27870 DL, OtherVal.getValueType(), OtherVal,
27871 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27873 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27874 DL, OtherVal.getValueType(), OtherVal,
27875 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27878 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27879 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27880 const X86Subtarget *Subtarget) {
27881 EVT VT = N->getValueType(0);
27882 SDValue Op0 = N->getOperand(0);
27883 SDValue Op1 = N->getOperand(1);
27885 // Try to synthesize horizontal adds from adds of shuffles.
27886 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27887 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27888 isHorizontalBinOp(Op0, Op1, true))
27889 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27891 return OptimizeConditionalInDecrement(N, DAG);
27894 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27895 const X86Subtarget *Subtarget) {
27896 SDValue Op0 = N->getOperand(0);
27897 SDValue Op1 = N->getOperand(1);
27899 // X86 can't encode an immediate LHS of a sub. See if we can push the
27900 // negation into a preceding instruction.
27901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27902 // If the RHS of the sub is a XOR with one use and a constant, invert the
27903 // immediate. Then add one to the LHS of the sub so we can turn
27904 // X-Y -> X+~Y+1, saving one register.
27905 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27906 isa<ConstantSDNode>(Op1.getOperand(1))) {
27907 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27908 EVT VT = Op0.getValueType();
27909 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27911 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27912 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27913 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27917 // Try to synthesize horizontal adds from adds of shuffles.
27918 EVT VT = N->getValueType(0);
27919 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27920 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27921 isHorizontalBinOp(Op0, Op1, true))
27922 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27924 return OptimizeConditionalInDecrement(N, DAG);
27927 /// performVZEXTCombine - Performs build vector combines
27928 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27929 TargetLowering::DAGCombinerInfo &DCI,
27930 const X86Subtarget *Subtarget) {
27932 MVT VT = N->getSimpleValueType(0);
27933 SDValue Op = N->getOperand(0);
27934 MVT OpVT = Op.getSimpleValueType();
27935 MVT OpEltVT = OpVT.getVectorElementType();
27936 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27938 // (vzext (bitcast (vzext (x)) -> (vzext x)
27940 while (V.getOpcode() == ISD::BITCAST)
27941 V = V.getOperand(0);
27943 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27944 MVT InnerVT = V.getSimpleValueType();
27945 MVT InnerEltVT = InnerVT.getVectorElementType();
27947 // If the element sizes match exactly, we can just do one larger vzext. This
27948 // is always an exact type match as vzext operates on integer types.
27949 if (OpEltVT == InnerEltVT) {
27950 assert(OpVT == InnerVT && "Types must match for vzext!");
27951 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27954 // The only other way we can combine them is if only a single element of the
27955 // inner vzext is used in the input to the outer vzext.
27956 if (InnerEltVT.getSizeInBits() < InputBits)
27959 // In this case, the inner vzext is completely dead because we're going to
27960 // only look at bits inside of the low element. Just do the outer vzext on
27961 // a bitcast of the input to the inner.
27962 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27965 // Check if we can bypass extracting and re-inserting an element of an input
27966 // vector. Essentially:
27967 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27968 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27969 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27970 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27971 SDValue ExtractedV = V.getOperand(0);
27972 SDValue OrigV = ExtractedV.getOperand(0);
27973 if (isNullConstant(ExtractedV.getOperand(1))) {
27974 MVT OrigVT = OrigV.getSimpleValueType();
27975 // Extract a subvector if necessary...
27976 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27977 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27978 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27979 OrigVT.getVectorNumElements() / Ratio);
27980 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27981 DAG.getIntPtrConstant(0, DL));
27983 Op = DAG.getBitcast(OpVT, OrigV);
27984 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27991 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27992 DAGCombinerInfo &DCI) const {
27993 SelectionDAG &DAG = DCI.DAG;
27994 switch (N->getOpcode()) {
27996 case ISD::EXTRACT_VECTOR_ELT:
27997 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
28000 case X86ISD::SHRUNKBLEND:
28001 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
28002 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
28003 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
28004 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
28005 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
28006 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
28007 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
28010 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
28011 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
28012 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
28013 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
28014 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
28015 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
28016 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
28017 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
28018 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
28019 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
28020 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
28021 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
28022 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
28023 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
28025 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
28027 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
28029 case ISD::FMAXNUM: return performFMinNumFMaxNumCombine(N, DAG,
28031 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
28032 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
28033 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
28034 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
28035 case ISD::ANY_EXTEND:
28036 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
28037 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
28038 case ISD::SIGN_EXTEND_INREG:
28039 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28040 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
28041 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28042 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28043 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
28044 case X86ISD::SHUFP: // Handle all target specific shuffles
28045 case X86ISD::PALIGNR:
28046 case X86ISD::BLENDI:
28047 case X86ISD::UNPCKH:
28048 case X86ISD::UNPCKL:
28049 case X86ISD::MOVHLPS:
28050 case X86ISD::MOVLHPS:
28051 case X86ISD::PSHUFB:
28052 case X86ISD::PSHUFD:
28053 case X86ISD::PSHUFHW:
28054 case X86ISD::PSHUFLW:
28055 case X86ISD::MOVSS:
28056 case X86ISD::MOVSD:
28057 case X86ISD::VPERMILPI:
28058 case X86ISD::VPERM2X128:
28059 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28060 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
28062 case ISD::MSCATTER: return PerformGatherScatterCombine(N, DAG);
28068 /// isTypeDesirableForOp - Return true if the target has native support for
28069 /// the specified value type and it is 'desirable' to use the type for the
28070 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28071 /// instruction encodings are longer and some i16 instructions are slow.
28072 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28073 if (!isTypeLegal(VT))
28075 if (VT != MVT::i16)
28082 case ISD::SIGN_EXTEND:
28083 case ISD::ZERO_EXTEND:
28084 case ISD::ANY_EXTEND:
28097 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28098 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28099 /// we don't adjust the stack we clobber the first frame index.
28100 /// See X86InstrInfo::copyPhysReg.
28101 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28102 MachineFunction *MF) const {
28103 const MachineRegisterInfo &MRI = MF->getRegInfo();
28105 return any_of(MRI.reg_instructions(X86::EFLAGS),
28106 [](const MachineInstr &RI) { return RI.isCopy(); });
28109 /// IsDesirableToPromoteOp - This method query the target whether it is
28110 /// beneficial for dag combiner to promote the specified node. If true, it
28111 /// should return the desired promotion type by reference.
28112 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28113 EVT VT = Op.getValueType();
28114 if (VT != MVT::i16)
28117 bool Promote = false;
28118 bool Commute = false;
28119 switch (Op.getOpcode()) {
28122 LoadSDNode *LD = cast<LoadSDNode>(Op);
28123 // If the non-extending load has a single use and it's not live out, then it
28124 // might be folded.
28125 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28126 Op.hasOneUse()*/) {
28127 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28128 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28129 // The only case where we'd want to promote LOAD (rather then it being
28130 // promoted as an operand is when it's only use is liveout.
28131 if (UI->getOpcode() != ISD::CopyToReg)
28138 case ISD::SIGN_EXTEND:
28139 case ISD::ZERO_EXTEND:
28140 case ISD::ANY_EXTEND:
28145 SDValue N0 = Op.getOperand(0);
28146 // Look out for (store (shl (load), x)).
28147 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28160 SDValue N0 = Op.getOperand(0);
28161 SDValue N1 = Op.getOperand(1);
28162 if (!Commute && MayFoldLoad(N1))
28164 // Avoid disabling potential load folding opportunities.
28165 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28167 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28177 //===----------------------------------------------------------------------===//
28178 // X86 Inline Assembly Support
28179 //===----------------------------------------------------------------------===//
28181 // Helper to match a string separated by whitespace.
28182 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28183 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28185 for (StringRef Piece : Pieces) {
28186 if (!S.startswith(Piece)) // Check if the piece matches.
28189 S = S.substr(Piece.size());
28190 StringRef::size_type Pos = S.find_first_not_of(" \t");
28191 if (Pos == 0) // We matched a prefix.
28200 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28202 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28203 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28204 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28205 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28207 if (AsmPieces.size() == 3)
28209 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28216 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28217 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28219 std::string AsmStr = IA->getAsmString();
28221 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28222 if (!Ty || Ty->getBitWidth() % 16 != 0)
28225 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28226 SmallVector<StringRef, 4> AsmPieces;
28227 SplitString(AsmStr, AsmPieces, ";\n");
28229 switch (AsmPieces.size()) {
28230 default: return false;
28232 // FIXME: this should verify that we are targeting a 486 or better. If not,
28233 // we will turn this bswap into something that will be lowered to logical
28234 // ops instead of emitting the bswap asm. For now, we don't support 486 or
28235 // lower so don't worry about this.
28237 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28238 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28239 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28240 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28241 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28242 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28243 // No need to check constraints, nothing other than the equivalent of
28244 // "=r,0" would be valid here.
28245 return IntrinsicLowering::LowerToByteSwap(CI);
28248 // rorw $$8, ${0:w} --> llvm.bswap.i16
28249 if (CI->getType()->isIntegerTy(16) &&
28250 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28251 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28252 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28254 StringRef ConstraintsStr = IA->getConstraintString();
28255 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28256 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28257 if (clobbersFlagRegisters(AsmPieces))
28258 return IntrinsicLowering::LowerToByteSwap(CI);
28262 if (CI->getType()->isIntegerTy(32) &&
28263 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28264 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28265 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28266 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28268 StringRef ConstraintsStr = IA->getConstraintString();
28269 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28270 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28271 if (clobbersFlagRegisters(AsmPieces))
28272 return IntrinsicLowering::LowerToByteSwap(CI);
28275 if (CI->getType()->isIntegerTy(64)) {
28276 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28277 if (Constraints.size() >= 2 &&
28278 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28279 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28280 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
28281 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28282 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28283 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28284 return IntrinsicLowering::LowerToByteSwap(CI);
28292 /// getConstraintType - Given a constraint letter, return the type of
28293 /// constraint it is for this target.
28294 X86TargetLowering::ConstraintType
28295 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28296 if (Constraint.size() == 1) {
28297 switch (Constraint[0]) {
28308 return C_RegisterClass;
28332 return TargetLowering::getConstraintType(Constraint);
28335 /// Examine constraint type and operand type and determine a weight value.
28336 /// This object must already have been set up with the operand type
28337 /// and the current alternative constraint selected.
28338 TargetLowering::ConstraintWeight
28339 X86TargetLowering::getSingleConstraintMatchWeight(
28340 AsmOperandInfo &info, const char *constraint) const {
28341 ConstraintWeight weight = CW_Invalid;
28342 Value *CallOperandVal = info.CallOperandVal;
28343 // If we don't have a value, we can't do a match,
28344 // but allow it at the lowest weight.
28345 if (!CallOperandVal)
28347 Type *type = CallOperandVal->getType();
28348 // Look at the constraint type.
28349 switch (*constraint) {
28351 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28362 if (CallOperandVal->getType()->isIntegerTy())
28363 weight = CW_SpecificReg;
28368 if (type->isFloatingPointTy())
28369 weight = CW_SpecificReg;
28372 if (type->isX86_MMXTy() && Subtarget->hasMMX())
28373 weight = CW_SpecificReg;
28377 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28378 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28379 weight = CW_Register;
28382 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28383 if (C->getZExtValue() <= 31)
28384 weight = CW_Constant;
28388 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28389 if (C->getZExtValue() <= 63)
28390 weight = CW_Constant;
28394 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28395 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28396 weight = CW_Constant;
28400 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28401 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28402 weight = CW_Constant;
28406 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28407 if (C->getZExtValue() <= 3)
28408 weight = CW_Constant;
28412 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28413 if (C->getZExtValue() <= 0xff)
28414 weight = CW_Constant;
28419 if (isa<ConstantFP>(CallOperandVal)) {
28420 weight = CW_Constant;
28424 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28425 if ((C->getSExtValue() >= -0x80000000LL) &&
28426 (C->getSExtValue() <= 0x7fffffffLL))
28427 weight = CW_Constant;
28431 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28432 if (C->getZExtValue() <= 0xffffffff)
28433 weight = CW_Constant;
28440 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28441 /// with another that has more specific requirements based on the type of the
28442 /// corresponding operand.
28443 const char *X86TargetLowering::
28444 LowerXConstraint(EVT ConstraintVT) const {
28445 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28446 // 'f' like normal targets.
28447 if (ConstraintVT.isFloatingPoint()) {
28448 if (Subtarget->hasSSE2())
28450 if (Subtarget->hasSSE1())
28454 return TargetLowering::LowerXConstraint(ConstraintVT);
28457 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28458 /// vector. If it is invalid, don't add anything to Ops.
28459 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28460 std::string &Constraint,
28461 std::vector<SDValue>&Ops,
28462 SelectionDAG &DAG) const {
28465 // Only support length 1 constraints for now.
28466 if (Constraint.length() > 1) return;
28468 char ConstraintLetter = Constraint[0];
28469 switch (ConstraintLetter) {
28472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28473 if (C->getZExtValue() <= 31) {
28474 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28475 Op.getValueType());
28481 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28482 if (C->getZExtValue() <= 63) {
28483 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28484 Op.getValueType());
28490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28491 if (isInt<8>(C->getSExtValue())) {
28492 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28493 Op.getValueType());
28499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28500 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28501 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28502 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28503 Op.getValueType());
28509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28510 if (C->getZExtValue() <= 3) {
28511 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28512 Op.getValueType());
28518 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28519 if (C->getZExtValue() <= 255) {
28520 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28521 Op.getValueType());
28527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28528 if (C->getZExtValue() <= 127) {
28529 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28530 Op.getValueType());
28536 // 32-bit signed value
28537 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28538 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28539 C->getSExtValue())) {
28540 // Widen to 64 bits here to get it sign extended.
28541 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28544 // FIXME gcc accepts some relocatable values here too, but only in certain
28545 // memory models; it's complicated.
28550 // 32-bit unsigned value
28551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28552 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28553 C->getZExtValue())) {
28554 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28555 Op.getValueType());
28559 // FIXME gcc accepts some relocatable values here too, but only in certain
28560 // memory models; it's complicated.
28564 // Literal immediates are always ok.
28565 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28566 // Widen to 64 bits here to get it sign extended.
28567 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28571 // In any sort of PIC mode addresses need to be computed at runtime by
28572 // adding in a register or some sort of table lookup. These can't
28573 // be used as immediates.
28574 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28577 // If we are in non-pic codegen mode, we allow the address of a global (with
28578 // an optional displacement) to be used with 'i'.
28579 GlobalAddressSDNode *GA = nullptr;
28580 int64_t Offset = 0;
28582 // Match either (GA), (GA+C), (GA+C1+C2), etc.
28584 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28585 Offset += GA->getOffset();
28587 } else if (Op.getOpcode() == ISD::ADD) {
28588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28589 Offset += C->getZExtValue();
28590 Op = Op.getOperand(0);
28593 } else if (Op.getOpcode() == ISD::SUB) {
28594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28595 Offset += -C->getZExtValue();
28596 Op = Op.getOperand(0);
28601 // Otherwise, this isn't something we can handle, reject it.
28605 const GlobalValue *GV = GA->getGlobal();
28606 // If we require an extra load to get this address, as in PIC mode, we
28607 // can't accept it.
28608 if (isGlobalStubReference(
28609 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28612 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28613 GA->getValueType(0), Offset);
28618 if (Result.getNode()) {
28619 Ops.push_back(Result);
28622 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28625 std::pair<unsigned, const TargetRegisterClass *>
28626 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28627 StringRef Constraint,
28629 // First, see if this is a constraint that directly corresponds to an LLVM
28631 if (Constraint.size() == 1) {
28632 // GCC Constraint Letters
28633 switch (Constraint[0]) {
28635 // TODO: Slight differences here in allocation order and leaving
28636 // RIP in the class. Do they matter any more here than they do
28637 // in the normal allocation?
28638 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28639 if (Subtarget->is64Bit()) {
28640 if (VT == MVT::i32 || VT == MVT::f32)
28641 return std::make_pair(0U, &X86::GR32RegClass);
28642 if (VT == MVT::i16)
28643 return std::make_pair(0U, &X86::GR16RegClass);
28644 if (VT == MVT::i8 || VT == MVT::i1)
28645 return std::make_pair(0U, &X86::GR8RegClass);
28646 if (VT == MVT::i64 || VT == MVT::f64)
28647 return std::make_pair(0U, &X86::GR64RegClass);
28650 // 32-bit fallthrough
28651 case 'Q': // Q_REGS
28652 if (VT == MVT::i32 || VT == MVT::f32)
28653 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28654 if (VT == MVT::i16)
28655 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28656 if (VT == MVT::i8 || VT == MVT::i1)
28657 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28658 if (VT == MVT::i64)
28659 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28661 case 'r': // GENERAL_REGS
28662 case 'l': // INDEX_REGS
28663 if (VT == MVT::i8 || VT == MVT::i1)
28664 return std::make_pair(0U, &X86::GR8RegClass);
28665 if (VT == MVT::i16)
28666 return std::make_pair(0U, &X86::GR16RegClass);
28667 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28668 return std::make_pair(0U, &X86::GR32RegClass);
28669 return std::make_pair(0U, &X86::GR64RegClass);
28670 case 'R': // LEGACY_REGS
28671 if (VT == MVT::i8 || VT == MVT::i1)
28672 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28673 if (VT == MVT::i16)
28674 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28675 if (VT == MVT::i32 || !Subtarget->is64Bit())
28676 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28677 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28678 case 'f': // FP Stack registers.
28679 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28680 // value to the correct fpstack register class.
28681 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28682 return std::make_pair(0U, &X86::RFP32RegClass);
28683 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28684 return std::make_pair(0U, &X86::RFP64RegClass);
28685 return std::make_pair(0U, &X86::RFP80RegClass);
28686 case 'y': // MMX_REGS if MMX allowed.
28687 if (!Subtarget->hasMMX()) break;
28688 return std::make_pair(0U, &X86::VR64RegClass);
28689 case 'Y': // SSE_REGS if SSE2 allowed
28690 if (!Subtarget->hasSSE2()) break;
28692 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28693 if (!Subtarget->hasSSE1()) break;
28695 switch (VT.SimpleTy) {
28697 // Scalar SSE types.
28700 return std::make_pair(0U, &X86::FR32RegClass);
28703 return std::make_pair(0U, &X86::FR64RegClass);
28704 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28712 return std::make_pair(0U, &X86::VR128RegClass);
28720 return std::make_pair(0U, &X86::VR256RegClass);
28725 return std::make_pair(0U, &X86::VR512RegClass);
28731 // Use the default implementation in TargetLowering to convert the register
28732 // constraint into a member of a register class.
28733 std::pair<unsigned, const TargetRegisterClass*> Res;
28734 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28736 // Not found as a standard register?
28738 // Map st(0) -> st(7) -> ST0
28739 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28740 tolower(Constraint[1]) == 's' &&
28741 tolower(Constraint[2]) == 't' &&
28742 Constraint[3] == '(' &&
28743 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28744 Constraint[5] == ')' &&
28745 Constraint[6] == '}') {
28747 Res.first = X86::FP0+Constraint[4]-'0';
28748 Res.second = &X86::RFP80RegClass;
28752 // GCC allows "st(0)" to be called just plain "st".
28753 if (StringRef("{st}").equals_lower(Constraint)) {
28754 Res.first = X86::FP0;
28755 Res.second = &X86::RFP80RegClass;
28760 if (StringRef("{flags}").equals_lower(Constraint)) {
28761 Res.first = X86::EFLAGS;
28762 Res.second = &X86::CCRRegClass;
28766 // 'A' means EAX + EDX.
28767 if (Constraint == "A") {
28768 Res.first = X86::EAX;
28769 Res.second = &X86::GR32_ADRegClass;
28775 // Otherwise, check to see if this is a register class of the wrong value
28776 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28777 // turn into {ax},{dx}.
28778 // MVT::Other is used to specify clobber names.
28779 if (Res.second->hasType(VT) || VT == MVT::Other)
28780 return Res; // Correct type already, nothing to do.
28782 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28783 // return "eax". This should even work for things like getting 64bit integer
28784 // registers when given an f64 type.
28785 const TargetRegisterClass *Class = Res.second;
28786 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28787 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28788 unsigned Size = VT.getSizeInBits();
28789 if (Size == 1) Size = 8;
28790 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28792 Res.first = DestReg;
28793 Res.second = Size == 8 ? &X86::GR8RegClass
28794 : Size == 16 ? &X86::GR16RegClass
28795 : Size == 32 ? &X86::GR32RegClass
28796 : &X86::GR64RegClass;
28797 assert(Res.second->contains(Res.first) && "Register in register class");
28799 // No register found/type mismatch.
28801 Res.second = nullptr;
28803 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28804 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28805 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28806 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28807 Class == &X86::VR512RegClass) {
28808 // Handle references to XMM physical registers that got mapped into the
28809 // wrong class. This can happen with constraints like {xmm0} where the
28810 // target independent register mapper will just pick the first match it can
28811 // find, ignoring the required type.
28813 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28814 if (VT == MVT::f32 || VT == MVT::i32)
28815 Res.second = &X86::FR32RegClass;
28816 else if (VT == MVT::f64 || VT == MVT::i64)
28817 Res.second = &X86::FR64RegClass;
28818 else if (X86::VR128RegClass.hasType(VT))
28819 Res.second = &X86::VR128RegClass;
28820 else if (X86::VR256RegClass.hasType(VT))
28821 Res.second = &X86::VR256RegClass;
28822 else if (X86::VR512RegClass.hasType(VT))
28823 Res.second = &X86::VR512RegClass;
28825 // Type mismatch and not a clobber: Return an error;
28827 Res.second = nullptr;
28834 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28835 const AddrMode &AM, Type *Ty,
28836 unsigned AS) const {
28837 // Scaling factors are not free at all.
28838 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28839 // will take 2 allocations in the out of order engine instead of 1
28840 // for plain addressing mode, i.e. inst (reg1).
28842 // vaddps (%rsi,%drx), %ymm0, %ymm1
28843 // Requires two allocations (one for the load, one for the computation)
28845 // vaddps (%rsi), %ymm0, %ymm1
28846 // Requires just 1 allocation, i.e., freeing allocations for other operations
28847 // and having less micro operations to execute.
28849 // For some X86 architectures, this is even worse because for instance for
28850 // stores, the complex addressing mode forces the instruction to use the
28851 // "load" ports instead of the dedicated "store" port.
28852 // E.g., on Haswell:
28853 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28854 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28855 if (isLegalAddressingMode(DL, AM, Ty, AS))
28856 // Scale represents reg2 * scale, thus account for 1
28857 // as soon as we use a second register.
28858 return AM.Scale != 0;
28862 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28863 // Integer division on x86 is expensive. However, when aggressively optimizing
28864 // for code size, we prefer to use a div instruction, as it is usually smaller
28865 // than the alternative sequence.
28866 // The exception to this is vector division. Since x86 doesn't have vector
28867 // integer division, leaving the division as-is is a loss even in terms of
28868 // size, because it will have to be scalarized, while the alternative code
28869 // sequence can be performed in vector form.
28870 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28871 Attribute::MinSize);
28872 return OptSize && !VT.isVector();
28875 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28876 if (!Subtarget->is64Bit())
28879 // Update IsSplitCSR in X86MachineFunctionInfo.
28880 X86MachineFunctionInfo *AFI =
28881 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28882 AFI->setIsSplitCSR(true);
28885 void X86TargetLowering::insertCopiesSplitCSR(
28886 MachineBasicBlock *Entry,
28887 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28888 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28889 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28893 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28894 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28895 MachineBasicBlock::iterator MBBI = Entry->begin();
28896 for (const MCPhysReg *I = IStart; *I; ++I) {
28897 const TargetRegisterClass *RC = nullptr;
28898 if (X86::GR64RegClass.contains(*I))
28899 RC = &X86::GR64RegClass;
28901 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28903 unsigned NewVR = MRI->createVirtualRegister(RC);
28904 // Create copy from CSR to a virtual register.
28905 // FIXME: this currently does not emit CFI pseudo-instructions, it works
28906 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28907 // nounwind. If we want to generalize this later, we may need to emit
28908 // CFI pseudo-instructions.
28909 assert(Entry->getParent()->getFunction()->hasFnAttribute(
28910 Attribute::NoUnwind) &&
28911 "Function should be nounwind in insertCopiesSplitCSR!");
28912 Entry->addLiveIn(*I);
28913 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
28916 // Insert the copy-back instructions right before the terminator.
28917 for (auto *Exit : Exits)
28918 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
28919 TII->get(TargetOpcode::COPY), *I)