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::SELECT_CC, MVT::i1, Expand);
1339 setOperationAction(ISD::XOR, MVT::i1, Legal);
1340 setOperationAction(ISD::OR, MVT::i1, Legal);
1341 setOperationAction(ISD::AND, MVT::i1, Legal);
1342 setOperationAction(ISD::SUB, MVT::i1, Custom);
1343 setOperationAction(ISD::ADD, MVT::i1, Custom);
1344 setOperationAction(ISD::MUL, MVT::i1, Custom);
1345 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1349 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1351 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1357 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1359 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1364 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1365 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1366 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1367 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1369 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1372 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1383 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1384 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1386 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1387 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1388 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1389 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1390 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1391 if (Subtarget->hasVLX()){
1392 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1393 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1394 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1395 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1396 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1398 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1399 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1400 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1401 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1402 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1404 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1405 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1406 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1407 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1409 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1410 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1411 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1412 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1413 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1414 if (Subtarget->hasDQI()) {
1415 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1416 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1418 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1420 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1421 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1422 if (Subtarget->hasVLX()) {
1423 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1424 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1425 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1426 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1427 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1428 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1429 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1430 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1433 if (Subtarget->hasVLX()) {
1434 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1435 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1436 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1437 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1438 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1439 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1440 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1441 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1443 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1444 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1445 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1446 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1447 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1448 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1449 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1450 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1453 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1455 if (Subtarget->hasDQI()) {
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1457 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1459 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1460 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1461 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1462 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1463 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1464 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1465 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1466 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1467 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1468 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1470 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1474 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1476 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1477 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1479 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1481 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1483 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1484 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1485 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1486 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1487 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1488 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1492 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1494 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1495 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1496 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1497 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1498 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1499 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1500 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1501 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1503 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1504 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1506 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1507 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1509 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1511 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1512 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1514 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1515 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1517 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1518 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1520 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1521 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1522 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1523 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1524 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1525 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1527 if (Subtarget->hasCDI()) {
1528 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1529 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1530 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Expand);
1531 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Expand);
1533 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1534 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1535 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1536 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1537 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Expand);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Expand);
1539 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Expand);
1540 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Expand);
1542 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1543 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1545 if (Subtarget->hasVLX()) {
1546 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1547 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1548 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1549 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1550 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1552 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1553 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1555 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1557 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1558 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1560 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1562 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1563 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1567 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1569 } // Subtarget->hasCDI()
1571 if (Subtarget->hasDQI()) {
1572 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1573 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1574 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1576 // Custom lower several nodes.
1577 for (MVT VT : MVT::vector_valuetypes()) {
1578 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1580 setOperationAction(ISD::AND, VT, Legal);
1581 setOperationAction(ISD::OR, VT, Legal);
1582 setOperationAction(ISD::XOR, VT, Legal);
1584 if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1585 setOperationAction(ISD::MGATHER, VT, Custom);
1586 setOperationAction(ISD::MSCATTER, VT, Custom);
1588 // Extract subvector is special because the value type
1589 // (result) is 256/128-bit but the source is 512-bit wide.
1590 if (VT.is128BitVector() || VT.is256BitVector()) {
1591 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1593 if (VT.getVectorElementType() == MVT::i1)
1594 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1596 // Do not attempt to custom lower other non-512-bit vectors
1597 if (!VT.is512BitVector())
1600 if (EltSize >= 32) {
1601 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1602 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1603 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1604 setOperationAction(ISD::VSELECT, VT, Legal);
1605 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1606 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1607 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1608 setOperationAction(ISD::MLOAD, VT, Legal);
1609 setOperationAction(ISD::MSTORE, VT, Legal);
1610 setOperationAction(ISD::MGATHER, VT, Legal);
1611 setOperationAction(ISD::MSCATTER, VT, Custom);
1614 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1615 setOperationAction(ISD::SELECT, VT, Promote);
1616 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1620 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1621 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1622 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1624 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1625 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1627 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1628 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1629 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1630 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1631 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1632 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1633 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1634 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1635 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1636 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1637 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1638 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1641 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1642 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1645 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1646 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1648 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1649 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1650 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1651 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1652 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1653 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1656 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1657 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1661 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1662 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1663 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1664 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1665 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1666 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1670 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1671 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1672 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1673 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1674 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1675 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1676 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1677 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1679 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1680 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1681 if (Subtarget->hasVLX())
1682 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1684 if (Subtarget->hasCDI()) {
1685 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1686 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1687 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1688 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Expand);
1691 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1692 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1693 setOperationAction(ISD::VSELECT, VT, Legal);
1694 setOperationAction(ISD::SRL, VT, Custom);
1695 setOperationAction(ISD::SHL, VT, Custom);
1696 setOperationAction(ISD::SRA, VT, Custom);
1698 setOperationAction(ISD::AND, VT, Promote);
1699 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1700 setOperationAction(ISD::OR, VT, Promote);
1701 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1702 setOperationAction(ISD::XOR, VT, Promote);
1703 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1707 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1708 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1709 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1711 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1712 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1713 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1715 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1716 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1717 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1718 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1719 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1720 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1721 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1722 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1724 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1725 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1726 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1727 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1728 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1729 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1730 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1731 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1733 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1734 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1735 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1736 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1737 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1738 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1739 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1740 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1743 // We want to custom lower some of our intrinsics.
1744 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1745 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1746 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1747 if (!Subtarget->is64Bit()) {
1748 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1749 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1752 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1753 // handle type legalization for these operations here.
1755 // FIXME: We really should do custom legalization for addition and
1756 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1757 // than generic legalization for 64-bit multiplication-with-overflow, though.
1758 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1759 if (VT == MVT::i64 && !Subtarget->is64Bit())
1761 // Add/Sub/Mul with overflow operations are custom lowered.
1762 setOperationAction(ISD::SADDO, VT, Custom);
1763 setOperationAction(ISD::UADDO, VT, Custom);
1764 setOperationAction(ISD::SSUBO, VT, Custom);
1765 setOperationAction(ISD::USUBO, VT, Custom);
1766 setOperationAction(ISD::SMULO, VT, Custom);
1767 setOperationAction(ISD::UMULO, VT, Custom);
1770 if (!Subtarget->is64Bit()) {
1771 // These libcalls are not available in 32-bit.
1772 setLibcallName(RTLIB::SHL_I128, nullptr);
1773 setLibcallName(RTLIB::SRL_I128, nullptr);
1774 setLibcallName(RTLIB::SRA_I128, nullptr);
1777 // Combine sin / cos into one node or libcall if possible.
1778 if (Subtarget->hasSinCos()) {
1779 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1780 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1781 if (Subtarget->isTargetDarwin()) {
1782 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1783 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1784 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1785 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1789 if (Subtarget->isTargetWin64()) {
1790 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1791 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1792 setOperationAction(ISD::SREM, MVT::i128, Custom);
1793 setOperationAction(ISD::UREM, MVT::i128, Custom);
1794 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1795 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1798 // We have target-specific dag combine patterns for the following nodes:
1799 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1800 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1801 setTargetDAGCombine(ISD::BITCAST);
1802 setTargetDAGCombine(ISD::VSELECT);
1803 setTargetDAGCombine(ISD::SELECT);
1804 setTargetDAGCombine(ISD::SHL);
1805 setTargetDAGCombine(ISD::SRA);
1806 setTargetDAGCombine(ISD::SRL);
1807 setTargetDAGCombine(ISD::OR);
1808 setTargetDAGCombine(ISD::AND);
1809 setTargetDAGCombine(ISD::ADD);
1810 setTargetDAGCombine(ISD::FADD);
1811 setTargetDAGCombine(ISD::FSUB);
1812 setTargetDAGCombine(ISD::FNEG);
1813 setTargetDAGCombine(ISD::FMA);
1814 setTargetDAGCombine(ISD::FMINNUM);
1815 setTargetDAGCombine(ISD::FMAXNUM);
1816 setTargetDAGCombine(ISD::SUB);
1817 setTargetDAGCombine(ISD::LOAD);
1818 setTargetDAGCombine(ISD::MLOAD);
1819 setTargetDAGCombine(ISD::STORE);
1820 setTargetDAGCombine(ISD::MSTORE);
1821 setTargetDAGCombine(ISD::TRUNCATE);
1822 setTargetDAGCombine(ISD::ZERO_EXTEND);
1823 setTargetDAGCombine(ISD::ANY_EXTEND);
1824 setTargetDAGCombine(ISD::SIGN_EXTEND);
1825 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1826 setTargetDAGCombine(ISD::SINT_TO_FP);
1827 setTargetDAGCombine(ISD::UINT_TO_FP);
1828 setTargetDAGCombine(ISD::SETCC);
1829 setTargetDAGCombine(ISD::BUILD_VECTOR);
1830 setTargetDAGCombine(ISD::MUL);
1831 setTargetDAGCombine(ISD::XOR);
1832 setTargetDAGCombine(ISD::MSCATTER);
1833 setTargetDAGCombine(ISD::MGATHER);
1835 computeRegisterProperties(Subtarget->getRegisterInfo());
1837 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1838 MaxStoresPerMemsetOptSize = 8;
1839 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1840 MaxStoresPerMemcpyOptSize = 4;
1841 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1842 MaxStoresPerMemmoveOptSize = 4;
1843 setPrefLoopAlignment(4); // 2^4 bytes.
1845 // A predictable cmov does not hurt on an in-order CPU.
1846 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1847 PredictableSelectIsExpensive = !Subtarget->isAtom();
1848 EnableExtLdPromotion = true;
1849 setPrefFunctionAlignment(4); // 2^4 bytes.
1851 verifyIntrinsicTables();
1854 // This has so far only been implemented for 64-bit MachO.
1855 bool X86TargetLowering::useLoadStackGuardNode() const {
1856 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1859 TargetLoweringBase::LegalizeTypeAction
1860 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1861 if (ExperimentalVectorWideningLegalization &&
1862 VT.getVectorNumElements() != 1 &&
1863 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1864 return TypeWidenVector;
1866 return TargetLoweringBase::getPreferredVectorAction(VT);
1869 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1872 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1874 if (VT.isSimple()) {
1875 MVT VVT = VT.getSimpleVT();
1876 const unsigned NumElts = VVT.getVectorNumElements();
1877 const MVT EltVT = VVT.getVectorElementType();
1878 if (VVT.is512BitVector()) {
1879 if (Subtarget->hasAVX512())
1880 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1881 EltVT == MVT::f32 || EltVT == MVT::f64)
1883 case 8: return MVT::v8i1;
1884 case 16: return MVT::v16i1;
1886 if (Subtarget->hasBWI())
1887 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1889 case 32: return MVT::v32i1;
1890 case 64: return MVT::v64i1;
1894 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1895 if (Subtarget->hasVLX())
1896 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1897 EltVT == MVT::f32 || EltVT == MVT::f64)
1899 case 2: return MVT::v2i1;
1900 case 4: return MVT::v4i1;
1901 case 8: return MVT::v8i1;
1903 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1904 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1906 case 8: return MVT::v8i1;
1907 case 16: return MVT::v16i1;
1908 case 32: return MVT::v32i1;
1913 return VT.changeVectorElementTypeToInteger();
1916 /// Helper for getByValTypeAlignment to determine
1917 /// the desired ByVal argument alignment.
1918 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1921 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1922 if (VTy->getBitWidth() == 128)
1924 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1925 unsigned EltAlign = 0;
1926 getMaxByValAlign(ATy->getElementType(), EltAlign);
1927 if (EltAlign > MaxAlign)
1928 MaxAlign = EltAlign;
1929 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1930 for (auto *EltTy : STy->elements()) {
1931 unsigned EltAlign = 0;
1932 getMaxByValAlign(EltTy, EltAlign);
1933 if (EltAlign > MaxAlign)
1934 MaxAlign = EltAlign;
1941 /// Return the desired alignment for ByVal aggregate
1942 /// function arguments in the caller parameter area. For X86, aggregates
1943 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1944 /// are at 4-byte boundaries.
1945 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1946 const DataLayout &DL) const {
1947 if (Subtarget->is64Bit()) {
1948 // Max of 8 and alignment of type.
1949 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1956 if (Subtarget->hasSSE1())
1957 getMaxByValAlign(Ty, Align);
1961 /// Returns the target specific optimal type for load
1962 /// and store operations as a result of memset, memcpy, and memmove
1963 /// lowering. If DstAlign is zero that means it's safe to destination
1964 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1965 /// means there isn't a need to check it against alignment requirement,
1966 /// probably because the source does not need to be loaded. If 'IsMemset' is
1967 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1968 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1969 /// source is constant so it does not need to be loaded.
1970 /// It returns EVT::Other if the type should be determined using generic
1971 /// target-independent logic.
1973 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1974 unsigned DstAlign, unsigned SrcAlign,
1975 bool IsMemset, bool ZeroMemset,
1977 MachineFunction &MF) const {
1978 const Function *F = MF.getFunction();
1979 if ((!IsMemset || ZeroMemset) &&
1980 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1982 (!Subtarget->isUnalignedMem16Slow() ||
1983 ((DstAlign == 0 || DstAlign >= 16) &&
1984 (SrcAlign == 0 || SrcAlign >= 16)))) {
1986 // FIXME: Check if unaligned 32-byte accesses are slow.
1987 if (Subtarget->hasInt256())
1989 if (Subtarget->hasFp256())
1992 if (Subtarget->hasSSE2())
1994 if (Subtarget->hasSSE1())
1996 } else if (!MemcpyStrSrc && Size >= 8 &&
1997 !Subtarget->is64Bit() &&
1998 Subtarget->hasSSE2()) {
1999 // Do not use f64 to lower memcpy if source is string constant. It's
2000 // better to use i32 to avoid the loads.
2004 // This is a compromise. If we reach here, unaligned accesses may be slow on
2005 // this target. However, creating smaller, aligned accesses could be even
2006 // slower and would certainly be a lot more code.
2007 if (Subtarget->is64Bit() && Size >= 8)
2012 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2014 return X86ScalarSSEf32;
2015 else if (VT == MVT::f64)
2016 return X86ScalarSSEf64;
2021 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2026 switch (VT.getSizeInBits()) {
2028 // 8-byte and under are always assumed to be fast.
2032 *Fast = !Subtarget->isUnalignedMem16Slow();
2035 *Fast = !Subtarget->isUnalignedMem32Slow();
2037 // TODO: What about AVX-512 (512-bit) accesses?
2040 // Misaligned accesses of any size are always allowed.
2044 /// Return the entry encoding for a jump table in the
2045 /// current function. The returned value is a member of the
2046 /// MachineJumpTableInfo::JTEntryKind enum.
2047 unsigned X86TargetLowering::getJumpTableEncoding() const {
2048 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2050 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2051 Subtarget->isPICStyleGOT())
2052 return MachineJumpTableInfo::EK_Custom32;
2054 // Otherwise, use the normal jump table encoding heuristics.
2055 return TargetLowering::getJumpTableEncoding();
2058 bool X86TargetLowering::useSoftFloat() const {
2059 return Subtarget->useSoftFloat();
2063 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2064 const MachineBasicBlock *MBB,
2065 unsigned uid,MCContext &Ctx) const{
2066 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2067 Subtarget->isPICStyleGOT());
2068 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2070 return MCSymbolRefExpr::create(MBB->getSymbol(),
2071 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2074 /// Returns relocation base for the given PIC jumptable.
2075 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2076 SelectionDAG &DAG) const {
2077 if (!Subtarget->is64Bit())
2078 // This doesn't have SDLoc associated with it, but is not really the
2079 // same as a Register.
2080 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2081 getPointerTy(DAG.getDataLayout()));
2085 /// This returns the relocation base for the given PIC jumptable,
2086 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2087 const MCExpr *X86TargetLowering::
2088 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2089 MCContext &Ctx) const {
2090 // X86-64 uses RIP relative addressing based on the jump table label.
2091 if (Subtarget->isPICStyleRIPRel())
2092 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2094 // Otherwise, the reference is relative to the PIC base.
2095 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2098 std::pair<const TargetRegisterClass *, uint8_t>
2099 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2101 const TargetRegisterClass *RRC = nullptr;
2103 switch (VT.SimpleTy) {
2105 return TargetLowering::findRepresentativeClass(TRI, VT);
2106 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2107 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2110 RRC = &X86::VR64RegClass;
2112 case MVT::f32: case MVT::f64:
2113 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2114 case MVT::v4f32: case MVT::v2f64:
2115 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2117 RRC = &X86::VR128RegClass;
2120 return std::make_pair(RRC, Cost);
2123 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2124 unsigned &Offset) const {
2125 if (!Subtarget->isTargetLinux())
2128 if (Subtarget->is64Bit()) {
2129 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2131 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2143 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2144 if (!Subtarget->isTargetAndroid())
2145 return TargetLowering::getSafeStackPointerLocation(IRB);
2147 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2148 // definition of TLS_SLOT_SAFESTACK in
2149 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2150 unsigned AddressSpace, Offset;
2151 if (Subtarget->is64Bit()) {
2152 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2154 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2164 return ConstantExpr::getIntToPtr(
2165 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2166 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2169 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2170 unsigned DestAS) const {
2171 assert(SrcAS != DestAS && "Expected different address spaces!");
2173 return SrcAS < 256 && DestAS < 256;
2176 //===----------------------------------------------------------------------===//
2177 // Return Value Calling Convention Implementation
2178 //===----------------------------------------------------------------------===//
2180 #include "X86GenCallingConv.inc"
2182 bool X86TargetLowering::CanLowerReturn(
2183 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2184 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2185 SmallVector<CCValAssign, 16> RVLocs;
2186 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2187 return CCInfo.CheckReturn(Outs, RetCC_X86);
2190 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2191 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2196 X86TargetLowering::LowerReturn(SDValue Chain,
2197 CallingConv::ID CallConv, bool isVarArg,
2198 const SmallVectorImpl<ISD::OutputArg> &Outs,
2199 const SmallVectorImpl<SDValue> &OutVals,
2200 SDLoc dl, SelectionDAG &DAG) const {
2201 MachineFunction &MF = DAG.getMachineFunction();
2202 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2204 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2205 report_fatal_error("X86 interrupts may not return any value");
2207 SmallVector<CCValAssign, 16> RVLocs;
2208 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2209 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2212 SmallVector<SDValue, 6> RetOps;
2213 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2214 // Operand #1 = Bytes To Pop
2215 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2218 // Copy the result values into the output registers.
2219 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2220 CCValAssign &VA = RVLocs[i];
2221 assert(VA.isRegLoc() && "Can only return in registers!");
2222 SDValue ValToCopy = OutVals[i];
2223 EVT ValVT = ValToCopy.getValueType();
2225 // Promote values to the appropriate types.
2226 if (VA.getLocInfo() == CCValAssign::SExt)
2227 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2228 else if (VA.getLocInfo() == CCValAssign::ZExt)
2229 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2230 else if (VA.getLocInfo() == CCValAssign::AExt) {
2231 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2232 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2234 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2236 else if (VA.getLocInfo() == CCValAssign::BCvt)
2237 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2239 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2240 "Unexpected FP-extend for return value.");
2242 // If this is x86-64, and we disabled SSE, we can't return FP values,
2243 // or SSE or MMX vectors.
2244 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2245 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2246 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2247 report_fatal_error("SSE register return with SSE disabled");
2249 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2250 // llvm-gcc has never done it right and no one has noticed, so this
2251 // should be OK for now.
2252 if (ValVT == MVT::f64 &&
2253 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2254 report_fatal_error("SSE2 register return with SSE2 disabled");
2256 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2257 // the RET instruction and handled by the FP Stackifier.
2258 if (VA.getLocReg() == X86::FP0 ||
2259 VA.getLocReg() == X86::FP1) {
2260 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2261 // change the value to the FP stack register class.
2262 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2263 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2264 RetOps.push_back(ValToCopy);
2265 // Don't emit a copytoreg.
2269 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2270 // which is returned in RAX / RDX.
2271 if (Subtarget->is64Bit()) {
2272 if (ValVT == MVT::x86mmx) {
2273 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2274 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2275 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2277 // If we don't have SSE2 available, convert to v4f32 so the generated
2278 // register is legal.
2279 if (!Subtarget->hasSSE2())
2280 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2285 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2286 Flag = Chain.getValue(1);
2287 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2290 // All x86 ABIs require that for returning structs by value we copy
2291 // the sret argument into %rax/%eax (depending on ABI) for the return.
2292 // We saved the argument into a virtual register in the entry block,
2293 // so now we copy the value out and into %rax/%eax.
2295 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2296 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2297 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2298 // either case FuncInfo->setSRetReturnReg() will have been called.
2299 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2300 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2301 getPointerTy(MF.getDataLayout()));
2304 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2305 X86::RAX : X86::EAX;
2306 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2307 Flag = Chain.getValue(1);
2309 // RAX/EAX now acts like a return value.
2311 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2314 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
2315 const MCPhysReg *I =
2316 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2319 if (X86::GR64RegClass.contains(*I))
2320 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2322 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2326 RetOps[0] = Chain; // Update chain.
2328 // Add the flag if we have it.
2330 RetOps.push_back(Flag);
2332 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2333 if (CallConv == CallingConv::X86_INTR)
2334 opcode = X86ISD::IRET;
2335 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2338 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2339 if (N->getNumValues() != 1)
2341 if (!N->hasNUsesOfValue(1, 0))
2344 SDValue TCChain = Chain;
2345 SDNode *Copy = *N->use_begin();
2346 if (Copy->getOpcode() == ISD::CopyToReg) {
2347 // If the copy has a glue operand, we conservatively assume it isn't safe to
2348 // perform a tail call.
2349 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2351 TCChain = Copy->getOperand(0);
2352 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2355 bool HasRet = false;
2356 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2358 if (UI->getOpcode() != X86ISD::RET_FLAG)
2360 // If we are returning more than one value, we can definitely
2361 // not make a tail call see PR19530
2362 if (UI->getNumOperands() > 4)
2364 if (UI->getNumOperands() == 4 &&
2365 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2378 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2379 ISD::NodeType ExtendKind) const {
2381 // TODO: Is this also valid on 32-bit?
2382 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2383 ReturnMVT = MVT::i8;
2385 ReturnMVT = MVT::i32;
2387 EVT MinVT = getRegisterType(Context, ReturnMVT);
2388 return VT.bitsLT(MinVT) ? MinVT : VT;
2391 /// Lower the result values of a call into the
2392 /// appropriate copies out of appropriate physical registers.
2395 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2396 CallingConv::ID CallConv, bool isVarArg,
2397 const SmallVectorImpl<ISD::InputArg> &Ins,
2398 SDLoc dl, SelectionDAG &DAG,
2399 SmallVectorImpl<SDValue> &InVals) const {
2401 // Assign locations to each value returned by this call.
2402 SmallVector<CCValAssign, 16> RVLocs;
2403 bool Is64Bit = Subtarget->is64Bit();
2404 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2406 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2408 // Copy all of the result registers out of their specified physreg.
2409 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2410 CCValAssign &VA = RVLocs[i];
2411 EVT CopyVT = VA.getLocVT();
2413 // If this is x86-64, and we disabled SSE, we can't return FP values
2414 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2415 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2416 report_fatal_error("SSE register return with SSE disabled");
2419 // If we prefer to use the value in xmm registers, copy it out as f80 and
2420 // use a truncate to move it from fp stack reg to xmm reg.
2421 bool RoundAfterCopy = false;
2422 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2423 isScalarFPTypeInSSEReg(VA.getValVT())) {
2425 RoundAfterCopy = (CopyVT != VA.getLocVT());
2428 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2429 CopyVT, InFlag).getValue(1);
2430 SDValue Val = Chain.getValue(0);
2433 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2434 // This truncation won't change the value.
2435 DAG.getIntPtrConstant(1, dl));
2437 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2438 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2440 InFlag = Chain.getValue(2);
2441 InVals.push_back(Val);
2447 //===----------------------------------------------------------------------===//
2448 // C & StdCall & Fast Calling Convention implementation
2449 //===----------------------------------------------------------------------===//
2450 // StdCall calling convention seems to be standard for many Windows' API
2451 // routines and around. It differs from C calling convention just a little:
2452 // callee should clean up the stack, not caller. Symbols should be also
2453 // decorated in some fancy way :) It doesn't support any vector arguments.
2454 // For info on fast calling convention see Fast Calling Convention (tail call)
2455 // implementation LowerX86_32FastCCCallTo.
2457 /// CallIsStructReturn - Determines whether a call uses struct return
2459 enum StructReturnType {
2464 static StructReturnType
2465 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2467 return NotStructReturn;
2469 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2470 if (!Flags.isSRet())
2471 return NotStructReturn;
2472 if (Flags.isInReg() || IsMCU)
2473 return RegStructReturn;
2474 return StackStructReturn;
2477 /// Determines whether a function uses struct return semantics.
2478 static StructReturnType
2479 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2481 return NotStructReturn;
2483 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2484 if (!Flags.isSRet())
2485 return NotStructReturn;
2486 if (Flags.isInReg() || IsMCU)
2487 return RegStructReturn;
2488 return StackStructReturn;
2491 /// Make a copy of an aggregate at address specified by "Src" to address
2492 /// "Dst" with size and alignment information specified by the specific
2493 /// parameter attribute. The copy will be passed as a byval function parameter.
2495 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2496 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2498 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2500 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2501 /*isVolatile*/false, /*AlwaysInline=*/true,
2502 /*isTailCall*/false,
2503 MachinePointerInfo(), MachinePointerInfo());
2506 /// Return true if the calling convention is one that we can guarantee TCO for.
2507 static bool canGuaranteeTCO(CallingConv::ID CC) {
2508 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2509 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2512 /// Return true if we might ever do TCO for calls with this calling convention.
2513 static bool mayTailCallThisCC(CallingConv::ID CC) {
2515 // C calling conventions:
2516 case CallingConv::C:
2517 case CallingConv::X86_64_Win64:
2518 case CallingConv::X86_64_SysV:
2519 // Callee pop conventions:
2520 case CallingConv::X86_ThisCall:
2521 case CallingConv::X86_StdCall:
2522 case CallingConv::X86_VectorCall:
2523 case CallingConv::X86_FastCall:
2526 return canGuaranteeTCO(CC);
2530 /// Return true if the function is being made into a tailcall target by
2531 /// changing its ABI.
2532 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2533 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2536 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2538 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2539 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2543 CallingConv::ID CalleeCC = CS.getCallingConv();
2544 if (!mayTailCallThisCC(CalleeCC))
2551 X86TargetLowering::LowerMemArgument(SDValue Chain,
2552 CallingConv::ID CallConv,
2553 const SmallVectorImpl<ISD::InputArg> &Ins,
2554 SDLoc dl, SelectionDAG &DAG,
2555 const CCValAssign &VA,
2556 MachineFrameInfo *MFI,
2558 // Create the nodes corresponding to a load from this parameter slot.
2559 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2560 bool AlwaysUseMutable = shouldGuaranteeTCO(
2561 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2562 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2565 // If value is passed by pointer we have address passed instead of the value
2567 bool ExtendedInMem = VA.isExtInLoc() &&
2568 VA.getValVT().getScalarType() == MVT::i1;
2570 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2571 ValVT = VA.getLocVT();
2573 ValVT = VA.getValVT();
2575 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2576 // taken by a return address.
2578 if (CallConv == CallingConv::X86_INTR) {
2579 const X86Subtarget& Subtarget =
2580 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2581 // X86 interrupts may take one or two arguments.
2582 // On the stack there will be no return address as in regular call.
2583 // Offset of last argument need to be set to -4/-8 bytes.
2584 // Where offset of the first argument out of two, should be set to 0 bytes.
2585 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2588 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2589 // changed with more analysis.
2590 // In case of tail call optimization mark all arguments mutable. Since they
2591 // could be overwritten by lowering of arguments in case of a tail call.
2592 if (Flags.isByVal()) {
2593 unsigned Bytes = Flags.getByValSize();
2594 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2595 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2596 // Adjust SP offset of interrupt parameter.
2597 if (CallConv == CallingConv::X86_INTR) {
2598 MFI->setObjectOffset(FI, Offset);
2600 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2602 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2603 VA.getLocMemOffset(), isImmutable);
2604 // Adjust SP offset of interrupt parameter.
2605 if (CallConv == CallingConv::X86_INTR) {
2606 MFI->setObjectOffset(FI, Offset);
2609 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2610 SDValue Val = DAG.getLoad(
2611 ValVT, dl, Chain, FIN,
2612 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2614 return ExtendedInMem ?
2615 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2619 // FIXME: Get this from tablegen.
2620 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2621 const X86Subtarget *Subtarget) {
2622 assert(Subtarget->is64Bit());
2624 if (Subtarget->isCallingConvWin64(CallConv)) {
2625 static const MCPhysReg GPR64ArgRegsWin64[] = {
2626 X86::RCX, X86::RDX, X86::R8, X86::R9
2628 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2631 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2632 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2634 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2637 // FIXME: Get this from tablegen.
2638 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2639 CallingConv::ID CallConv,
2640 const X86Subtarget *Subtarget) {
2641 assert(Subtarget->is64Bit());
2642 if (Subtarget->isCallingConvWin64(CallConv)) {
2643 // The XMM registers which might contain var arg parameters are shadowed
2644 // in their paired GPR. So we only need to save the GPR to their home
2646 // TODO: __vectorcall will change this.
2650 const Function *Fn = MF.getFunction();
2651 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2652 bool isSoftFloat = Subtarget->useSoftFloat();
2653 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2654 "SSE register cannot be used when SSE is disabled!");
2655 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2656 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2660 static const MCPhysReg XMMArgRegs64Bit[] = {
2661 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2662 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2664 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2667 SDValue X86TargetLowering::LowerFormalArguments(
2668 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2669 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2670 SmallVectorImpl<SDValue> &InVals) const {
2671 MachineFunction &MF = DAG.getMachineFunction();
2672 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2673 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2675 const Function* Fn = MF.getFunction();
2676 if (Fn->hasExternalLinkage() &&
2677 Subtarget->isTargetCygMing() &&
2678 Fn->getName() == "main")
2679 FuncInfo->setForceFramePointer(true);
2681 MachineFrameInfo *MFI = MF.getFrameInfo();
2682 bool Is64Bit = Subtarget->is64Bit();
2683 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2685 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2686 "Var args not supported with calling convention fastcc, ghc or hipe");
2688 if (CallConv == CallingConv::X86_INTR) {
2689 bool isLegal = Ins.size() == 1 ||
2690 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2691 (!Is64Bit && Ins[1].VT == MVT::i32)));
2693 report_fatal_error("X86 interrupts may take one or two arguments");
2696 // Assign locations to all of the incoming arguments.
2697 SmallVector<CCValAssign, 16> ArgLocs;
2698 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2700 // Allocate shadow area for Win64
2702 CCInfo.AllocateStack(32, 8);
2704 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2706 unsigned LastVal = ~0U;
2708 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2709 CCValAssign &VA = ArgLocs[i];
2710 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2712 assert(VA.getValNo() != LastVal &&
2713 "Don't support value assigned to multiple locs yet");
2715 LastVal = VA.getValNo();
2717 if (VA.isRegLoc()) {
2718 EVT RegVT = VA.getLocVT();
2719 const TargetRegisterClass *RC;
2720 if (RegVT == MVT::i32)
2721 RC = &X86::GR32RegClass;
2722 else if (Is64Bit && RegVT == MVT::i64)
2723 RC = &X86::GR64RegClass;
2724 else if (RegVT == MVT::f32)
2725 RC = &X86::FR32RegClass;
2726 else if (RegVT == MVT::f64)
2727 RC = &X86::FR64RegClass;
2728 else if (RegVT == MVT::f128)
2729 RC = &X86::FR128RegClass;
2730 else if (RegVT.is512BitVector())
2731 RC = &X86::VR512RegClass;
2732 else if (RegVT.is256BitVector())
2733 RC = &X86::VR256RegClass;
2734 else if (RegVT.is128BitVector())
2735 RC = &X86::VR128RegClass;
2736 else if (RegVT == MVT::x86mmx)
2737 RC = &X86::VR64RegClass;
2738 else if (RegVT == MVT::i1)
2739 RC = &X86::VK1RegClass;
2740 else if (RegVT == MVT::v8i1)
2741 RC = &X86::VK8RegClass;
2742 else if (RegVT == MVT::v16i1)
2743 RC = &X86::VK16RegClass;
2744 else if (RegVT == MVT::v32i1)
2745 RC = &X86::VK32RegClass;
2746 else if (RegVT == MVT::v64i1)
2747 RC = &X86::VK64RegClass;
2749 llvm_unreachable("Unknown argument type!");
2751 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2752 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2754 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2755 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2757 if (VA.getLocInfo() == CCValAssign::SExt)
2758 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2759 DAG.getValueType(VA.getValVT()));
2760 else if (VA.getLocInfo() == CCValAssign::ZExt)
2761 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2762 DAG.getValueType(VA.getValVT()));
2763 else if (VA.getLocInfo() == CCValAssign::BCvt)
2764 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2766 if (VA.isExtInLoc()) {
2767 // Handle MMX values passed in XMM regs.
2768 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2769 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2771 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2774 assert(VA.isMemLoc());
2775 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2778 // If value is passed via pointer - do a load.
2779 if (VA.getLocInfo() == CCValAssign::Indirect)
2780 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2781 MachinePointerInfo(), false, false, false, 0);
2783 InVals.push_back(ArgValue);
2786 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2787 // All x86 ABIs require that for returning structs by value we copy the
2788 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2789 // the argument into a virtual register so that we can access it from the
2791 if (Ins[i].Flags.isSRet()) {
2792 unsigned Reg = FuncInfo->getSRetReturnReg();
2794 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2795 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2796 FuncInfo->setSRetReturnReg(Reg);
2798 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2799 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2804 unsigned StackSize = CCInfo.getNextStackOffset();
2805 // Align stack specially for tail calls.
2806 if (shouldGuaranteeTCO(CallConv,
2807 MF.getTarget().Options.GuaranteedTailCallOpt))
2808 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2810 // If the function takes variable number of arguments, make a frame index for
2811 // the start of the first vararg value... for expansion of llvm.va_start. We
2812 // can skip this if there are no va_start calls.
2813 if (MFI->hasVAStart() &&
2814 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2815 CallConv != CallingConv::X86_ThisCall))) {
2816 FuncInfo->setVarArgsFrameIndex(
2817 MFI->CreateFixedObject(1, StackSize, true));
2820 // Figure out if XMM registers are in use.
2821 assert(!(Subtarget->useSoftFloat() &&
2822 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2823 "SSE register cannot be used when SSE is disabled!");
2825 // 64-bit calling conventions support varargs and register parameters, so we
2826 // have to do extra work to spill them in the prologue.
2827 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2828 // Find the first unallocated argument registers.
2829 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2830 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2831 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2832 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2833 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2834 "SSE register cannot be used when SSE is disabled!");
2836 // Gather all the live in physical registers.
2837 SmallVector<SDValue, 6> LiveGPRs;
2838 SmallVector<SDValue, 8> LiveXMMRegs;
2840 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2841 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2843 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2845 if (!ArgXMMs.empty()) {
2846 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2847 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2848 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2849 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2850 LiveXMMRegs.push_back(
2851 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2856 // Get to the caller-allocated home save location. Add 8 to account
2857 // for the return address.
2858 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2859 FuncInfo->setRegSaveFrameIndex(
2860 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2861 // Fixup to set vararg frame on shadow area (4 x i64).
2863 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2865 // For X86-64, if there are vararg parameters that are passed via
2866 // registers, then we must store them to their spots on the stack so
2867 // they may be loaded by deferencing the result of va_next.
2868 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2869 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2870 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2871 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2874 // Store the integer parameter registers.
2875 SmallVector<SDValue, 8> MemOps;
2876 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2877 getPointerTy(DAG.getDataLayout()));
2878 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2879 for (SDValue Val : LiveGPRs) {
2880 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2881 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2883 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2884 MachinePointerInfo::getFixedStack(
2885 DAG.getMachineFunction(),
2886 FuncInfo->getRegSaveFrameIndex(), Offset),
2888 MemOps.push_back(Store);
2892 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2893 // Now store the XMM (fp + vector) parameter registers.
2894 SmallVector<SDValue, 12> SaveXMMOps;
2895 SaveXMMOps.push_back(Chain);
2896 SaveXMMOps.push_back(ALVal);
2897 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2898 FuncInfo->getRegSaveFrameIndex(), dl));
2899 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2900 FuncInfo->getVarArgsFPOffset(), dl));
2901 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2903 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2904 MVT::Other, SaveXMMOps));
2907 if (!MemOps.empty())
2908 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2911 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2912 // Find the largest legal vector type.
2913 MVT VecVT = MVT::Other;
2914 // FIXME: Only some x86_32 calling conventions support AVX512.
2915 if (Subtarget->hasAVX512() &&
2916 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2917 CallConv == CallingConv::Intel_OCL_BI)))
2918 VecVT = MVT::v16f32;
2919 else if (Subtarget->hasAVX())
2921 else if (Subtarget->hasSSE2())
2924 // We forward some GPRs and some vector types.
2925 SmallVector<MVT, 2> RegParmTypes;
2926 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2927 RegParmTypes.push_back(IntVT);
2928 if (VecVT != MVT::Other)
2929 RegParmTypes.push_back(VecVT);
2931 // Compute the set of forwarded registers. The rest are scratch.
2932 SmallVectorImpl<ForwardedRegister> &Forwards =
2933 FuncInfo->getForwardedMustTailRegParms();
2934 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2936 // Conservatively forward AL on x86_64, since it might be used for varargs.
2937 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2938 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2939 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2942 // Copy all forwards from physical to virtual registers.
2943 for (ForwardedRegister &F : Forwards) {
2944 // FIXME: Can we use a less constrained schedule?
2945 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2946 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2947 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2951 // Some CCs need callee pop.
2952 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2953 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2954 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2955 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2956 // X86 interrupts must pop the error code if present
2957 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2959 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2960 // If this is an sret function, the return should pop the hidden pointer.
2961 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2962 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2963 argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2964 FuncInfo->setBytesToPopOnReturn(4);
2968 // RegSaveFrameIndex is X86-64 only.
2969 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2970 if (CallConv == CallingConv::X86_FastCall ||
2971 CallConv == CallingConv::X86_ThisCall)
2972 // fastcc functions can't have varargs.
2973 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2976 FuncInfo->setArgumentStackSize(StackSize);
2978 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2979 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2980 if (Personality == EHPersonality::CoreCLR) {
2982 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2983 // that we'd prefer this slot be allocated towards the bottom of the frame
2984 // (i.e. near the stack pointer after allocating the frame). Every
2985 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2986 // offset from the bottom of this and each funclet's frame must be the
2987 // same, so the size of funclets' (mostly empty) frames is dictated by
2988 // how far this slot is from the bottom (since they allocate just enough
2989 // space to accomodate holding this slot at the correct offset).
2990 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2991 EHInfo->PSPSymFrameIdx = PSPSymFI;
2999 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
3000 SDValue StackPtr, SDValue Arg,
3001 SDLoc dl, SelectionDAG &DAG,
3002 const CCValAssign &VA,
3003 ISD::ArgFlagsTy Flags) const {
3004 unsigned LocMemOffset = VA.getLocMemOffset();
3005 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3006 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3008 if (Flags.isByVal())
3009 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3011 return DAG.getStore(
3012 Chain, dl, Arg, PtrOff,
3013 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3017 /// Emit a load of return address if tail call
3018 /// optimization is performed and it is required.
3020 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3021 SDValue &OutRetAddr, SDValue Chain,
3022 bool IsTailCall, bool Is64Bit,
3023 int FPDiff, SDLoc dl) const {
3024 // Adjust the Return address stack slot.
3025 EVT VT = getPointerTy(DAG.getDataLayout());
3026 OutRetAddr = getReturnAddressFrameIndex(DAG);
3028 // Load the "old" Return address.
3029 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3030 false, false, false, 0);
3031 return SDValue(OutRetAddr.getNode(), 1);
3034 /// Emit a store of the return address if tail call
3035 /// optimization is performed and it is required (FPDiff!=0).
3036 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3037 SDValue Chain, SDValue RetAddrFrIdx,
3038 EVT PtrVT, unsigned SlotSize,
3039 int FPDiff, SDLoc dl) {
3040 // Store the return address to the appropriate stack slot.
3041 if (!FPDiff) return Chain;
3042 // Calculate the new stack slot for the return address.
3043 int NewReturnAddrFI =
3044 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3046 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3047 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3048 MachinePointerInfo::getFixedStack(
3049 DAG.getMachineFunction(), NewReturnAddrFI),
3054 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3055 /// operation of specified width.
3056 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3058 unsigned NumElems = VT.getVectorNumElements();
3059 SmallVector<int, 8> Mask;
3060 Mask.push_back(NumElems);
3061 for (unsigned i = 1; i != NumElems; ++i)
3063 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3067 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3068 SmallVectorImpl<SDValue> &InVals) const {
3069 SelectionDAG &DAG = CLI.DAG;
3071 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3072 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3073 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3074 SDValue Chain = CLI.Chain;
3075 SDValue Callee = CLI.Callee;
3076 CallingConv::ID CallConv = CLI.CallConv;
3077 bool &isTailCall = CLI.IsTailCall;
3078 bool isVarArg = CLI.IsVarArg;
3080 MachineFunction &MF = DAG.getMachineFunction();
3081 bool Is64Bit = Subtarget->is64Bit();
3082 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3083 StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3084 bool IsSibcall = false;
3085 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3086 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3088 if (CallConv == CallingConv::X86_INTR)
3089 report_fatal_error("X86 interrupts may not be called directly");
3091 if (Attr.getValueAsString() == "true")
3094 if (Subtarget->isPICStyleGOT() &&
3095 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3096 // If we are using a GOT, disable tail calls to external symbols with
3097 // default visibility. Tail calling such a symbol requires using a GOT
3098 // relocation, which forces early binding of the symbol. This breaks code
3099 // that require lazy function symbol resolution. Using musttail or
3100 // GuaranteedTailCallOpt will override this.
3101 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3102 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3103 G->getGlobal()->hasDefaultVisibility()))
3107 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3109 // Force this to be a tail call. The verifier rules are enough to ensure
3110 // that we can lower this successfully without moving the return address
3113 } else if (isTailCall) {
3114 // Check if it's really possible to do a tail call.
3115 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3116 isVarArg, SR != NotStructReturn,
3117 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3118 Outs, OutVals, Ins, DAG);
3120 // Sibcalls are automatically detected tailcalls which do not require
3122 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3129 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3130 "Var args not supported with calling convention fastcc, ghc or hipe");
3132 // Analyze operands of the call, assigning locations to each operand.
3133 SmallVector<CCValAssign, 16> ArgLocs;
3134 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3136 // Allocate shadow area for Win64
3138 CCInfo.AllocateStack(32, 8);
3140 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3142 // Get a count of how many bytes are to be pushed on the stack.
3143 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3145 // This is a sibcall. The memory operands are available in caller's
3146 // own caller's stack.
3148 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3149 canGuaranteeTCO(CallConv))
3150 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3153 if (isTailCall && !IsSibcall && !IsMustTail) {
3154 // Lower arguments at fp - stackoffset + fpdiff.
3155 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3157 FPDiff = NumBytesCallerPushed - NumBytes;
3159 // Set the delta of movement of the returnaddr stackslot.
3160 // But only set if delta is greater than previous delta.
3161 if (FPDiff < X86Info->getTCReturnAddrDelta())
3162 X86Info->setTCReturnAddrDelta(FPDiff);
3165 unsigned NumBytesToPush = NumBytes;
3166 unsigned NumBytesToPop = NumBytes;
3168 // If we have an inalloca argument, all stack space has already been allocated
3169 // for us and be right at the top of the stack. We don't support multiple
3170 // arguments passed in memory when using inalloca.
3171 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3173 if (!ArgLocs.back().isMemLoc())
3174 report_fatal_error("cannot use inalloca attribute on a register "
3176 if (ArgLocs.back().getLocMemOffset() != 0)
3177 report_fatal_error("any parameter with the inalloca attribute must be "
3178 "the only memory argument");
3182 Chain = DAG.getCALLSEQ_START(
3183 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3185 SDValue RetAddrFrIdx;
3186 // Load return address for tail calls.
3187 if (isTailCall && FPDiff)
3188 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3189 Is64Bit, FPDiff, dl);
3191 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3192 SmallVector<SDValue, 8> MemOpChains;
3195 // Walk the register/memloc assignments, inserting copies/loads. In the case
3196 // of tail call optimization arguments are handle later.
3197 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199 // Skip inalloca arguments, they have already been written.
3200 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3201 if (Flags.isInAlloca())
3204 CCValAssign &VA = ArgLocs[i];
3205 EVT RegVT = VA.getLocVT();
3206 SDValue Arg = OutVals[i];
3207 bool isByVal = Flags.isByVal();
3209 // Promote the value if needed.
3210 switch (VA.getLocInfo()) {
3211 default: llvm_unreachable("Unknown loc info!");
3212 case CCValAssign::Full: break;
3213 case CCValAssign::SExt:
3214 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3216 case CCValAssign::ZExt:
3217 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3219 case CCValAssign::AExt:
3220 if (Arg.getValueType().isVector() &&
3221 Arg.getValueType().getVectorElementType() == MVT::i1)
3222 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3223 else if (RegVT.is128BitVector()) {
3224 // Special case: passing MMX values in XMM registers.
3225 Arg = DAG.getBitcast(MVT::i64, Arg);
3226 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3227 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3229 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3231 case CCValAssign::BCvt:
3232 Arg = DAG.getBitcast(RegVT, Arg);
3234 case CCValAssign::Indirect: {
3235 // Store the argument.
3236 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3237 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3238 Chain = DAG.getStore(
3239 Chain, dl, Arg, SpillSlot,
3240 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3247 if (VA.isRegLoc()) {
3248 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3249 if (isVarArg && IsWin64) {
3250 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3251 // shadow reg if callee is a varargs function.
3252 unsigned ShadowReg = 0;
3253 switch (VA.getLocReg()) {
3254 case X86::XMM0: ShadowReg = X86::RCX; break;
3255 case X86::XMM1: ShadowReg = X86::RDX; break;
3256 case X86::XMM2: ShadowReg = X86::R8; break;
3257 case X86::XMM3: ShadowReg = X86::R9; break;
3260 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3262 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3263 assert(VA.isMemLoc());
3264 if (!StackPtr.getNode())
3265 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3266 getPointerTy(DAG.getDataLayout()));
3267 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3268 dl, DAG, VA, Flags));
3272 if (!MemOpChains.empty())
3273 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3275 if (Subtarget->isPICStyleGOT()) {
3276 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3279 RegsToPass.push_back(std::make_pair(
3280 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3281 getPointerTy(DAG.getDataLayout()))));
3283 // If we are tail calling and generating PIC/GOT style code load the
3284 // address of the callee into ECX. The value in ecx is used as target of
3285 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3286 // for tail calls on PIC/GOT architectures. Normally we would just put the
3287 // address of GOT into ebx and then call target@PLT. But for tail calls
3288 // ebx would be restored (since ebx is callee saved) before jumping to the
3291 // Note: The actual moving to ECX is done further down.
3292 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3293 if (G && !G->getGlobal()->hasLocalLinkage() &&
3294 G->getGlobal()->hasDefaultVisibility())
3295 Callee = LowerGlobalAddress(Callee, DAG);
3296 else if (isa<ExternalSymbolSDNode>(Callee))
3297 Callee = LowerExternalSymbol(Callee, DAG);
3301 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3302 // From AMD64 ABI document:
3303 // For calls that may call functions that use varargs or stdargs
3304 // (prototype-less calls or calls to functions containing ellipsis (...) in
3305 // the declaration) %al is used as hidden argument to specify the number
3306 // of SSE registers used. The contents of %al do not need to match exactly
3307 // the number of registers, but must be an ubound on the number of SSE
3308 // registers used and is in the range 0 - 8 inclusive.
3310 // Count the number of XMM registers allocated.
3311 static const MCPhysReg XMMArgRegs[] = {
3312 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3313 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3315 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3316 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3317 && "SSE registers cannot be used when SSE is disabled");
3319 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3320 DAG.getConstant(NumXMMRegs, dl,
3324 if (isVarArg && IsMustTail) {
3325 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3326 for (const auto &F : Forwards) {
3327 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3328 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3332 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3333 // don't need this because the eligibility check rejects calls that require
3334 // shuffling arguments passed in memory.
3335 if (!IsSibcall && isTailCall) {
3336 // Force all the incoming stack arguments to be loaded from the stack
3337 // before any new outgoing arguments are stored to the stack, because the
3338 // outgoing stack slots may alias the incoming argument stack slots, and
3339 // the alias isn't otherwise explicit. This is slightly more conservative
3340 // than necessary, because it means that each store effectively depends
3341 // on every argument instead of just those arguments it would clobber.
3342 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3344 SmallVector<SDValue, 8> MemOpChains2;
3347 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3348 CCValAssign &VA = ArgLocs[i];
3351 assert(VA.isMemLoc());
3352 SDValue Arg = OutVals[i];
3353 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3354 // Skip inalloca arguments. They don't require any work.
3355 if (Flags.isInAlloca())
3357 // Create frame index.
3358 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3359 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3360 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3361 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3363 if (Flags.isByVal()) {
3364 // Copy relative to framepointer.
3365 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3366 if (!StackPtr.getNode())
3367 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3368 getPointerTy(DAG.getDataLayout()));
3369 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3372 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3376 // Store relative to framepointer.
3377 MemOpChains2.push_back(DAG.getStore(
3378 ArgChain, dl, Arg, FIN,
3379 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3384 if (!MemOpChains2.empty())
3385 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3387 // Store the return address to the appropriate stack slot.
3388 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3389 getPointerTy(DAG.getDataLayout()),
3390 RegInfo->getSlotSize(), FPDiff, dl);
3393 // Build a sequence of copy-to-reg nodes chained together with token chain
3394 // and flag operands which copy the outgoing args into registers.
3396 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3397 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3398 RegsToPass[i].second, InFlag);
3399 InFlag = Chain.getValue(1);
3402 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3403 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3404 // In the 64-bit large code model, we have to make all calls
3405 // through a register, since the call instruction's 32-bit
3406 // pc-relative offset may not be large enough to hold the whole
3408 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3409 // If the callee is a GlobalAddress node (quite common, every direct call
3410 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3412 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3414 // We should use extra load for direct calls to dllimported functions in
3416 const GlobalValue *GV = G->getGlobal();
3417 if (!GV->hasDLLImportStorageClass()) {
3418 unsigned char OpFlags = 0;
3419 bool ExtraLoad = false;
3420 unsigned WrapperKind = ISD::DELETED_NODE;
3422 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3423 // external symbols most go through the PLT in PIC mode. If the symbol
3424 // has hidden or protected visibility, or if it is static or local, then
3425 // we don't need to use the PLT - we can directly call it.
3426 if (Subtarget->isTargetELF() &&
3427 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3428 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3429 OpFlags = X86II::MO_PLT;
3430 } else if (Subtarget->isPICStyleStubAny() &&
3431 !GV->isStrongDefinitionForLinker() &&
3432 (!Subtarget->getTargetTriple().isMacOSX() ||
3433 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3434 // PC-relative references to external symbols should go through $stub,
3435 // unless we're building with the leopard linker or later, which
3436 // automatically synthesizes these stubs.
3437 OpFlags = X86II::MO_DARWIN_STUB;
3438 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3439 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3440 // If the function is marked as non-lazy, generate an indirect call
3441 // which loads from the GOT directly. This avoids runtime overhead
3442 // at the cost of eager binding (and one extra byte of encoding).
3443 OpFlags = X86II::MO_GOTPCREL;
3444 WrapperKind = X86ISD::WrapperRIP;
3448 Callee = DAG.getTargetGlobalAddress(
3449 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3451 // Add a wrapper if needed.
3452 if (WrapperKind != ISD::DELETED_NODE)
3453 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3454 getPointerTy(DAG.getDataLayout()), Callee);
3455 // Add extra indirection if needed.
3457 Callee = DAG.getLoad(
3458 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3459 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3462 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3463 unsigned char OpFlags = 0;
3465 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3466 // external symbols should go through the PLT.
3467 if (Subtarget->isTargetELF() &&
3468 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3469 OpFlags = X86II::MO_PLT;
3470 } else if (Subtarget->isPICStyleStubAny() &&
3471 (!Subtarget->getTargetTriple().isMacOSX() ||
3472 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3473 // PC-relative references to external symbols should go through $stub,
3474 // unless we're building with the leopard linker or later, which
3475 // automatically synthesizes these stubs.
3476 OpFlags = X86II::MO_DARWIN_STUB;
3479 Callee = DAG.getTargetExternalSymbol(
3480 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3481 } else if (Subtarget->isTarget64BitILP32() &&
3482 Callee->getValueType(0) == MVT::i32) {
3483 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3484 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3487 // Returns a chain & a flag for retval copy to use.
3488 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3489 SmallVector<SDValue, 8> Ops;
3491 if (!IsSibcall && isTailCall) {
3492 Chain = DAG.getCALLSEQ_END(Chain,
3493 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3494 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3495 InFlag = Chain.getValue(1);
3498 Ops.push_back(Chain);
3499 Ops.push_back(Callee);
3502 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3504 // Add argument registers to the end of the list so that they are known live
3506 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3507 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3508 RegsToPass[i].second.getValueType()));
3510 // Add a register mask operand representing the call-preserved registers.
3511 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3512 assert(Mask && "Missing call preserved mask for calling convention");
3514 // If this is an invoke in a 32-bit function using a funclet-based
3515 // personality, assume the function clobbers all registers. If an exception
3516 // is thrown, the runtime will not restore CSRs.
3517 // FIXME: Model this more precisely so that we can register allocate across
3518 // the normal edge and spill and fill across the exceptional edge.
3519 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3520 const Function *CallerFn = MF.getFunction();
3521 EHPersonality Pers =
3522 CallerFn->hasPersonalityFn()
3523 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3524 : EHPersonality::Unknown;
3525 if (isFuncletEHPersonality(Pers))
3526 Mask = RegInfo->getNoPreservedMask();
3529 Ops.push_back(DAG.getRegisterMask(Mask));
3531 if (InFlag.getNode())
3532 Ops.push_back(InFlag);
3536 //// If this is the first return lowered for this function, add the regs
3537 //// to the liveout set for the function.
3538 // This isn't right, although it's probably harmless on x86; liveouts
3539 // should be computed from returns not tail calls. Consider a void
3540 // function making a tail call to a function returning int.
3541 MF.getFrameInfo()->setHasTailCall();
3542 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3545 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3546 InFlag = Chain.getValue(1);
3548 // Create the CALLSEQ_END node.
3549 unsigned NumBytesForCalleeToPop;
3550 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3551 DAG.getTarget().Options.GuaranteedTailCallOpt))
3552 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3553 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3554 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3555 SR == StackStructReturn)
3556 // If this is a call to a struct-return function, the callee
3557 // pops the hidden struct pointer, so we have to push it back.
3558 // This is common for Darwin/X86, Linux & Mingw32 targets.
3559 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3560 NumBytesForCalleeToPop = 4;
3562 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3564 // Returns a flag for retval copy to use.
3566 Chain = DAG.getCALLSEQ_END(Chain,
3567 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3568 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3571 InFlag = Chain.getValue(1);
3574 // Handle result values, copying them out of physregs into vregs that we
3576 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3577 Ins, dl, DAG, InVals);
3580 //===----------------------------------------------------------------------===//
3581 // Fast Calling Convention (tail call) implementation
3582 //===----------------------------------------------------------------------===//
3584 // Like std call, callee cleans arguments, convention except that ECX is
3585 // reserved for storing the tail called function address. Only 2 registers are
3586 // free for argument passing (inreg). Tail call optimization is performed
3588 // * tailcallopt is enabled
3589 // * caller/callee are fastcc
3590 // On X86_64 architecture with GOT-style position independent code only local
3591 // (within module) calls are supported at the moment.
3592 // To keep the stack aligned according to platform abi the function
3593 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3594 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3595 // If a tail called function callee has more arguments than the caller the
3596 // caller needs to make sure that there is room to move the RETADDR to. This is
3597 // achieved by reserving an area the size of the argument delta right after the
3598 // original RETADDR, but before the saved framepointer or the spilled registers
3599 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3611 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3614 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3615 SelectionDAG& DAG) const {
3616 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3617 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3618 unsigned StackAlignment = TFI.getStackAlignment();
3619 uint64_t AlignMask = StackAlignment - 1;
3620 int64_t Offset = StackSize;
3621 unsigned SlotSize = RegInfo->getSlotSize();
3622 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3623 // Number smaller than 12 so just add the difference.
3624 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3626 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3627 Offset = ((~AlignMask) & Offset) + StackAlignment +
3628 (StackAlignment-SlotSize);
3633 /// Return true if the given stack call argument is already available in the
3634 /// same position (relatively) of the caller's incoming argument stack.
3636 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3637 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3638 const X86InstrInfo *TII) {
3639 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3641 if (Arg.getOpcode() == ISD::CopyFromReg) {
3642 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3643 if (!TargetRegisterInfo::isVirtualRegister(VR))
3645 MachineInstr *Def = MRI->getVRegDef(VR);
3648 if (!Flags.isByVal()) {
3649 if (!TII->isLoadFromStackSlot(Def, FI))
3652 unsigned Opcode = Def->getOpcode();
3653 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3654 Opcode == X86::LEA64_32r) &&
3655 Def->getOperand(1).isFI()) {
3656 FI = Def->getOperand(1).getIndex();
3657 Bytes = Flags.getByValSize();
3661 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3662 if (Flags.isByVal())
3663 // ByVal argument is passed in as a pointer but it's now being
3664 // dereferenced. e.g.
3665 // define @foo(%struct.X* %A) {
3666 // tail call @bar(%struct.X* byval %A)
3669 SDValue Ptr = Ld->getBasePtr();
3670 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3673 FI = FINode->getIndex();
3674 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3675 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3676 FI = FINode->getIndex();
3677 Bytes = Flags.getByValSize();
3681 assert(FI != INT_MAX);
3682 if (!MFI->isFixedObjectIndex(FI))
3684 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3687 /// Check whether the call is eligible for tail call optimization. Targets
3688 /// that want to do tail call optimization should implement this function.
3689 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3690 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3691 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3692 const SmallVectorImpl<ISD::OutputArg> &Outs,
3693 const SmallVectorImpl<SDValue> &OutVals,
3694 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3695 if (!mayTailCallThisCC(CalleeCC))
3698 // If -tailcallopt is specified, make fastcc functions tail-callable.
3699 MachineFunction &MF = DAG.getMachineFunction();
3700 const Function *CallerF = MF.getFunction();
3702 // If the function return type is x86_fp80 and the callee return type is not,
3703 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3704 // perform a tailcall optimization here.
3705 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3708 CallingConv::ID CallerCC = CallerF->getCallingConv();
3709 bool CCMatch = CallerCC == CalleeCC;
3710 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3711 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3713 // Win64 functions have extra shadow space for argument homing. Don't do the
3714 // sibcall if the caller and callee have mismatched expectations for this
3716 if (IsCalleeWin64 != IsCallerWin64)
3719 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3720 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3725 // Look for obvious safe cases to perform tail call optimization that do not
3726 // require ABI changes. This is what gcc calls sibcall.
3728 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3729 // emit a special epilogue.
3730 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3731 if (RegInfo->needsStackRealignment(MF))
3734 // Also avoid sibcall optimization if either caller or callee uses struct
3735 // return semantics.
3736 if (isCalleeStructRet || isCallerStructRet)
3739 // Do not sibcall optimize vararg calls unless all arguments are passed via
3741 if (isVarArg && !Outs.empty()) {
3742 // Optimizing for varargs on Win64 is unlikely to be safe without
3743 // additional testing.
3744 if (IsCalleeWin64 || IsCallerWin64)
3747 SmallVector<CCValAssign, 16> ArgLocs;
3748 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3751 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3752 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3753 if (!ArgLocs[i].isRegLoc())
3757 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3758 // stack. Therefore, if it's not used by the call it is not safe to optimize
3759 // this into a sibcall.
3760 bool Unused = false;
3761 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3768 SmallVector<CCValAssign, 16> RVLocs;
3769 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3771 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3772 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3773 CCValAssign &VA = RVLocs[i];
3774 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3779 // If the calling conventions do not match, then we'd better make sure the
3780 // results are returned in the same way as what the caller expects.
3782 SmallVector<CCValAssign, 16> RVLocs1;
3783 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3785 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3787 SmallVector<CCValAssign, 16> RVLocs2;
3788 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3790 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3792 if (RVLocs1.size() != RVLocs2.size())
3794 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3795 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3797 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3799 if (RVLocs1[i].isRegLoc()) {
3800 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3803 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3809 unsigned StackArgsSize = 0;
3811 // If the callee takes no arguments then go on to check the results of the
3813 if (!Outs.empty()) {
3814 // Check if stack adjustment is needed. For now, do not do this if any
3815 // argument is passed on the stack.
3816 SmallVector<CCValAssign, 16> ArgLocs;
3817 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3820 // Allocate shadow area for Win64
3822 CCInfo.AllocateStack(32, 8);
3824 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3825 StackArgsSize = CCInfo.getNextStackOffset();
3827 if (CCInfo.getNextStackOffset()) {
3828 // Check if the arguments are already laid out in the right way as
3829 // the caller's fixed stack objects.
3830 MachineFrameInfo *MFI = MF.getFrameInfo();
3831 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3832 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3833 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3834 CCValAssign &VA = ArgLocs[i];
3835 SDValue Arg = OutVals[i];
3836 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3837 if (VA.getLocInfo() == CCValAssign::Indirect)
3839 if (!VA.isRegLoc()) {
3840 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3847 // If the tailcall address may be in a register, then make sure it's
3848 // possible to register allocate for it. In 32-bit, the call address can
3849 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3850 // callee-saved registers are restored. These happen to be the same
3851 // registers used to pass 'inreg' arguments so watch out for those.
3852 if (!Subtarget->is64Bit() &&
3853 ((!isa<GlobalAddressSDNode>(Callee) &&
3854 !isa<ExternalSymbolSDNode>(Callee)) ||
3855 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3856 unsigned NumInRegs = 0;
3857 // In PIC we need an extra register to formulate the address computation
3859 unsigned MaxInRegs =
3860 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3862 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3863 CCValAssign &VA = ArgLocs[i];
3866 unsigned Reg = VA.getLocReg();
3869 case X86::EAX: case X86::EDX: case X86::ECX:
3870 if (++NumInRegs == MaxInRegs)
3878 bool CalleeWillPop =
3879 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3880 MF.getTarget().Options.GuaranteedTailCallOpt);
3882 if (unsigned BytesToPop =
3883 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3884 // If we have bytes to pop, the callee must pop them.
3885 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3886 if (!CalleePopMatches)
3888 } else if (CalleeWillPop && StackArgsSize > 0) {
3889 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3897 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3898 const TargetLibraryInfo *libInfo) const {
3899 return X86::createFastISel(funcInfo, libInfo);
3902 //===----------------------------------------------------------------------===//
3903 // Other Lowering Hooks
3904 //===----------------------------------------------------------------------===//
3906 static bool MayFoldLoad(SDValue Op) {
3907 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3910 static bool MayFoldIntoStore(SDValue Op) {
3911 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3914 static bool isTargetShuffle(unsigned Opcode) {
3916 default: return false;
3917 case X86ISD::BLENDI:
3918 case X86ISD::PSHUFB:
3919 case X86ISD::PSHUFD:
3920 case X86ISD::PSHUFHW:
3921 case X86ISD::PSHUFLW:
3923 case X86ISD::INSERTPS:
3924 case X86ISD::PALIGNR:
3925 case X86ISD::MOVLHPS:
3926 case X86ISD::MOVLHPD:
3927 case X86ISD::MOVHLPS:
3928 case X86ISD::MOVLPS:
3929 case X86ISD::MOVLPD:
3930 case X86ISD::MOVSHDUP:
3931 case X86ISD::MOVSLDUP:
3932 case X86ISD::MOVDDUP:
3935 case X86ISD::UNPCKL:
3936 case X86ISD::UNPCKH:
3937 case X86ISD::VPERMILPI:
3938 case X86ISD::VPERM2X128:
3939 case X86ISD::VPERMI:
3940 case X86ISD::VPERMV:
3941 case X86ISD::VPERMV3:
3946 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3947 SDValue V1, unsigned TargetMask,
3948 SelectionDAG &DAG) {
3950 default: llvm_unreachable("Unknown x86 shuffle node");
3951 case X86ISD::PSHUFD:
3952 case X86ISD::PSHUFHW:
3953 case X86ISD::PSHUFLW:
3954 case X86ISD::VPERMILPI:
3955 case X86ISD::VPERMI:
3956 return DAG.getNode(Opc, dl, VT, V1,
3957 DAG.getConstant(TargetMask, dl, MVT::i8));
3961 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3962 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3964 default: llvm_unreachable("Unknown x86 shuffle node");
3965 case X86ISD::MOVLHPS:
3966 case X86ISD::MOVLHPD:
3967 case X86ISD::MOVHLPS:
3968 case X86ISD::MOVLPS:
3969 case X86ISD::MOVLPD:
3972 case X86ISD::UNPCKL:
3973 case X86ISD::UNPCKH:
3974 return DAG.getNode(Opc, dl, VT, V1, V2);
3978 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3979 MachineFunction &MF = DAG.getMachineFunction();
3980 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3981 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3982 int ReturnAddrIndex = FuncInfo->getRAIndex();
3984 if (ReturnAddrIndex == 0) {
3985 // Set up a frame object for the return address.
3986 unsigned SlotSize = RegInfo->getSlotSize();
3987 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3990 FuncInfo->setRAIndex(ReturnAddrIndex);
3993 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3997 bool hasSymbolicDisplacement) {
3998 // Offset should fit into 32 bit immediate field.
3999 if (!isInt<32>(Offset))
4002 // If we don't have a symbolic displacement - we don't have any extra
4004 if (!hasSymbolicDisplacement)
4007 // FIXME: Some tweaks might be needed for medium code model.
4008 if (M != CodeModel::Small && M != CodeModel::Kernel)
4011 // For small code model we assume that latest object is 16MB before end of 31
4012 // bits boundary. We may also accept pretty large negative constants knowing
4013 // that all objects are in the positive half of address space.
4014 if (M == CodeModel::Small && Offset < 16*1024*1024)
4017 // For kernel code model we know that all object resist in the negative half
4018 // of 32bits address space. We may not accept negative offsets, since they may
4019 // be just off and we may accept pretty large positive ones.
4020 if (M == CodeModel::Kernel && Offset >= 0)
4026 /// Determines whether the callee is required to pop its own arguments.
4027 /// Callee pop is necessary to support tail calls.
4028 bool X86::isCalleePop(CallingConv::ID CallingConv,
4029 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4030 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4031 // can guarantee TCO.
4032 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4035 switch (CallingConv) {
4038 case CallingConv::X86_StdCall:
4039 case CallingConv::X86_FastCall:
4040 case CallingConv::X86_ThisCall:
4041 case CallingConv::X86_VectorCall:
4046 /// \brief Return true if the condition is an unsigned comparison operation.
4047 static bool isX86CCUnsigned(unsigned X86CC) {
4049 default: llvm_unreachable("Invalid integer condition!");
4050 case X86::COND_E: return true;
4051 case X86::COND_G: return false;
4052 case X86::COND_GE: return false;
4053 case X86::COND_L: return false;
4054 case X86::COND_LE: return false;
4055 case X86::COND_NE: return true;
4056 case X86::COND_B: return true;
4057 case X86::COND_A: return true;
4058 case X86::COND_BE: return true;
4059 case X86::COND_AE: return true;
4063 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4064 switch (SetCCOpcode) {
4065 default: llvm_unreachable("Invalid integer condition!");
4066 case ISD::SETEQ: return X86::COND_E;
4067 case ISD::SETGT: return X86::COND_G;
4068 case ISD::SETGE: return X86::COND_GE;
4069 case ISD::SETLT: return X86::COND_L;
4070 case ISD::SETLE: return X86::COND_LE;
4071 case ISD::SETNE: return X86::COND_NE;
4072 case ISD::SETULT: return X86::COND_B;
4073 case ISD::SETUGT: return X86::COND_A;
4074 case ISD::SETULE: return X86::COND_BE;
4075 case ISD::SETUGE: return X86::COND_AE;
4079 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4080 /// condition code, returning the condition code and the LHS/RHS of the
4081 /// comparison to make.
4082 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4083 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4085 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4086 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4087 // X > -1 -> X == 0, jump !sign.
4088 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4089 return X86::COND_NS;
4091 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4092 // X < 0 -> X == 0, jump on sign.
4095 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4097 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4098 return X86::COND_LE;
4102 return TranslateIntegerX86CC(SetCCOpcode);
4105 // First determine if it is required or is profitable to flip the operands.
4107 // If LHS is a foldable load, but RHS is not, flip the condition.
4108 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4109 !ISD::isNON_EXTLoad(RHS.getNode())) {
4110 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4111 std::swap(LHS, RHS);
4114 switch (SetCCOpcode) {
4120 std::swap(LHS, RHS);
4124 // On a floating point condition, the flags are set as follows:
4126 // 0 | 0 | 0 | X > Y
4127 // 0 | 0 | 1 | X < Y
4128 // 1 | 0 | 0 | X == Y
4129 // 1 | 1 | 1 | unordered
4130 switch (SetCCOpcode) {
4131 default: llvm_unreachable("Condcode should be pre-legalized away");
4133 case ISD::SETEQ: return X86::COND_E;
4134 case ISD::SETOLT: // flipped
4136 case ISD::SETGT: return X86::COND_A;
4137 case ISD::SETOLE: // flipped
4139 case ISD::SETGE: return X86::COND_AE;
4140 case ISD::SETUGT: // flipped
4142 case ISD::SETLT: return X86::COND_B;
4143 case ISD::SETUGE: // flipped
4145 case ISD::SETLE: return X86::COND_BE;
4147 case ISD::SETNE: return X86::COND_NE;
4148 case ISD::SETUO: return X86::COND_P;
4149 case ISD::SETO: return X86::COND_NP;
4151 case ISD::SETUNE: return X86::COND_INVALID;
4155 /// Is there a floating point cmov for the specific X86 condition code?
4156 /// Current x86 isa includes the following FP cmov instructions:
4157 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4158 static bool hasFPCMov(unsigned X86CC) {
4175 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4177 unsigned Intrinsic) const {
4179 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4183 switch (IntrData->Type) {
4186 Info.opc = ISD::INTRINSIC_W_CHAIN;
4187 Info.memVT = MVT::getVT(I.getType());
4188 Info.ptrVal = I.getArgOperand(0);
4190 Info.align = (IntrData->Type == LOADA ? Info.memVT.getSizeInBits()/8 : 1);
4192 Info.readMem = true;
4193 Info.writeMem = false;
4203 /// Returns true if the target can instruction select the
4204 /// specified FP immediate natively. If false, the legalizer will
4205 /// materialize the FP immediate as a load from a constant pool.
4206 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4207 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4208 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4214 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4215 ISD::LoadExtType ExtTy,
4217 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4218 // relocation target a movq or addq instruction: don't let the load shrink.
4219 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4220 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4221 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4222 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4226 /// \brief Returns true if it is beneficial to convert a load of a constant
4227 /// to just the constant itself.
4228 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4230 assert(Ty->isIntegerTy());
4232 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4233 if (BitSize == 0 || BitSize > 64)
4238 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4239 unsigned Index) const {
4240 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4243 return (Index == 0 || Index == ResVT.getVectorNumElements());
4246 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4247 // Speculate cttz only if we can directly use TZCNT.
4248 return Subtarget->hasBMI();
4251 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4252 // Speculate ctlz only if we can directly use LZCNT.
4253 return Subtarget->hasLZCNT();
4256 /// Return true if every element in Mask, beginning
4257 /// from position Pos and ending in Pos+Size is undef.
4258 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4259 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4265 /// Return true if Val is undef or if its value falls within the
4266 /// specified range (L, H].
4267 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4268 return (Val < 0) || (Val >= Low && Val < Hi);
4271 /// Val is either less than zero (undef) or equal to the specified value.
4272 static bool isUndefOrEqual(int Val, int CmpVal) {
4273 return (Val < 0 || Val == CmpVal);
4276 /// Return true if every element in Mask, beginning
4277 /// from position Pos and ending in Pos+Size, falls within the specified
4278 /// sequential range (Low, Low+Size]. or is undef.
4279 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4280 unsigned Pos, unsigned Size, int Low) {
4281 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4282 if (!isUndefOrEqual(Mask[i], Low))
4287 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4288 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4289 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4290 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4291 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4294 // The index should be aligned on a vecWidth-bit boundary.
4296 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4298 MVT VT = N->getSimpleValueType(0);
4299 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4300 bool Result = (Index * ElSize) % vecWidth == 0;
4305 /// Return true if the specified INSERT_SUBVECTOR
4306 /// operand specifies a subvector insert that is suitable for input to
4307 /// insertion of 128 or 256-bit subvectors
4308 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4309 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4310 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4312 // The index should be aligned on a vecWidth-bit boundary.
4314 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4316 MVT VT = N->getSimpleValueType(0);
4317 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4318 bool Result = (Index * ElSize) % vecWidth == 0;
4323 bool X86::isVINSERT128Index(SDNode *N) {
4324 return isVINSERTIndex(N, 128);
4327 bool X86::isVINSERT256Index(SDNode *N) {
4328 return isVINSERTIndex(N, 256);
4331 bool X86::isVEXTRACT128Index(SDNode *N) {
4332 return isVEXTRACTIndex(N, 128);
4335 bool X86::isVEXTRACT256Index(SDNode *N) {
4336 return isVEXTRACTIndex(N, 256);
4339 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4340 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4341 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4342 "Illegal extract subvector for VEXTRACT");
4345 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4347 MVT VecVT = N->getOperand(0).getSimpleValueType();
4348 MVT ElVT = VecVT.getVectorElementType();
4350 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4351 return Index / NumElemsPerChunk;
4354 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4355 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4356 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4357 "Illegal insert subvector for VINSERT");
4360 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4362 MVT VecVT = N->getSimpleValueType(0);
4363 MVT ElVT = VecVT.getVectorElementType();
4365 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4366 return Index / NumElemsPerChunk;
4369 /// Return the appropriate immediate to extract the specified
4370 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4371 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4372 return getExtractVEXTRACTImmediate(N, 128);
4375 /// Return the appropriate immediate to extract the specified
4376 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4377 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4378 return getExtractVEXTRACTImmediate(N, 256);
4381 /// Return the appropriate immediate to insert at the specified
4382 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4383 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4384 return getInsertVINSERTImmediate(N, 128);
4387 /// Return the appropriate immediate to insert at the specified
4388 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4389 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4390 return getInsertVINSERTImmediate(N, 256);
4393 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4394 bool X86::isZeroNode(SDValue Elt) {
4395 return isNullConstant(Elt) || isNullFPConstant(Elt);
4398 // Build a vector of constants
4399 // Use an UNDEF node if MaskElt == -1.
4400 // Spilt 64-bit constants in the 32-bit mode.
4401 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4403 SDLoc dl, bool IsMask = false) {
4405 SmallVector<SDValue, 32> Ops;
4408 MVT ConstVecVT = VT;
4409 unsigned NumElts = VT.getVectorNumElements();
4410 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4411 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4412 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4416 MVT EltVT = ConstVecVT.getVectorElementType();
4417 for (unsigned i = 0; i < NumElts; ++i) {
4418 bool IsUndef = Values[i] < 0 && IsMask;
4419 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4420 DAG.getConstant(Values[i], dl, EltVT);
4421 Ops.push_back(OpNode);
4423 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4424 DAG.getConstant(0, dl, EltVT));
4426 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4428 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4432 /// Returns a vector of specified type with all zero elements.
4433 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4434 SelectionDAG &DAG, SDLoc dl) {
4435 assert(VT.isVector() && "Expected a vector type");
4437 // Always build SSE zero vectors as <4 x i32> bitcasted
4438 // to their dest type. This ensures they get CSE'd.
4440 if (VT.is128BitVector()) { // SSE
4441 if (Subtarget->hasSSE2()) { // SSE2
4442 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4443 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4445 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4446 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4448 } else if (VT.is256BitVector()) { // AVX
4449 if (Subtarget->hasInt256()) { // AVX2
4450 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4451 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4454 // 256-bit logic and arithmetic instructions in AVX are all
4455 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4456 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4457 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4458 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4460 } else if (VT.is512BitVector()) { // AVX-512
4461 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4462 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4463 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4464 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4465 } else if (VT.getVectorElementType() == MVT::i1) {
4467 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4468 && "Unexpected vector type");
4469 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4470 && "Unexpected vector type");
4471 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4472 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4473 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4475 llvm_unreachable("Unexpected vector type");
4477 return DAG.getBitcast(VT, Vec);
4480 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4481 SelectionDAG &DAG, SDLoc dl,
4482 unsigned vectorWidth) {
4483 assert((vectorWidth == 128 || vectorWidth == 256) &&
4484 "Unsupported vector width");
4485 EVT VT = Vec.getValueType();
4486 EVT ElVT = VT.getVectorElementType();
4487 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4488 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4489 VT.getVectorNumElements()/Factor);
4491 // Extract from UNDEF is UNDEF.
4492 if (Vec.getOpcode() == ISD::UNDEF)
4493 return DAG.getUNDEF(ResultVT);
4495 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4496 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4497 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4499 // This is the index of the first element of the vectorWidth-bit chunk
4500 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4501 IdxVal &= ~(ElemsPerChunk - 1);
4503 // If the input is a buildvector just emit a smaller one.
4504 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4505 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4506 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4508 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4509 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4512 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4513 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4514 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4515 /// instructions or a simple subregister reference. Idx is an index in the
4516 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4517 /// lowering EXTRACT_VECTOR_ELT operations easier.
4518 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4519 SelectionDAG &DAG, SDLoc dl) {
4520 assert((Vec.getValueType().is256BitVector() ||
4521 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4522 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4525 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4526 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4527 SelectionDAG &DAG, SDLoc dl) {
4528 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4529 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4532 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4533 unsigned IdxVal, SelectionDAG &DAG,
4534 SDLoc dl, unsigned vectorWidth) {
4535 assert((vectorWidth == 128 || vectorWidth == 256) &&
4536 "Unsupported vector width");
4537 // Inserting UNDEF is Result
4538 if (Vec.getOpcode() == ISD::UNDEF)
4540 EVT VT = Vec.getValueType();
4541 EVT ElVT = VT.getVectorElementType();
4542 EVT ResultVT = Result.getValueType();
4544 // Insert the relevant vectorWidth bits.
4545 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4546 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4548 // This is the index of the first element of the vectorWidth-bit chunk
4549 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4550 IdxVal &= ~(ElemsPerChunk - 1);
4552 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4553 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4556 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4557 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4558 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4559 /// simple superregister reference. Idx is an index in the 128 bits
4560 /// we want. It need not be aligned to a 128-bit boundary. That makes
4561 /// lowering INSERT_VECTOR_ELT operations easier.
4562 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4563 SelectionDAG &DAG, SDLoc dl) {
4564 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4566 // For insertion into the zero index (low half) of a 256-bit vector, it is
4567 // more efficient to generate a blend with immediate instead of an insert*128.
4568 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4569 // extend the subvector to the size of the result vector. Make sure that
4570 // we are not recursing on that node by checking for undef here.
4571 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4572 Result.getOpcode() != ISD::UNDEF) {
4573 EVT ResultVT = Result.getValueType();
4574 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4575 SDValue Undef = DAG.getUNDEF(ResultVT);
4576 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4579 // The blend instruction, and therefore its mask, depend on the data type.
4580 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4581 if (ScalarType.isFloatingPoint()) {
4582 // Choose either vblendps (float) or vblendpd (double).
4583 unsigned ScalarSize = ScalarType.getSizeInBits();
4584 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4585 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4586 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4587 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4590 const X86Subtarget &Subtarget =
4591 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4593 // AVX2 is needed for 256-bit integer blend support.
4594 // Integers must be cast to 32-bit because there is only vpblendd;
4595 // vpblendw can't be used for this because it has a handicapped mask.
4597 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4598 // is still more efficient than using the wrong domain vinsertf128 that
4599 // will be created by InsertSubVector().
4600 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4602 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4603 Result = DAG.getBitcast(CastVT, Result);
4604 Vec256 = DAG.getBitcast(CastVT, Vec256);
4605 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4606 return DAG.getBitcast(ResultVT, Vec256);
4609 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4612 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4613 SelectionDAG &DAG, SDLoc dl) {
4614 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4615 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4618 /// Insert i1-subvector to i1-vector.
4619 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4622 SDValue Vec = Op.getOperand(0);
4623 SDValue SubVec = Op.getOperand(1);
4624 SDValue Idx = Op.getOperand(2);
4626 if (!isa<ConstantSDNode>(Idx))
4629 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4630 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4633 MVT OpVT = Op.getSimpleValueType();
4634 MVT SubVecVT = SubVec.getSimpleValueType();
4635 unsigned NumElems = OpVT.getVectorNumElements();
4636 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4638 assert(IdxVal + SubVecNumElems <= NumElems &&
4639 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4640 "Unexpected index value in INSERT_SUBVECTOR");
4642 // There are 3 possible cases:
4643 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4644 // 2. Subvector should be inserted in the upper part
4645 // (IdxVal + SubVecNumElems == NumElems)
4646 // 3. Subvector should be inserted in the middle (for example v2i1
4647 // to v16i1, index 2)
4649 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4650 SDValue Undef = DAG.getUNDEF(OpVT);
4651 SDValue WideSubVec =
4652 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4654 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4655 DAG.getConstant(IdxVal, dl, MVT::i8));
4657 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4658 unsigned ShiftLeft = NumElems - SubVecNumElems;
4659 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4660 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4661 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4662 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4663 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4667 // Zero lower bits of the Vec
4668 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4669 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4670 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4671 // Merge them together
4672 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4675 // Simple case when we put subvector in the upper part
4676 if (IdxVal + SubVecNumElems == NumElems) {
4677 // Zero upper bits of the Vec
4678 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4679 DAG.getConstant(IdxVal, dl, MVT::i8));
4680 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4681 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4682 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4683 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4685 // Subvector should be inserted in the middle - use shuffle
4686 SmallVector<int, 64> Mask;
4687 for (unsigned i = 0; i < NumElems; ++i)
4688 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4690 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4693 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4694 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4695 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4696 /// large BUILD_VECTORS.
4697 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4698 unsigned NumElems, SelectionDAG &DAG,
4700 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4701 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4704 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4705 unsigned NumElems, SelectionDAG &DAG,
4707 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4708 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4711 /// Returns a vector of specified type with all bits set.
4712 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4713 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4714 /// Then bitcast to their original type, ensuring they get CSE'd.
4715 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4716 SelectionDAG &DAG, SDLoc dl) {
4717 assert(VT.isVector() && "Expected a vector type");
4719 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4721 if (VT.is512BitVector()) {
4722 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4723 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4724 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4725 } else if (VT.is256BitVector()) {
4726 if (Subtarget->hasInt256()) { // AVX2
4727 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4728 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4730 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4731 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4733 } else if (VT.is128BitVector()) {
4734 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4736 llvm_unreachable("Unexpected vector type");
4738 return DAG.getBitcast(VT, Vec);
4741 /// Returns a vector_shuffle node for an unpackl operation.
4742 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4744 unsigned NumElems = VT.getVectorNumElements();
4745 SmallVector<int, 8> Mask;
4746 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4748 Mask.push_back(i + NumElems);
4750 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4753 /// Returns a vector_shuffle node for an unpackh operation.
4754 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4756 unsigned NumElems = VT.getVectorNumElements();
4757 SmallVector<int, 8> Mask;
4758 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4759 Mask.push_back(i + Half);
4760 Mask.push_back(i + NumElems + Half);
4762 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4765 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4766 /// This produces a shuffle where the low element of V2 is swizzled into the
4767 /// zero/undef vector, landing at element Idx.
4768 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4769 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4771 const X86Subtarget *Subtarget,
4772 SelectionDAG &DAG) {
4773 MVT VT = V2.getSimpleValueType();
4775 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4776 unsigned NumElems = VT.getVectorNumElements();
4777 SmallVector<int, 16> MaskVec;
4778 for (unsigned i = 0; i != NumElems; ++i)
4779 // If this is the insertion idx, put the low elt of V2 here.
4780 MaskVec.push_back(i == Idx ? NumElems : i);
4781 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4784 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4785 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4786 /// uses one source. Note that this will set IsUnary for shuffles which use a
4787 /// single input multiple times, and in those cases it will
4788 /// adjust the mask to only have indices within that single input.
4789 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4790 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4791 unsigned NumElems = VT.getVectorNumElements();
4795 bool IsFakeUnary = false;
4796 switch(N->getOpcode()) {
4797 case X86ISD::BLENDI:
4798 ImmN = N->getOperand(N->getNumOperands()-1);
4799 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4802 ImmN = N->getOperand(N->getNumOperands()-1);
4803 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4804 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4806 case X86ISD::INSERTPS:
4807 ImmN = N->getOperand(N->getNumOperands()-1);
4808 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4809 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4811 case X86ISD::UNPCKH:
4812 DecodeUNPCKHMask(VT, Mask);
4813 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4815 case X86ISD::UNPCKL:
4816 DecodeUNPCKLMask(VT, Mask);
4817 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4819 case X86ISD::MOVHLPS:
4820 DecodeMOVHLPSMask(NumElems, Mask);
4821 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4823 case X86ISD::MOVLHPS:
4824 DecodeMOVLHPSMask(NumElems, Mask);
4825 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4827 case X86ISD::PALIGNR:
4828 ImmN = N->getOperand(N->getNumOperands()-1);
4829 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4831 case X86ISD::PSHUFD:
4832 case X86ISD::VPERMILPI:
4833 ImmN = N->getOperand(N->getNumOperands()-1);
4834 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4837 case X86ISD::PSHUFHW:
4838 ImmN = N->getOperand(N->getNumOperands()-1);
4839 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4842 case X86ISD::PSHUFLW:
4843 ImmN = N->getOperand(N->getNumOperands()-1);
4844 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4847 case X86ISD::PSHUFB: {
4849 SDValue MaskNode = N->getOperand(1);
4850 while (MaskNode->getOpcode() == ISD::BITCAST)
4851 MaskNode = MaskNode->getOperand(0);
4853 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4854 // If we have a build-vector, then things are easy.
4855 MVT VT = MaskNode.getSimpleValueType();
4856 assert(VT.isVector() &&
4857 "Can't produce a non-vector with a build_vector!");
4858 if (!VT.isInteger())
4861 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4863 SmallVector<uint64_t, 32> RawMask;
4864 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4865 SDValue Op = MaskNode->getOperand(i);
4866 if (Op->getOpcode() == ISD::UNDEF) {
4867 RawMask.push_back((uint64_t)SM_SentinelUndef);
4870 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4873 APInt MaskElement = CN->getAPIntValue();
4875 // We now have to decode the element which could be any integer size and
4876 // extract each byte of it.
4877 for (int j = 0; j < NumBytesPerElement; ++j) {
4878 // Note that this is x86 and so always little endian: the low byte is
4879 // the first byte of the mask.
4880 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4881 MaskElement = MaskElement.lshr(8);
4884 DecodePSHUFBMask(RawMask, Mask);
4888 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4892 SDValue Ptr = MaskLoad->getBasePtr();
4893 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4894 Ptr->getOpcode() == X86ISD::WrapperRIP)
4895 Ptr = Ptr->getOperand(0);
4897 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4898 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4901 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4902 DecodePSHUFBMask(C, Mask);
4908 case X86ISD::VPERMI:
4909 ImmN = N->getOperand(N->getNumOperands()-1);
4910 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4915 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4917 case X86ISD::VPERM2X128:
4918 ImmN = N->getOperand(N->getNumOperands()-1);
4919 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4920 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4922 case X86ISD::MOVSLDUP:
4923 DecodeMOVSLDUPMask(VT, Mask);
4926 case X86ISD::MOVSHDUP:
4927 DecodeMOVSHDUPMask(VT, Mask);
4930 case X86ISD::MOVDDUP:
4931 DecodeMOVDDUPMask(VT, Mask);
4934 case X86ISD::MOVLHPD:
4935 case X86ISD::MOVLPD:
4936 case X86ISD::MOVLPS:
4937 // Not yet implemented
4939 case X86ISD::VPERMV: {
4941 SDValue MaskNode = N->getOperand(0);
4942 while (MaskNode->getOpcode() == ISD::BITCAST)
4943 MaskNode = MaskNode->getOperand(0);
4945 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4946 SmallVector<uint64_t, 32> RawMask;
4947 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4948 // If we have a build-vector, then things are easy.
4949 assert(MaskNode.getSimpleValueType().isInteger() &&
4950 MaskNode.getSimpleValueType().getVectorNumElements() ==
4951 VT.getVectorNumElements());
4953 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4954 SDValue Op = MaskNode->getOperand(i);
4955 if (Op->getOpcode() == ISD::UNDEF)
4956 RawMask.push_back((uint64_t)SM_SentinelUndef);
4957 else if (isa<ConstantSDNode>(Op)) {
4958 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4959 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4963 DecodeVPERMVMask(RawMask, Mask);
4966 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4967 unsigned NumEltsInMask = MaskNode->getNumOperands();
4968 MaskNode = MaskNode->getOperand(0);
4969 if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4970 APInt MaskEltValue = CN->getAPIntValue();
4971 for (unsigned i = 0; i < NumEltsInMask; ++i)
4972 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4973 DecodeVPERMVMask(RawMask, Mask);
4976 // It may be a scalar load
4979 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4983 SDValue Ptr = MaskLoad->getBasePtr();
4984 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4985 Ptr->getOpcode() == X86ISD::WrapperRIP)
4986 Ptr = Ptr->getOperand(0);
4988 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4989 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4992 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4993 DecodeVPERMVMask(C, VT, Mask);
4998 case X86ISD::VPERMV3: {
5000 SDValue MaskNode = N->getOperand(1);
5001 while (MaskNode->getOpcode() == ISD::BITCAST)
5002 MaskNode = MaskNode->getOperand(1);
5004 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5005 // If we have a build-vector, then things are easy.
5006 assert(MaskNode.getSimpleValueType().isInteger() &&
5007 MaskNode.getSimpleValueType().getVectorNumElements() ==
5008 VT.getVectorNumElements());
5010 SmallVector<uint64_t, 32> RawMask;
5011 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
5013 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
5014 SDValue Op = MaskNode->getOperand(i);
5015 if (Op->getOpcode() == ISD::UNDEF)
5016 RawMask.push_back((uint64_t)SM_SentinelUndef);
5018 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5021 APInt MaskElement = CN->getAPIntValue();
5022 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
5025 DecodeVPERMV3Mask(RawMask, Mask);
5029 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5033 SDValue Ptr = MaskLoad->getBasePtr();
5034 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5035 Ptr->getOpcode() == X86ISD::WrapperRIP)
5036 Ptr = Ptr->getOperand(0);
5038 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5039 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5042 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5043 DecodeVPERMV3Mask(C, VT, Mask);
5048 default: llvm_unreachable("unknown target shuffle node");
5051 // Empty mask indicates the decode failed.
5055 // Check if we're getting a shuffle mask with zero'd elements.
5056 if (!AllowSentinelZero)
5057 if (std::any_of(Mask.begin(), Mask.end(),
5058 [](int M){ return M == SM_SentinelZero; }))
5061 // If we have a fake unary shuffle, the shuffle mask is spread across two
5062 // inputs that are actually the same node. Re-map the mask to always point
5063 // into the first input.
5066 if (M >= (int)Mask.size())
5072 /// Returns the scalar element that will make up the ith
5073 /// element of the result of the vector shuffle.
5074 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5077 return SDValue(); // Limit search depth.
5079 SDValue V = SDValue(N, 0);
5080 EVT VT = V.getValueType();
5081 unsigned Opcode = V.getOpcode();
5083 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5084 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5085 int Elt = SV->getMaskElt(Index);
5088 return DAG.getUNDEF(VT.getVectorElementType());
5090 unsigned NumElems = VT.getVectorNumElements();
5091 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5092 : SV->getOperand(1);
5093 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5096 // Recurse into target specific vector shuffles to find scalars.
5097 if (isTargetShuffle(Opcode)) {
5098 MVT ShufVT = V.getSimpleValueType();
5099 int NumElems = (int)ShufVT.getVectorNumElements();
5100 SmallVector<int, 16> ShuffleMask;
5103 if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5106 int Elt = ShuffleMask[Index];
5107 if (Elt == SM_SentinelUndef)
5108 return DAG.getUNDEF(ShufVT.getVectorElementType());
5110 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5111 SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5112 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5116 // Actual nodes that may contain scalar elements
5117 if (Opcode == ISD::BITCAST) {
5118 V = V.getOperand(0);
5119 EVT SrcVT = V.getValueType();
5120 unsigned NumElems = VT.getVectorNumElements();
5122 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5126 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5127 return (Index == 0) ? V.getOperand(0)
5128 : DAG.getUNDEF(VT.getVectorElementType());
5130 if (V.getOpcode() == ISD::BUILD_VECTOR)
5131 return V.getOperand(Index);
5136 /// Custom lower build_vector of v16i8.
5137 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5138 unsigned NumNonZero, unsigned NumZero,
5140 const X86Subtarget* Subtarget,
5141 const TargetLowering &TLI) {
5149 // SSE4.1 - use PINSRB to insert each byte directly.
5150 if (Subtarget->hasSSE41()) {
5151 for (unsigned i = 0; i < 16; ++i) {
5152 bool isNonZero = (NonZeros & (1 << i)) != 0;
5156 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5158 V = DAG.getUNDEF(MVT::v16i8);
5161 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5162 MVT::v16i8, V, Op.getOperand(i),
5163 DAG.getIntPtrConstant(i, dl));
5170 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5171 for (unsigned i = 0; i < 16; ++i) {
5172 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5173 if (ThisIsNonZero && First) {
5175 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5177 V = DAG.getUNDEF(MVT::v8i16);
5182 SDValue ThisElt, LastElt;
5183 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5184 if (LastIsNonZero) {
5185 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5186 MVT::i16, Op.getOperand(i-1));
5188 if (ThisIsNonZero) {
5189 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5190 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5191 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5193 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5197 if (ThisElt.getNode())
5198 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5199 DAG.getIntPtrConstant(i/2, dl));
5203 return DAG.getBitcast(MVT::v16i8, V);
5206 /// Custom lower build_vector of v8i16.
5207 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5208 unsigned NumNonZero, unsigned NumZero,
5210 const X86Subtarget* Subtarget,
5211 const TargetLowering &TLI) {
5218 for (unsigned i = 0; i < 8; ++i) {
5219 bool isNonZero = (NonZeros & (1 << i)) != 0;
5223 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5225 V = DAG.getUNDEF(MVT::v8i16);
5228 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5229 MVT::v8i16, V, Op.getOperand(i),
5230 DAG.getIntPtrConstant(i, dl));
5237 /// Custom lower build_vector of v4i32 or v4f32.
5238 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5239 const X86Subtarget *Subtarget,
5240 const TargetLowering &TLI) {
5241 // Find all zeroable elements.
5242 std::bitset<4> Zeroable;
5243 for (int i=0; i < 4; ++i) {
5244 SDValue Elt = Op->getOperand(i);
5245 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5247 assert(Zeroable.size() - Zeroable.count() > 1 &&
5248 "We expect at least two non-zero elements!");
5250 // We only know how to deal with build_vector nodes where elements are either
5251 // zeroable or extract_vector_elt with constant index.
5252 SDValue FirstNonZero;
5253 unsigned FirstNonZeroIdx;
5254 for (unsigned i=0; i < 4; ++i) {
5257 SDValue Elt = Op->getOperand(i);
5258 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5259 !isa<ConstantSDNode>(Elt.getOperand(1)))
5261 // Make sure that this node is extracting from a 128-bit vector.
5262 MVT VT = Elt.getOperand(0).getSimpleValueType();
5263 if (!VT.is128BitVector())
5265 if (!FirstNonZero.getNode()) {
5267 FirstNonZeroIdx = i;
5271 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5272 SDValue V1 = FirstNonZero.getOperand(0);
5273 MVT VT = V1.getSimpleValueType();
5275 // See if this build_vector can be lowered as a blend with zero.
5277 unsigned EltMaskIdx, EltIdx;
5279 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5280 if (Zeroable[EltIdx]) {
5281 // The zero vector will be on the right hand side.
5282 Mask[EltIdx] = EltIdx+4;
5286 Elt = Op->getOperand(EltIdx);
5287 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5288 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5289 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5291 Mask[EltIdx] = EltIdx;
5295 // Let the shuffle legalizer deal with blend operations.
5296 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5297 if (V1.getSimpleValueType() != VT)
5298 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5299 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5302 // See if we can lower this build_vector to a INSERTPS.
5303 if (!Subtarget->hasSSE41())
5306 SDValue V2 = Elt.getOperand(0);
5307 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5310 bool CanFold = true;
5311 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5315 SDValue Current = Op->getOperand(i);
5316 SDValue SrcVector = Current->getOperand(0);
5319 CanFold = SrcVector == V1 &&
5320 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5326 assert(V1.getNode() && "Expected at least two non-zero elements!");
5327 if (V1.getSimpleValueType() != MVT::v4f32)
5328 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5329 if (V2.getSimpleValueType() != MVT::v4f32)
5330 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5332 // Ok, we can emit an INSERTPS instruction.
5333 unsigned ZMask = Zeroable.to_ulong();
5335 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5336 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5338 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5339 DAG.getIntPtrConstant(InsertPSMask, DL));
5340 return DAG.getBitcast(VT, Result);
5343 /// Return a vector logical shift node.
5344 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5345 unsigned NumBits, SelectionDAG &DAG,
5346 const TargetLowering &TLI, SDLoc dl) {
5347 assert(VT.is128BitVector() && "Unknown type for VShift");
5348 MVT ShVT = MVT::v2i64;
5349 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5350 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5351 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5352 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5353 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5354 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5358 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5360 // Check if the scalar load can be widened into a vector load. And if
5361 // the address is "base + cst" see if the cst can be "absorbed" into
5362 // the shuffle mask.
5363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5364 SDValue Ptr = LD->getBasePtr();
5365 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5367 EVT PVT = LD->getValueType(0);
5368 if (PVT != MVT::i32 && PVT != MVT::f32)
5373 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5374 FI = FINode->getIndex();
5376 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5377 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5378 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5379 Offset = Ptr.getConstantOperandVal(1);
5380 Ptr = Ptr.getOperand(0);
5385 // FIXME: 256-bit vector instructions don't require a strict alignment,
5386 // improve this code to support it better.
5387 unsigned RequiredAlign = VT.getSizeInBits()/8;
5388 SDValue Chain = LD->getChain();
5389 // Make sure the stack object alignment is at least 16 or 32.
5390 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5391 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5392 if (MFI->isFixedObjectIndex(FI)) {
5393 // Can't change the alignment. FIXME: It's possible to compute
5394 // the exact stack offset and reference FI + adjust offset instead.
5395 // If someone *really* cares about this. That's the way to implement it.
5398 MFI->setObjectAlignment(FI, RequiredAlign);
5402 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5403 // Ptr + (Offset & ~15).
5406 if ((Offset % RequiredAlign) & 3)
5408 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5411 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5412 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5415 int EltNo = (Offset - StartOffset) >> 2;
5416 unsigned NumElems = VT.getVectorNumElements();
5418 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5419 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5420 LD->getPointerInfo().getWithOffset(StartOffset),
5421 false, false, false, 0);
5423 SmallVector<int, 8> Mask(NumElems, EltNo);
5425 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5431 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5432 /// elements can be replaced by a single large load which has the same value as
5433 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5435 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5437 /// FIXME: we'd also like to handle the case where the last elements are zero
5438 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5439 /// There's even a handy isZeroNode for that purpose.
5440 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5441 SDLoc &DL, SelectionDAG &DAG,
5442 bool isAfterLegalize) {
5443 unsigned NumElems = Elts.size();
5445 LoadSDNode *LDBase = nullptr;
5446 unsigned LastLoadedElt = -1U;
5448 // For each element in the initializer, see if we've found a load or an undef.
5449 // If we don't find an initial load element, or later load elements are
5450 // non-consecutive, bail out.
5451 for (unsigned i = 0; i < NumElems; ++i) {
5452 SDValue Elt = Elts[i];
5453 // Look through a bitcast.
5454 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5455 Elt = Elt.getOperand(0);
5456 if (!Elt.getNode() ||
5457 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5460 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5462 LDBase = cast<LoadSDNode>(Elt.getNode());
5466 if (Elt.getOpcode() == ISD::UNDEF)
5469 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5470 EVT LdVT = Elt.getValueType();
5471 // Each loaded element must be the correct fractional portion of the
5472 // requested vector load.
5473 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5475 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5480 // If we have found an entire vector of loads and undefs, then return a large
5481 // load of the entire vector width starting at the base pointer. If we found
5482 // consecutive loads for the low half, generate a vzext_load node.
5483 if (LastLoadedElt == NumElems - 1) {
5484 assert(LDBase && "Did not find base load for merging consecutive loads");
5485 EVT EltVT = LDBase->getValueType(0);
5486 // Ensure that the input vector size for the merged loads matches the
5487 // cumulative size of the input elements.
5488 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5491 if (isAfterLegalize &&
5492 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5495 SDValue NewLd = SDValue();
5497 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5498 LDBase->getPointerInfo(), LDBase->isVolatile(),
5499 LDBase->isNonTemporal(), LDBase->isInvariant(),
5500 LDBase->getAlignment());
5502 if (LDBase->hasAnyUseOfValue(1)) {
5503 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5505 SDValue(NewLd.getNode(), 1));
5506 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5507 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5508 SDValue(NewLd.getNode(), 1));
5514 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5515 //of a v4i32 / v4f32. It's probably worth generalizing.
5516 EVT EltVT = VT.getVectorElementType();
5517 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5518 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5519 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5520 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5522 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5523 LDBase->getPointerInfo(),
5524 LDBase->getAlignment(),
5525 false/*isVolatile*/, true/*ReadMem*/,
5528 // Make sure the newly-created LOAD is in the same position as LDBase in
5529 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5530 // update uses of LDBase's output chain to use the TokenFactor.
5531 if (LDBase->hasAnyUseOfValue(1)) {
5532 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5533 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5534 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5535 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5536 SDValue(ResNode.getNode(), 1));
5539 return DAG.getBitcast(VT, ResNode);
5544 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5545 /// to generate a splat value for the following cases:
5546 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5547 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5548 /// a scalar load, or a constant.
5549 /// The VBROADCAST node is returned when a pattern is found,
5550 /// or SDValue() otherwise.
5551 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5552 SelectionDAG &DAG) {
5553 // VBROADCAST requires AVX.
5554 // TODO: Splats could be generated for non-AVX CPUs using SSE
5555 // instructions, but there's less potential gain for only 128-bit vectors.
5556 if (!Subtarget->hasAVX())
5559 MVT VT = Op.getSimpleValueType();
5562 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5563 "Unsupported vector type for broadcast.");
5568 switch (Op.getOpcode()) {
5570 // Unknown pattern found.
5573 case ISD::BUILD_VECTOR: {
5574 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5575 BitVector UndefElements;
5576 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5578 // We need a splat of a single value to use broadcast, and it doesn't
5579 // make any sense if the value is only in one element of the vector.
5580 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5584 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5585 Ld.getOpcode() == ISD::ConstantFP);
5587 // Make sure that all of the users of a non-constant load are from the
5588 // BUILD_VECTOR node.
5589 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5594 case ISD::VECTOR_SHUFFLE: {
5595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5597 // Shuffles must have a splat mask where the first element is
5599 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5602 SDValue Sc = Op.getOperand(0);
5603 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5604 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5606 if (!Subtarget->hasInt256())
5609 // Use the register form of the broadcast instruction available on AVX2.
5610 if (VT.getSizeInBits() >= 256)
5611 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5612 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5615 Ld = Sc.getOperand(0);
5616 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5617 Ld.getOpcode() == ISD::ConstantFP);
5619 // The scalar_to_vector node and the suspected
5620 // load node must have exactly one user.
5621 // Constants may have multiple users.
5623 // AVX-512 has register version of the broadcast
5624 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5625 Ld.getValueType().getSizeInBits() >= 32;
5626 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5633 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5634 bool IsGE256 = (VT.getSizeInBits() >= 256);
5636 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5637 // instruction to save 8 or more bytes of constant pool data.
5638 // TODO: If multiple splats are generated to load the same constant,
5639 // it may be detrimental to overall size. There needs to be a way to detect
5640 // that condition to know if this is truly a size win.
5641 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5643 // Handle broadcasting a single constant scalar from the constant pool
5645 // On Sandybridge (no AVX2), it is still better to load a constant vector
5646 // from the constant pool and not to broadcast it from a scalar.
5647 // But override that restriction when optimizing for size.
5648 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5649 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5650 EVT CVT = Ld.getValueType();
5651 assert(!CVT.isVector() && "Must not broadcast a vector type");
5653 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5654 // For size optimization, also splat v2f64 and v2i64, and for size opt
5655 // with AVX2, also splat i8 and i16.
5656 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5657 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5658 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5659 const Constant *C = nullptr;
5660 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5661 C = CI->getConstantIntValue();
5662 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5663 C = CF->getConstantFPValue();
5665 assert(C && "Invalid constant type");
5667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5669 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5670 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5672 CVT, dl, DAG.getEntryNode(), CP,
5673 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5674 false, false, Alignment);
5676 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5680 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5682 // Handle AVX2 in-register broadcasts.
5683 if (!IsLoad && Subtarget->hasInt256() &&
5684 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5685 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5687 // The scalar source must be a normal load.
5691 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5692 (Subtarget->hasVLX() && ScalarSize == 64))
5693 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5695 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5696 // double since there is no vbroadcastsd xmm
5697 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5698 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5699 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5702 // Unsupported broadcast.
5706 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5707 /// underlying vector and index.
5709 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5711 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5713 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5714 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5717 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5719 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5721 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5722 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5725 // In this case the vector is the extract_subvector expression and the index
5726 // is 2, as specified by the shuffle.
5727 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5728 SDValue ShuffleVec = SVOp->getOperand(0);
5729 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5730 assert(ShuffleVecVT.getVectorElementType() ==
5731 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5733 int ShuffleIdx = SVOp->getMaskElt(Idx);
5734 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5735 ExtractedFromVec = ShuffleVec;
5741 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5742 MVT VT = Op.getSimpleValueType();
5744 // Skip if insert_vec_elt is not supported.
5745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5746 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5750 unsigned NumElems = Op.getNumOperands();
5754 SmallVector<unsigned, 4> InsertIndices;
5755 SmallVector<int, 8> Mask(NumElems, -1);
5757 for (unsigned i = 0; i != NumElems; ++i) {
5758 unsigned Opc = Op.getOperand(i).getOpcode();
5760 if (Opc == ISD::UNDEF)
5763 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5764 // Quit if more than 1 elements need inserting.
5765 if (InsertIndices.size() > 1)
5768 InsertIndices.push_back(i);
5772 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5773 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5774 // Quit if non-constant index.
5775 if (!isa<ConstantSDNode>(ExtIdx))
5777 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5779 // Quit if extracted from vector of different type.
5780 if (ExtractedFromVec.getValueType() != VT)
5783 if (!VecIn1.getNode())
5784 VecIn1 = ExtractedFromVec;
5785 else if (VecIn1 != ExtractedFromVec) {
5786 if (!VecIn2.getNode())
5787 VecIn2 = ExtractedFromVec;
5788 else if (VecIn2 != ExtractedFromVec)
5789 // Quit if more than 2 vectors to shuffle
5793 if (ExtractedFromVec == VecIn1)
5795 else if (ExtractedFromVec == VecIn2)
5796 Mask[i] = Idx + NumElems;
5799 if (!VecIn1.getNode())
5802 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5803 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5804 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5805 unsigned Idx = InsertIndices[i];
5806 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5807 DAG.getIntPtrConstant(Idx, DL));
5813 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5814 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5815 Op.getScalarValueSizeInBits() == 1 &&
5816 "Can not convert non-constant vector");
5817 uint64_t Immediate = 0;
5818 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5819 SDValue In = Op.getOperand(idx);
5820 if (In.getOpcode() != ISD::UNDEF)
5821 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5825 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5826 return DAG.getConstant(Immediate, dl, VT);
5828 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5830 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5832 MVT VT = Op.getSimpleValueType();
5833 assert((VT.getVectorElementType() == MVT::i1) &&
5834 "Unexpected type in LowerBUILD_VECTORvXi1!");
5837 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5838 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5839 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5840 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5843 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5844 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5845 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5846 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5849 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5850 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5851 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5852 return DAG.getBitcast(VT, Imm);
5853 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5854 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5855 DAG.getIntPtrConstant(0, dl));
5858 // Vector has one or more non-const elements
5859 uint64_t Immediate = 0;
5860 SmallVector<unsigned, 16> NonConstIdx;
5861 bool IsSplat = true;
5862 bool HasConstElts = false;
5864 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5865 SDValue In = Op.getOperand(idx);
5866 if (In.getOpcode() == ISD::UNDEF)
5868 if (!isa<ConstantSDNode>(In))
5869 NonConstIdx.push_back(idx);
5871 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5872 HasConstElts = true;
5876 else if (In != Op.getOperand(SplatIdx))
5880 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5882 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5883 DAG.getConstant(1, dl, VT),
5884 DAG.getConstant(0, dl, VT));
5886 // insert elements one by one
5890 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5891 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5893 else if (HasConstElts)
5894 Imm = DAG.getConstant(0, dl, VT);
5896 Imm = DAG.getUNDEF(VT);
5897 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5898 DstVec = DAG.getBitcast(VT, Imm);
5900 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5901 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5902 DAG.getIntPtrConstant(0, dl));
5905 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5906 unsigned InsertIdx = NonConstIdx[i];
5907 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5908 Op.getOperand(InsertIdx),
5909 DAG.getIntPtrConstant(InsertIdx, dl));
5914 /// \brief Return true if \p N implements a horizontal binop and return the
5915 /// operands for the horizontal binop into V0 and V1.
5917 /// This is a helper function of LowerToHorizontalOp().
5918 /// This function checks that the build_vector \p N in input implements a
5919 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5920 /// operation to match.
5921 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5922 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5923 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5926 /// This function only analyzes elements of \p N whose indices are
5927 /// in range [BaseIdx, LastIdx).
5928 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5930 unsigned BaseIdx, unsigned LastIdx,
5931 SDValue &V0, SDValue &V1) {
5932 EVT VT = N->getValueType(0);
5934 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5935 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5936 "Invalid Vector in input!");
5938 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5939 bool CanFold = true;
5940 unsigned ExpectedVExtractIdx = BaseIdx;
5941 unsigned NumElts = LastIdx - BaseIdx;
5942 V0 = DAG.getUNDEF(VT);
5943 V1 = DAG.getUNDEF(VT);
5945 // Check if N implements a horizontal binop.
5946 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5947 SDValue Op = N->getOperand(i + BaseIdx);
5950 if (Op->getOpcode() == ISD::UNDEF) {
5951 // Update the expected vector extract index.
5952 if (i * 2 == NumElts)
5953 ExpectedVExtractIdx = BaseIdx;
5954 ExpectedVExtractIdx += 2;
5958 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5963 SDValue Op0 = Op.getOperand(0);
5964 SDValue Op1 = Op.getOperand(1);
5966 // Try to match the following pattern:
5967 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5968 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5969 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5970 Op0.getOperand(0) == Op1.getOperand(0) &&
5971 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5972 isa<ConstantSDNode>(Op1.getOperand(1)));
5976 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5977 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5979 if (i * 2 < NumElts) {
5980 if (V0.getOpcode() == ISD::UNDEF) {
5981 V0 = Op0.getOperand(0);
5982 if (V0.getValueType() != VT)
5986 if (V1.getOpcode() == ISD::UNDEF) {
5987 V1 = Op0.getOperand(0);
5988 if (V1.getValueType() != VT)
5991 if (i * 2 == NumElts)
5992 ExpectedVExtractIdx = BaseIdx;
5995 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5996 if (I0 == ExpectedVExtractIdx)
5997 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5998 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5999 // Try to match the following dag sequence:
6000 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6001 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6005 ExpectedVExtractIdx += 2;
6011 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6012 /// a concat_vector.
6014 /// This is a helper function of LowerToHorizontalOp().
6015 /// This function expects two 256-bit vectors called V0 and V1.
6016 /// At first, each vector is split into two separate 128-bit vectors.
6017 /// Then, the resulting 128-bit vectors are used to implement two
6018 /// horizontal binary operations.
6020 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6022 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6023 /// the two new horizontal binop.
6024 /// When Mode is set, the first horizontal binop dag node would take as input
6025 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6026 /// horizontal binop dag node would take as input the lower 128-bit of V1
6027 /// and the upper 128-bit of V1.
6029 /// HADD V0_LO, V0_HI
6030 /// HADD V1_LO, V1_HI
6032 /// Otherwise, the first horizontal binop dag node takes as input the lower
6033 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6034 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6036 /// HADD V0_LO, V1_LO
6037 /// HADD V0_HI, V1_HI
6039 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6040 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6041 /// the upper 128-bits of the result.
6042 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6043 SDLoc DL, SelectionDAG &DAG,
6044 unsigned X86Opcode, bool Mode,
6045 bool isUndefLO, bool isUndefHI) {
6046 EVT VT = V0.getValueType();
6047 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6048 "Invalid nodes in input!");
6050 unsigned NumElts = VT.getVectorNumElements();
6051 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6052 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6053 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6054 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6055 EVT NewVT = V0_LO.getValueType();
6057 SDValue LO = DAG.getUNDEF(NewVT);
6058 SDValue HI = DAG.getUNDEF(NewVT);
6061 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6062 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6063 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6064 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6065 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6067 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6068 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6069 V1_LO->getOpcode() != ISD::UNDEF))
6070 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6072 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6073 V1_HI->getOpcode() != ISD::UNDEF))
6074 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6077 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6080 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6082 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6083 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6084 MVT VT = BV->getSimpleValueType(0);
6085 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6086 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6090 unsigned NumElts = VT.getVectorNumElements();
6091 SDValue InVec0 = DAG.getUNDEF(VT);
6092 SDValue InVec1 = DAG.getUNDEF(VT);
6094 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6095 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6097 // Odd-numbered elements in the input build vector are obtained from
6098 // adding two integer/float elements.
6099 // Even-numbered elements in the input build vector are obtained from
6100 // subtracting two integer/float elements.
6101 unsigned ExpectedOpcode = ISD::FSUB;
6102 unsigned NextExpectedOpcode = ISD::FADD;
6103 bool AddFound = false;
6104 bool SubFound = false;
6106 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6107 SDValue Op = BV->getOperand(i);
6109 // Skip 'undef' values.
6110 unsigned Opcode = Op.getOpcode();
6111 if (Opcode == ISD::UNDEF) {
6112 std::swap(ExpectedOpcode, NextExpectedOpcode);
6116 // Early exit if we found an unexpected opcode.
6117 if (Opcode != ExpectedOpcode)
6120 SDValue Op0 = Op.getOperand(0);
6121 SDValue Op1 = Op.getOperand(1);
6123 // Try to match the following pattern:
6124 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6125 // Early exit if we cannot match that sequence.
6126 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6127 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6128 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6129 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6130 Op0.getOperand(1) != Op1.getOperand(1))
6133 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6137 // We found a valid add/sub node. Update the information accordingly.
6143 // Update InVec0 and InVec1.
6144 if (InVec0.getOpcode() == ISD::UNDEF) {
6145 InVec0 = Op0.getOperand(0);
6146 if (InVec0.getSimpleValueType() != VT)
6149 if (InVec1.getOpcode() == ISD::UNDEF) {
6150 InVec1 = Op1.getOperand(0);
6151 if (InVec1.getSimpleValueType() != VT)
6155 // Make sure that operands in input to each add/sub node always
6156 // come from a same pair of vectors.
6157 if (InVec0 != Op0.getOperand(0)) {
6158 if (ExpectedOpcode == ISD::FSUB)
6161 // FADD is commutable. Try to commute the operands
6162 // and then test again.
6163 std::swap(Op0, Op1);
6164 if (InVec0 != Op0.getOperand(0))
6168 if (InVec1 != Op1.getOperand(0))
6171 // Update the pair of expected opcodes.
6172 std::swap(ExpectedOpcode, NextExpectedOpcode);
6175 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6176 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6177 InVec1.getOpcode() != ISD::UNDEF)
6178 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6183 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6184 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6185 const X86Subtarget *Subtarget,
6186 SelectionDAG &DAG) {
6187 MVT VT = BV->getSimpleValueType(0);
6188 unsigned NumElts = VT.getVectorNumElements();
6189 unsigned NumUndefsLO = 0;
6190 unsigned NumUndefsHI = 0;
6191 unsigned Half = NumElts/2;
6193 // Count the number of UNDEF operands in the build_vector in input.
6194 for (unsigned i = 0, e = Half; i != e; ++i)
6195 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6198 for (unsigned i = Half, e = NumElts; i != e; ++i)
6199 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6202 // Early exit if this is either a build_vector of all UNDEFs or all the
6203 // operands but one are UNDEF.
6204 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6208 SDValue InVec0, InVec1;
6209 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6210 // Try to match an SSE3 float HADD/HSUB.
6211 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6212 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6214 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6215 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6216 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6217 // Try to match an SSSE3 integer HADD/HSUB.
6218 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6219 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6221 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6222 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6225 if (!Subtarget->hasAVX())
6228 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6229 // Try to match an AVX horizontal add/sub of packed single/double
6230 // precision floating point values from 256-bit vectors.
6231 SDValue InVec2, InVec3;
6232 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6233 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6234 ((InVec0.getOpcode() == ISD::UNDEF ||
6235 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6236 ((InVec1.getOpcode() == ISD::UNDEF ||
6237 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6238 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6240 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6241 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6242 ((InVec0.getOpcode() == ISD::UNDEF ||
6243 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6244 ((InVec1.getOpcode() == ISD::UNDEF ||
6245 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6246 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6247 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6248 // Try to match an AVX2 horizontal add/sub of signed integers.
6249 SDValue InVec2, InVec3;
6251 bool CanFold = true;
6253 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6254 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6255 ((InVec0.getOpcode() == ISD::UNDEF ||
6256 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6257 ((InVec1.getOpcode() == ISD::UNDEF ||
6258 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6259 X86Opcode = X86ISD::HADD;
6260 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6261 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6262 ((InVec0.getOpcode() == ISD::UNDEF ||
6263 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6264 ((InVec1.getOpcode() == ISD::UNDEF ||
6265 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6266 X86Opcode = X86ISD::HSUB;
6271 // Fold this build_vector into a single horizontal add/sub.
6272 // Do this only if the target has AVX2.
6273 if (Subtarget->hasAVX2())
6274 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6276 // Do not try to expand this build_vector into a pair of horizontal
6277 // add/sub if we can emit a pair of scalar add/sub.
6278 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6281 // Convert this build_vector into a pair of horizontal binop followed by
6283 bool isUndefLO = NumUndefsLO == Half;
6284 bool isUndefHI = NumUndefsHI == Half;
6285 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6286 isUndefLO, isUndefHI);
6290 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6291 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6293 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6294 X86Opcode = X86ISD::HADD;
6295 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6296 X86Opcode = X86ISD::HSUB;
6297 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6298 X86Opcode = X86ISD::FHADD;
6299 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6300 X86Opcode = X86ISD::FHSUB;
6304 // Don't try to expand this build_vector into a pair of horizontal add/sub
6305 // if we can simply emit a pair of scalar add/sub.
6306 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6309 // Convert this build_vector into two horizontal add/sub followed by
6311 bool isUndefLO = NumUndefsLO == Half;
6312 bool isUndefHI = NumUndefsHI == Half;
6313 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6314 isUndefLO, isUndefHI);
6321 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6324 MVT VT = Op.getSimpleValueType();
6325 MVT ExtVT = VT.getVectorElementType();
6326 unsigned NumElems = Op.getNumOperands();
6328 // Generate vectors for predicate vectors.
6329 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6330 return LowerBUILD_VECTORvXi1(Op, DAG);
6332 // Vectors containing all zeros can be matched by pxor and xorps later
6333 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6334 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6335 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6336 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6339 return getZeroVector(VT, Subtarget, DAG, dl);
6342 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6343 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6344 // vpcmpeqd on 256-bit vectors.
6345 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6346 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6349 if (!VT.is512BitVector())
6350 return getOnesVector(VT, Subtarget, DAG, dl);
6353 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6354 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6356 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6357 return HorizontalOp;
6358 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6361 unsigned EVTBits = ExtVT.getSizeInBits();
6363 unsigned NumZero = 0;
6364 unsigned NumNonZero = 0;
6365 uint64_t NonZeros = 0;
6366 bool IsAllConstants = true;
6367 SmallSet<SDValue, 8> Values;
6368 for (unsigned i = 0; i < NumElems; ++i) {
6369 SDValue Elt = Op.getOperand(i);
6370 if (Elt.getOpcode() == ISD::UNDEF)
6373 if (Elt.getOpcode() != ISD::Constant &&
6374 Elt.getOpcode() != ISD::ConstantFP)
6375 IsAllConstants = false;
6376 if (X86::isZeroNode(Elt))
6379 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6380 NonZeros |= ((uint64_t)1 << i);
6385 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6386 if (NumNonZero == 0)
6387 return DAG.getUNDEF(VT);
6389 // Special case for single non-zero, non-undef, element.
6390 if (NumNonZero == 1) {
6391 unsigned Idx = countTrailingZeros(NonZeros);
6392 SDValue Item = Op.getOperand(Idx);
6394 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6395 // the value are obviously zero, truncate the value to i32 and do the
6396 // insertion that way. Only do this if the value is non-constant or if the
6397 // value is a constant being inserted into element 0. It is cheaper to do
6398 // a constant pool load than it is to do a movd + shuffle.
6399 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6400 (!IsAllConstants || Idx == 0)) {
6401 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6403 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6404 MVT VecVT = MVT::v4i32;
6406 // Truncate the value (which may itself be a constant) to i32, and
6407 // convert it to a vector with movd (S2V+shuffle to zero extend).
6408 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6409 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6410 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6411 Item, Idx * 2, true, Subtarget, DAG));
6415 // If we have a constant or non-constant insertion into the low element of
6416 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6417 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6418 // depending on what the source datatype is.
6421 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6423 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6424 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6425 if (VT.is512BitVector()) {
6426 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6427 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6428 Item, DAG.getIntPtrConstant(0, dl));
6430 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6431 "Expected an SSE value type!");
6432 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6433 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6434 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6437 // We can't directly insert an i8 or i16 into a vector, so zero extend
6439 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6440 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6441 if (VT.is256BitVector()) {
6442 if (Subtarget->hasAVX()) {
6443 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6444 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6446 // Without AVX, we need to extend to a 128-bit vector and then
6447 // insert into the 256-bit vector.
6448 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6449 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6450 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6453 assert(VT.is128BitVector() && "Expected an SSE value type!");
6454 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6455 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6457 return DAG.getBitcast(VT, Item);
6461 // Is it a vector logical left shift?
6462 if (NumElems == 2 && Idx == 1 &&
6463 X86::isZeroNode(Op.getOperand(0)) &&
6464 !X86::isZeroNode(Op.getOperand(1))) {
6465 unsigned NumBits = VT.getSizeInBits();
6466 return getVShift(true, VT,
6467 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6468 VT, Op.getOperand(1)),
6469 NumBits/2, DAG, *this, dl);
6472 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6475 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6476 // is a non-constant being inserted into an element other than the low one,
6477 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6478 // movd/movss) to move this into the low element, then shuffle it into
6480 if (EVTBits == 32) {
6481 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6482 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6486 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6487 if (Values.size() == 1) {
6488 if (EVTBits == 32) {
6489 // Instead of a shuffle like this:
6490 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6491 // Check if it's possible to issue this instead.
6492 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6493 unsigned Idx = countTrailingZeros(NonZeros);
6494 SDValue Item = Op.getOperand(Idx);
6495 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6496 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6501 // A vector full of immediates; various special cases are already
6502 // handled, so this is best done with a single constant-pool load.
6506 // For AVX-length vectors, see if we can use a vector load to get all of the
6507 // elements, otherwise build the individual 128-bit pieces and use
6508 // shuffles to put them in place.
6509 if (VT.is256BitVector() || VT.is512BitVector()) {
6510 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6512 // Check for a build vector of consecutive loads.
6513 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6516 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6518 // Build both the lower and upper subvector.
6519 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6520 makeArrayRef(&V[0], NumElems/2));
6521 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6522 makeArrayRef(&V[NumElems / 2], NumElems/2));
6524 // Recreate the wider vector with the lower and upper part.
6525 if (VT.is256BitVector())
6526 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6527 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6530 // Let legalizer expand 2-wide build_vectors.
6531 if (EVTBits == 64) {
6532 if (NumNonZero == 1) {
6533 // One half is zero or undef.
6534 unsigned Idx = countTrailingZeros(NonZeros);
6535 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6536 Op.getOperand(Idx));
6537 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6542 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6543 if (EVTBits == 8 && NumElems == 16)
6544 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6545 DAG, Subtarget, *this))
6548 if (EVTBits == 16 && NumElems == 8)
6549 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6550 DAG, Subtarget, *this))
6553 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6554 if (EVTBits == 32 && NumElems == 4)
6555 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6558 // If element VT is == 32 bits, turn it into a number of shuffles.
6559 SmallVector<SDValue, 8> V(NumElems);
6560 if (NumElems == 4 && NumZero > 0) {
6561 for (unsigned i = 0; i < 4; ++i) {
6562 bool isZero = !(NonZeros & (1ULL << i));
6564 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6566 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6569 for (unsigned i = 0; i < 2; ++i) {
6570 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6573 V[i] = V[i*2]; // Must be a zero vector.
6576 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6579 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6582 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6587 bool Reverse1 = (NonZeros & 0x3) == 2;
6588 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6592 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6593 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6595 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6598 if (Values.size() > 1 && VT.is128BitVector()) {
6599 // Check for a build vector of consecutive loads.
6600 for (unsigned i = 0; i < NumElems; ++i)
6601 V[i] = Op.getOperand(i);
6603 // Check for elements which are consecutive loads.
6604 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6607 // Check for a build vector from mostly shuffle plus few inserting.
6608 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6611 // For SSE 4.1, use insertps to put the high elements into the low element.
6612 if (Subtarget->hasSSE41()) {
6614 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6615 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6617 Result = DAG.getUNDEF(VT);
6619 for (unsigned i = 1; i < NumElems; ++i) {
6620 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6621 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6622 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6627 // Otherwise, expand into a number of unpckl*, start by extending each of
6628 // our (non-undef) elements to the full vector width with the element in the
6629 // bottom slot of the vector (which generates no code for SSE).
6630 for (unsigned i = 0; i < NumElems; ++i) {
6631 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6632 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6634 V[i] = DAG.getUNDEF(VT);
6637 // Next, we iteratively mix elements, e.g. for v4f32:
6638 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6639 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6640 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6641 unsigned EltStride = NumElems >> 1;
6642 while (EltStride != 0) {
6643 for (unsigned i = 0; i < EltStride; ++i) {
6644 // If V[i+EltStride] is undef and this is the first round of mixing,
6645 // then it is safe to just drop this shuffle: V[i] is already in the
6646 // right place, the one element (since it's the first round) being
6647 // inserted as undef can be dropped. This isn't safe for successive
6648 // rounds because they will permute elements within both vectors.
6649 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6650 EltStride == NumElems/2)
6653 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6662 // 256-bit AVX can use the vinsertf128 instruction
6663 // to create 256-bit vectors from two other 128-bit ones.
6664 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6666 MVT ResVT = Op.getSimpleValueType();
6668 assert((ResVT.is256BitVector() ||
6669 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6671 SDValue V1 = Op.getOperand(0);
6672 SDValue V2 = Op.getOperand(1);
6673 unsigned NumElems = ResVT.getVectorNumElements();
6674 if (ResVT.is256BitVector())
6675 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6677 if (Op.getNumOperands() == 4) {
6678 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6679 ResVT.getVectorNumElements()/2);
6680 SDValue V3 = Op.getOperand(2);
6681 SDValue V4 = Op.getOperand(3);
6682 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6683 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6685 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6688 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6689 const X86Subtarget *Subtarget,
6690 SelectionDAG & DAG) {
6692 MVT ResVT = Op.getSimpleValueType();
6693 unsigned NumOfOperands = Op.getNumOperands();
6695 assert(isPowerOf2_32(NumOfOperands) &&
6696 "Unexpected number of operands in CONCAT_VECTORS");
6698 SDValue Undef = DAG.getUNDEF(ResVT);
6699 if (NumOfOperands > 2) {
6700 // Specialize the cases when all, or all but one, of the operands are undef.
6701 unsigned NumOfDefinedOps = 0;
6703 for (unsigned i = 0; i < NumOfOperands; i++)
6704 if (!Op.getOperand(i).isUndef()) {
6708 if (NumOfDefinedOps == 0)
6710 if (NumOfDefinedOps == 1) {
6711 unsigned SubVecNumElts =
6712 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6713 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6714 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6715 Op.getOperand(OpIdx), IdxVal);
6718 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6719 ResVT.getVectorNumElements()/2);
6720 SmallVector<SDValue, 2> Ops;
6721 for (unsigned i = 0; i < NumOfOperands/2; i++)
6722 Ops.push_back(Op.getOperand(i));
6723 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6725 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6726 Ops.push_back(Op.getOperand(i));
6727 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6728 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6732 SDValue V1 = Op.getOperand(0);
6733 SDValue V2 = Op.getOperand(1);
6734 unsigned NumElems = ResVT.getVectorNumElements();
6735 assert(V1.getValueType() == V2.getValueType() &&
6736 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6737 "Unexpected operands in CONCAT_VECTORS");
6739 if (ResVT.getSizeInBits() >= 16)
6740 return Op; // The operation is legal with KUNPCK
6742 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6743 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6744 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6745 if (IsZeroV1 && IsZeroV2)
6748 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6750 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6752 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6754 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6756 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6759 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6761 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6762 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6765 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6766 const X86Subtarget *Subtarget,
6767 SelectionDAG &DAG) {
6768 MVT VT = Op.getSimpleValueType();
6769 if (VT.getVectorElementType() == MVT::i1)
6770 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6772 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6773 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6774 Op.getNumOperands() == 4)));
6776 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6777 // from two other 128-bit ones.
6779 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6780 return LowerAVXCONCAT_VECTORS(Op, DAG);
6783 //===----------------------------------------------------------------------===//
6784 // Vector shuffle lowering
6786 // This is an experimental code path for lowering vector shuffles on x86. It is
6787 // designed to handle arbitrary vector shuffles and blends, gracefully
6788 // degrading performance as necessary. It works hard to recognize idiomatic
6789 // shuffles and lower them to optimal instruction patterns without leaving
6790 // a framework that allows reasonably efficient handling of all vector shuffle
6792 //===----------------------------------------------------------------------===//
6794 /// \brief Tiny helper function to identify a no-op mask.
6796 /// This is a somewhat boring predicate function. It checks whether the mask
6797 /// array input, which is assumed to be a single-input shuffle mask of the kind
6798 /// used by the X86 shuffle instructions (not a fully general
6799 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6800 /// in-place shuffle are 'no-op's.
6801 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6802 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6803 if (Mask[i] != -1 && Mask[i] != i)
6808 /// \brief Helper function to classify a mask as a single-input mask.
6810 /// This isn't a generic single-input test because in the vector shuffle
6811 /// lowering we canonicalize single inputs to be the first input operand. This
6812 /// means we can more quickly test for a single input by only checking whether
6813 /// an input from the second operand exists. We also assume that the size of
6814 /// mask corresponds to the size of the input vectors which isn't true in the
6815 /// fully general case.
6816 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6818 if (M >= (int)Mask.size())
6823 /// \brief Test whether there are elements crossing 128-bit lanes in this
6826 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6827 /// and we routinely test for these.
6828 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6829 int LaneSize = 128 / VT.getScalarSizeInBits();
6830 int Size = Mask.size();
6831 for (int i = 0; i < Size; ++i)
6832 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6837 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6839 /// This checks a shuffle mask to see if it is performing the same
6840 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6841 /// that it is also not lane-crossing. It may however involve a blend from the
6842 /// same lane of a second vector.
6844 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6845 /// non-trivial to compute in the face of undef lanes. The representation is
6846 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6847 /// entries from both V1 and V2 inputs to the wider mask.
6849 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6850 SmallVectorImpl<int> &RepeatedMask) {
6851 int LaneSize = 128 / VT.getScalarSizeInBits();
6852 RepeatedMask.resize(LaneSize, -1);
6853 int Size = Mask.size();
6854 for (int i = 0; i < Size; ++i) {
6857 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6858 // This entry crosses lanes, so there is no way to model this shuffle.
6861 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6862 if (RepeatedMask[i % LaneSize] == -1)
6863 // This is the first non-undef entry in this slot of a 128-bit lane.
6864 RepeatedMask[i % LaneSize] =
6865 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6866 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6867 // Found a mismatch with the repeated mask.
6873 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6876 /// This is a fast way to test a shuffle mask against a fixed pattern:
6878 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6880 /// It returns true if the mask is exactly as wide as the argument list, and
6881 /// each element of the mask is either -1 (signifying undef) or the value given
6882 /// in the argument.
6883 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6884 ArrayRef<int> ExpectedMask) {
6885 if (Mask.size() != ExpectedMask.size())
6888 int Size = Mask.size();
6890 // If the values are build vectors, we can look through them to find
6891 // equivalent inputs that make the shuffles equivalent.
6892 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6893 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6895 for (int i = 0; i < Size; ++i)
6896 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6897 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6898 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6899 if (!MaskBV || !ExpectedBV ||
6900 MaskBV->getOperand(Mask[i] % Size) !=
6901 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6908 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6910 /// This helper function produces an 8-bit shuffle immediate corresponding to
6911 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6912 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6915 /// NB: We rely heavily on "undef" masks preserving the input lane.
6916 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6917 SelectionDAG &DAG) {
6918 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6919 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6920 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6921 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6922 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6925 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6926 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6927 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6928 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6929 return DAG.getConstant(Imm, DL, MVT::i8);
6932 /// \brief Compute whether each element of a shuffle is zeroable.
6934 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6935 /// Either it is an undef element in the shuffle mask, the element of the input
6936 /// referenced is undef, or the element of the input referenced is known to be
6937 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6938 /// as many lanes with this technique as possible to simplify the remaining
6940 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6941 SDValue V1, SDValue V2) {
6942 SmallBitVector Zeroable(Mask.size(), false);
6944 while (V1.getOpcode() == ISD::BITCAST)
6945 V1 = V1->getOperand(0);
6946 while (V2.getOpcode() == ISD::BITCAST)
6947 V2 = V2->getOperand(0);
6949 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6950 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6952 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6954 // Handle the easy cases.
6955 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6960 // If this is an index into a build_vector node (which has the same number
6961 // of elements), dig out the input value and use it.
6962 SDValue V = M < Size ? V1 : V2;
6963 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6966 SDValue Input = V.getOperand(M % Size);
6967 // The UNDEF opcode check really should be dead code here, but not quite
6968 // worth asserting on (it isn't invalid, just unexpected).
6969 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6976 // X86 has dedicated unpack instructions that can handle specific blend
6977 // operations: UNPCKH and UNPCKL.
6978 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6979 SDValue V1, SDValue V2,
6980 SelectionDAG &DAG) {
6981 int NumElts = VT.getVectorNumElements();
6982 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6983 SmallVector<int, 8> Unpckl;
6984 SmallVector<int, 8> Unpckh;
6986 for (int i = 0; i < NumElts; ++i) {
6987 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6988 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6989 int HiPos = LoPos + NumEltsInLane / 2;
6990 Unpckl.push_back(LoPos);
6991 Unpckh.push_back(HiPos);
6994 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6995 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6996 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6997 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6999 // Commute and try again.
7000 ShuffleVectorSDNode::commuteMask(Unpckl);
7001 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7002 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7004 ShuffleVectorSDNode::commuteMask(Unpckh);
7005 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7006 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7011 /// \brief Try to emit a bitmask instruction for a shuffle.
7013 /// This handles cases where we can model a blend exactly as a bitmask due to
7014 /// one of the inputs being zeroable.
7015 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
7016 SDValue V2, ArrayRef<int> Mask,
7017 SelectionDAG &DAG) {
7018 MVT EltVT = VT.getVectorElementType();
7019 int NumEltBits = EltVT.getSizeInBits();
7020 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7021 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7022 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7024 if (EltVT.isFloatingPoint()) {
7025 Zero = DAG.getBitcast(EltVT, Zero);
7026 AllOnes = DAG.getBitcast(EltVT, AllOnes);
7028 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7029 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7031 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7034 if (Mask[i] % Size != i)
7035 return SDValue(); // Not a blend.
7037 V = Mask[i] < Size ? V1 : V2;
7038 else if (V != (Mask[i] < Size ? V1 : V2))
7039 return SDValue(); // Can only let one input through the mask.
7041 VMaskOps[i] = AllOnes;
7044 return SDValue(); // No non-zeroable elements!
7046 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7047 V = DAG.getNode(VT.isFloatingPoint()
7048 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7053 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7055 /// This is used as a fallback approach when first class blend instructions are
7056 /// unavailable. Currently it is only suitable for integer vectors, but could
7057 /// be generalized for floating point vectors if desirable.
7058 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7059 SDValue V2, ArrayRef<int> Mask,
7060 SelectionDAG &DAG) {
7061 assert(VT.isInteger() && "Only supports integer vector types!");
7062 MVT EltVT = VT.getVectorElementType();
7063 int NumEltBits = EltVT.getSizeInBits();
7064 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7065 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7067 SmallVector<SDValue, 16> MaskOps;
7068 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7069 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7070 return SDValue(); // Shuffled input!
7071 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7074 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7075 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7076 // We have to cast V2 around.
7077 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7078 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7079 DAG.getBitcast(MaskVT, V1Mask),
7080 DAG.getBitcast(MaskVT, V2)));
7081 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7084 /// \brief Try to emit a blend instruction for a shuffle.
7086 /// This doesn't do any checks for the availability of instructions for blending
7087 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7088 /// be matched in the backend with the type given. What it does check for is
7089 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7090 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7091 SDValue V2, ArrayRef<int> Original,
7092 const X86Subtarget *Subtarget,
7093 SelectionDAG &DAG) {
7094 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7095 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7096 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7097 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7098 bool ForceV1Zero = false, ForceV2Zero = false;
7100 // Attempt to generate the binary blend mask. If an input is zero then
7101 // we can use any lane.
7102 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7103 unsigned BlendMask = 0;
7104 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7110 if (M == i + Size) {
7111 BlendMask |= 1u << i;
7122 BlendMask |= 1u << i;
7127 return SDValue(); // Shuffled input!
7130 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7132 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7134 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7136 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7137 unsigned ScaledMask = 0;
7138 for (int i = 0; i != Size; ++i)
7139 if (BlendMask & (1u << i))
7140 for (int j = 0; j != Scale; ++j)
7141 ScaledMask |= 1u << (i * Scale + j);
7145 switch (VT.SimpleTy) {
7150 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7151 DAG.getConstant(BlendMask, DL, MVT::i8));
7155 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7159 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7160 // that instruction.
7161 if (Subtarget->hasAVX2()) {
7162 // Scale the blend by the number of 32-bit dwords per element.
7163 int Scale = VT.getScalarSizeInBits() / 32;
7164 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7165 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7166 V1 = DAG.getBitcast(BlendVT, V1);
7167 V2 = DAG.getBitcast(BlendVT, V2);
7168 return DAG.getBitcast(
7169 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7170 DAG.getConstant(BlendMask, DL, MVT::i8)));
7174 // For integer shuffles we need to expand the mask and cast the inputs to
7175 // v8i16s prior to blending.
7176 int Scale = 8 / VT.getVectorNumElements();
7177 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7178 V1 = DAG.getBitcast(MVT::v8i16, V1);
7179 V2 = DAG.getBitcast(MVT::v8i16, V2);
7180 return DAG.getBitcast(VT,
7181 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7182 DAG.getConstant(BlendMask, DL, MVT::i8)));
7186 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7187 SmallVector<int, 8> RepeatedMask;
7188 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7189 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7190 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7192 for (int i = 0; i < 8; ++i)
7193 if (RepeatedMask[i] >= 16)
7194 BlendMask |= 1u << i;
7195 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7196 DAG.getConstant(BlendMask, DL, MVT::i8));
7202 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7203 "256-bit byte-blends require AVX2 support!");
7205 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7206 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7209 // Scale the blend by the number of bytes per element.
7210 int Scale = VT.getScalarSizeInBits() / 8;
7212 // This form of blend is always done on bytes. Compute the byte vector
7214 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7216 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7217 // mix of LLVM's code generator and the x86 backend. We tell the code
7218 // generator that boolean values in the elements of an x86 vector register
7219 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7220 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7221 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7222 // of the element (the remaining are ignored) and 0 in that high bit would
7223 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7224 // the LLVM model for boolean values in vector elements gets the relevant
7225 // bit set, it is set backwards and over constrained relative to x86's
7227 SmallVector<SDValue, 32> VSELECTMask;
7228 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7229 for (int j = 0; j < Scale; ++j)
7230 VSELECTMask.push_back(
7231 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7232 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7235 V1 = DAG.getBitcast(BlendVT, V1);
7236 V2 = DAG.getBitcast(BlendVT, V2);
7237 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7238 DAG.getNode(ISD::BUILD_VECTOR, DL,
7239 BlendVT, VSELECTMask),
7244 llvm_unreachable("Not a supported integer vector type!");
7248 /// \brief Try to lower as a blend of elements from two inputs followed by
7249 /// a single-input permutation.
7251 /// This matches the pattern where we can blend elements from two inputs and
7252 /// then reduce the shuffle to a single-input permutation.
7253 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7256 SelectionDAG &DAG) {
7257 // We build up the blend mask while checking whether a blend is a viable way
7258 // to reduce the shuffle.
7259 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7260 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7262 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7266 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7268 if (BlendMask[Mask[i] % Size] == -1)
7269 BlendMask[Mask[i] % Size] = Mask[i];
7270 else if (BlendMask[Mask[i] % Size] != Mask[i])
7271 return SDValue(); // Can't blend in the needed input!
7273 PermuteMask[i] = Mask[i] % Size;
7276 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7277 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7280 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7281 /// blends and permutes.
7283 /// This matches the extremely common pattern for handling combined
7284 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7285 /// operations. It will try to pick the best arrangement of shuffles and
7287 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7291 SelectionDAG &DAG) {
7292 // Shuffle the input elements into the desired positions in V1 and V2 and
7293 // blend them together.
7294 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7295 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7296 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7297 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7298 if (Mask[i] >= 0 && Mask[i] < Size) {
7299 V1Mask[i] = Mask[i];
7301 } else if (Mask[i] >= Size) {
7302 V2Mask[i] = Mask[i] - Size;
7303 BlendMask[i] = i + Size;
7306 // Try to lower with the simpler initial blend strategy unless one of the
7307 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7308 // shuffle may be able to fold with a load or other benefit. However, when
7309 // we'll have to do 2x as many shuffles in order to achieve this, blending
7310 // first is a better strategy.
7311 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7312 if (SDValue BlendPerm =
7313 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7316 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7317 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7318 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7321 /// \brief Try to lower a vector shuffle as a byte rotation.
7323 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7324 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7325 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7326 /// try to generically lower a vector shuffle through such an pattern. It
7327 /// does not check for the profitability of lowering either as PALIGNR or
7328 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7329 /// This matches shuffle vectors that look like:
7331 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7333 /// Essentially it concatenates V1 and V2, shifts right by some number of
7334 /// elements, and takes the low elements as the result. Note that while this is
7335 /// specified as a *right shift* because x86 is little-endian, it is a *left
7336 /// rotate* of the vector lanes.
7337 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7340 const X86Subtarget *Subtarget,
7341 SelectionDAG &DAG) {
7342 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7344 int NumElts = Mask.size();
7345 int NumLanes = VT.getSizeInBits() / 128;
7346 int NumLaneElts = NumElts / NumLanes;
7348 // We need to detect various ways of spelling a rotation:
7349 // [11, 12, 13, 14, 15, 0, 1, 2]
7350 // [-1, 12, 13, 14, -1, -1, 1, -1]
7351 // [-1, -1, -1, -1, -1, -1, 1, 2]
7352 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7353 // [-1, 4, 5, 6, -1, -1, 9, -1]
7354 // [-1, 4, 5, 6, -1, -1, -1, -1]
7357 for (int l = 0; l < NumElts; l += NumLaneElts) {
7358 for (int i = 0; i < NumLaneElts; ++i) {
7359 if (Mask[l + i] == -1)
7361 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7363 // Get the mod-Size index and lane correct it.
7364 int LaneIdx = (Mask[l + i] % NumElts) - l;
7365 // Make sure it was in this lane.
7366 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7369 // Determine where a rotated vector would have started.
7370 int StartIdx = i - LaneIdx;
7372 // The identity rotation isn't interesting, stop.
7375 // If we found the tail of a vector the rotation must be the missing
7376 // front. If we found the head of a vector, it must be how much of the
7378 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7381 Rotation = CandidateRotation;
7382 else if (Rotation != CandidateRotation)
7383 // The rotations don't match, so we can't match this mask.
7386 // Compute which value this mask is pointing at.
7387 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7389 // Compute which of the two target values this index should be assigned
7390 // to. This reflects whether the high elements are remaining or the low
7391 // elements are remaining.
7392 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7394 // Either set up this value if we've not encountered it before, or check
7395 // that it remains consistent.
7398 else if (TargetV != MaskV)
7399 // This may be a rotation, but it pulls from the inputs in some
7400 // unsupported interleaving.
7405 // Check that we successfully analyzed the mask, and normalize the results.
7406 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7407 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7413 // The actual rotate instruction rotates bytes, so we need to scale the
7414 // rotation based on how many bytes are in the vector lane.
7415 int Scale = 16 / NumLaneElts;
7417 // SSSE3 targets can use the palignr instruction.
7418 if (Subtarget->hasSSSE3()) {
7419 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7420 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7421 Lo = DAG.getBitcast(AlignVT, Lo);
7422 Hi = DAG.getBitcast(AlignVT, Hi);
7424 return DAG.getBitcast(
7425 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7426 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7429 assert(VT.is128BitVector() &&
7430 "Rotate-based lowering only supports 128-bit lowering!");
7431 assert(Mask.size() <= 16 &&
7432 "Can shuffle at most 16 bytes in a 128-bit vector!");
7434 // Default SSE2 implementation
7435 int LoByteShift = 16 - Rotation * Scale;
7436 int HiByteShift = Rotation * Scale;
7438 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7439 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7440 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7442 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7443 DAG.getConstant(LoByteShift, DL, MVT::i8));
7444 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7445 DAG.getConstant(HiByteShift, DL, MVT::i8));
7446 return DAG.getBitcast(VT,
7447 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7450 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7452 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7453 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7454 /// matches elements from one of the input vectors shuffled to the left or
7455 /// right with zeroable elements 'shifted in'. It handles both the strictly
7456 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7459 /// PSHL : (little-endian) left bit shift.
7460 /// [ zz, 0, zz, 2 ]
7461 /// [ -1, 4, zz, -1 ]
7462 /// PSRL : (little-endian) right bit shift.
7464 /// [ -1, -1, 7, zz]
7465 /// PSLLDQ : (little-endian) left byte shift
7466 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7467 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7468 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7469 /// PSRLDQ : (little-endian) right byte shift
7470 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7471 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7472 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7473 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7474 SDValue V2, ArrayRef<int> Mask,
7475 SelectionDAG &DAG) {
7476 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7478 int Size = Mask.size();
7479 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7481 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7482 for (int i = 0; i < Size; i += Scale)
7483 for (int j = 0; j < Shift; ++j)
7484 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7490 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7491 for (int i = 0; i != Size; i += Scale) {
7492 unsigned Pos = Left ? i + Shift : i;
7493 unsigned Low = Left ? i : i + Shift;
7494 unsigned Len = Scale - Shift;
7495 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7496 Low + (V == V1 ? 0 : Size)))
7500 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7501 bool ByteShift = ShiftEltBits > 64;
7502 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7503 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7504 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7506 // Normalize the scale for byte shifts to still produce an i64 element
7508 Scale = ByteShift ? Scale / 2 : Scale;
7510 // We need to round trip through the appropriate type for the shift.
7511 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7512 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7513 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7514 "Illegal integer vector type");
7515 V = DAG.getBitcast(ShiftVT, V);
7517 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7518 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7519 return DAG.getBitcast(VT, V);
7522 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7523 // keep doubling the size of the integer elements up to that. We can
7524 // then shift the elements of the integer vector by whole multiples of
7525 // their width within the elements of the larger integer vector. Test each
7526 // multiple to see if we can find a match with the moved element indices
7527 // and that the shifted in elements are all zeroable.
7528 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7529 for (int Shift = 1; Shift != Scale; ++Shift)
7530 for (bool Left : {true, false})
7531 if (CheckZeros(Shift, Scale, Left))
7532 for (SDValue V : {V1, V2})
7533 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7540 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7541 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7542 SDValue V2, ArrayRef<int> Mask,
7543 SelectionDAG &DAG) {
7544 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7545 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7547 int Size = Mask.size();
7548 int HalfSize = Size / 2;
7549 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7551 // Upper half must be undefined.
7552 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7555 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7556 // Remainder of lower half result is zero and upper half is all undef.
7557 auto LowerAsEXTRQ = [&]() {
7558 // Determine the extraction length from the part of the
7559 // lower half that isn't zeroable.
7561 for (; Len > 0; --Len)
7562 if (!Zeroable[Len - 1])
7564 assert(Len > 0 && "Zeroable shuffle mask");
7566 // Attempt to match first Len sequential elements from the lower half.
7569 for (int i = 0; i != Len; ++i) {
7573 SDValue &V = (M < Size ? V1 : V2);
7576 // The extracted elements must start at a valid index and all mask
7577 // elements must be in the lower half.
7578 if (i > M || M >= HalfSize)
7581 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7592 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7593 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7594 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7595 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7596 DAG.getConstant(BitLen, DL, MVT::i8),
7597 DAG.getConstant(BitIdx, DL, MVT::i8));
7600 if (SDValue ExtrQ = LowerAsEXTRQ())
7603 // INSERTQ: Extract lowest Len elements from lower half of second source and
7604 // insert over first source, starting at Idx.
7605 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7606 auto LowerAsInsertQ = [&]() {
7607 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7610 // Attempt to match first source from mask before insertion point.
7611 if (isUndefInRange(Mask, 0, Idx)) {
7613 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7615 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7621 // Extend the extraction length looking to match both the insertion of
7622 // the second source and the remaining elements of the first.
7623 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7628 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7630 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7636 // Match the remaining elements of the lower half.
7637 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7639 } else if ((!Base || (Base == V1)) &&
7640 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7642 } else if ((!Base || (Base == V2)) &&
7643 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7650 // We may not have a base (first source) - this can safely be undefined.
7652 Base = DAG.getUNDEF(VT);
7654 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7655 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7656 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7657 DAG.getConstant(BitLen, DL, MVT::i8),
7658 DAG.getConstant(BitIdx, DL, MVT::i8));
7665 if (SDValue InsertQ = LowerAsInsertQ())
7671 /// \brief Lower a vector shuffle as a zero or any extension.
7673 /// Given a specific number of elements, element bit width, and extension
7674 /// stride, produce either a zero or any extension based on the available
7675 /// features of the subtarget. The extended elements are consecutive and
7676 /// begin and can start from an offseted element index in the input; to
7677 /// avoid excess shuffling the offset must either being in the bottom lane
7678 /// or at the start of a higher lane. All extended elements must be from
7680 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7681 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7682 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7683 assert(Scale > 1 && "Need a scale to extend.");
7684 int EltBits = VT.getScalarSizeInBits();
7685 int NumElements = VT.getVectorNumElements();
7686 int NumEltsPerLane = 128 / EltBits;
7687 int OffsetLane = Offset / NumEltsPerLane;
7688 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7689 "Only 8, 16, and 32 bit elements can be extended.");
7690 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7691 assert(0 <= Offset && "Extension offset must be positive.");
7692 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7693 "Extension offset must be in the first lane or start an upper lane.");
7695 // Check that an index is in same lane as the base offset.
7696 auto SafeOffset = [&](int Idx) {
7697 return OffsetLane == (Idx / NumEltsPerLane);
7700 // Shift along an input so that the offset base moves to the first element.
7701 auto ShuffleOffset = [&](SDValue V) {
7705 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7706 for (int i = 0; i * Scale < NumElements; ++i) {
7707 int SrcIdx = i + Offset;
7708 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7710 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7713 // Found a valid zext mask! Try various lowering strategies based on the
7714 // input type and available ISA extensions.
7715 if (Subtarget->hasSSE41()) {
7716 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7717 // PUNPCK will catch this in a later shuffle match.
7718 if (Offset && Scale == 2 && VT.is128BitVector())
7720 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7721 NumElements / Scale);
7722 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7723 return DAG.getBitcast(VT, InputV);
7726 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7728 // For any extends we can cheat for larger element sizes and use shuffle
7729 // instructions that can fold with a load and/or copy.
7730 if (AnyExt && EltBits == 32) {
7731 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7733 return DAG.getBitcast(
7734 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7735 DAG.getBitcast(MVT::v4i32, InputV),
7736 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7738 if (AnyExt && EltBits == 16 && Scale > 2) {
7739 int PSHUFDMask[4] = {Offset / 2, -1,
7740 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7741 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7742 DAG.getBitcast(MVT::v4i32, InputV),
7743 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7744 int PSHUFWMask[4] = {1, -1, -1, -1};
7745 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7746 return DAG.getBitcast(
7747 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7748 DAG.getBitcast(MVT::v8i16, InputV),
7749 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7752 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7754 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7755 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7756 assert(VT.is128BitVector() && "Unexpected vector width!");
7758 int LoIdx = Offset * EltBits;
7759 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7760 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7761 DAG.getConstant(EltBits, DL, MVT::i8),
7762 DAG.getConstant(LoIdx, DL, MVT::i8)));
7764 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7765 !SafeOffset(Offset + 1))
7766 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7768 int HiIdx = (Offset + 1) * EltBits;
7769 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7770 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7771 DAG.getConstant(EltBits, DL, MVT::i8),
7772 DAG.getConstant(HiIdx, DL, MVT::i8)));
7773 return DAG.getNode(ISD::BITCAST, DL, VT,
7774 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7777 // If this would require more than 2 unpack instructions to expand, use
7778 // pshufb when available. We can only use more than 2 unpack instructions
7779 // when zero extending i8 elements which also makes it easier to use pshufb.
7780 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7781 assert(NumElements == 16 && "Unexpected byte vector width!");
7782 SDValue PSHUFBMask[16];
7783 for (int i = 0; i < 16; ++i) {
7784 int Idx = Offset + (i / Scale);
7785 PSHUFBMask[i] = DAG.getConstant(
7786 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7788 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7789 return DAG.getBitcast(VT,
7790 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7791 DAG.getNode(ISD::BUILD_VECTOR, DL,
7792 MVT::v16i8, PSHUFBMask)));
7795 // If we are extending from an offset, ensure we start on a boundary that
7796 // we can unpack from.
7797 int AlignToUnpack = Offset % (NumElements / Scale);
7798 if (AlignToUnpack) {
7799 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7800 for (int i = AlignToUnpack; i < NumElements; ++i)
7801 ShMask[i - AlignToUnpack] = i;
7802 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7803 Offset -= AlignToUnpack;
7806 // Otherwise emit a sequence of unpacks.
7808 unsigned UnpackLoHi = X86ISD::UNPCKL;
7809 if (Offset >= (NumElements / 2)) {
7810 UnpackLoHi = X86ISD::UNPCKH;
7811 Offset -= (NumElements / 2);
7814 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7815 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7816 : getZeroVector(InputVT, Subtarget, DAG, DL);
7817 InputV = DAG.getBitcast(InputVT, InputV);
7818 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7822 } while (Scale > 1);
7823 return DAG.getBitcast(VT, InputV);
7826 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7828 /// This routine will try to do everything in its power to cleverly lower
7829 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7830 /// check for the profitability of this lowering, it tries to aggressively
7831 /// match this pattern. It will use all of the micro-architectural details it
7832 /// can to emit an efficient lowering. It handles both blends with all-zero
7833 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7834 /// masking out later).
7836 /// The reason we have dedicated lowering for zext-style shuffles is that they
7837 /// are both incredibly common and often quite performance sensitive.
7838 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7839 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7840 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7841 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7843 int Bits = VT.getSizeInBits();
7844 int NumLanes = Bits / 128;
7845 int NumElements = VT.getVectorNumElements();
7846 int NumEltsPerLane = NumElements / NumLanes;
7847 assert(VT.getScalarSizeInBits() <= 32 &&
7848 "Exceeds 32-bit integer zero extension limit");
7849 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7851 // Define a helper function to check a particular ext-scale and lower to it if
7853 auto Lower = [&](int Scale) -> SDValue {
7858 for (int i = 0; i < NumElements; ++i) {
7861 continue; // Valid anywhere but doesn't tell us anything.
7862 if (i % Scale != 0) {
7863 // Each of the extended elements need to be zeroable.
7867 // We no longer are in the anyext case.
7872 // Each of the base elements needs to be consecutive indices into the
7873 // same input vector.
7874 SDValue V = M < NumElements ? V1 : V2;
7875 M = M % NumElements;
7878 Offset = M - (i / Scale);
7879 } else if (InputV != V)
7880 return SDValue(); // Flip-flopping inputs.
7882 // Offset must start in the lowest 128-bit lane or at the start of an
7884 // FIXME: Is it ever worth allowing a negative base offset?
7885 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7886 (Offset % NumEltsPerLane) == 0))
7889 // If we are offsetting, all referenced entries must come from the same
7891 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7894 if ((M % NumElements) != (Offset + (i / Scale)))
7895 return SDValue(); // Non-consecutive strided elements.
7899 // If we fail to find an input, we have a zero-shuffle which should always
7900 // have already been handled.
7901 // FIXME: Maybe handle this here in case during blending we end up with one?
7905 // If we are offsetting, don't extend if we only match a single input, we
7906 // can always do better by using a basic PSHUF or PUNPCK.
7907 if (Offset != 0 && Matches < 2)
7910 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7911 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7914 // The widest scale possible for extending is to a 64-bit integer.
7915 assert(Bits % 64 == 0 &&
7916 "The number of bits in a vector must be divisible by 64 on x86!");
7917 int NumExtElements = Bits / 64;
7919 // Each iteration, try extending the elements half as much, but into twice as
7921 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7922 assert(NumElements % NumExtElements == 0 &&
7923 "The input vector size must be divisible by the extended size.");
7924 if (SDValue V = Lower(NumElements / NumExtElements))
7928 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7932 // Returns one of the source operands if the shuffle can be reduced to a
7933 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7934 auto CanZExtLowHalf = [&]() {
7935 for (int i = NumElements / 2; i != NumElements; ++i)
7938 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7940 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7945 if (SDValue V = CanZExtLowHalf()) {
7946 V = DAG.getBitcast(MVT::v2i64, V);
7947 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7948 return DAG.getBitcast(VT, V);
7951 // No viable ext lowering found.
7955 /// \brief Try to get a scalar value for a specific element of a vector.
7957 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7958 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7959 SelectionDAG &DAG) {
7960 MVT VT = V.getSimpleValueType();
7961 MVT EltVT = VT.getVectorElementType();
7962 while (V.getOpcode() == ISD::BITCAST)
7963 V = V.getOperand(0);
7964 // If the bitcasts shift the element size, we can't extract an equivalent
7966 MVT NewVT = V.getSimpleValueType();
7967 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7970 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7971 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7972 // Ensure the scalar operand is the same size as the destination.
7973 // FIXME: Add support for scalar truncation where possible.
7974 SDValue S = V.getOperand(Idx);
7975 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7976 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7982 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7984 /// This is particularly important because the set of instructions varies
7985 /// significantly based on whether the operand is a load or not.
7986 static bool isShuffleFoldableLoad(SDValue V) {
7987 while (V.getOpcode() == ISD::BITCAST)
7988 V = V.getOperand(0);
7990 return ISD::isNON_EXTLoad(V.getNode());
7993 /// \brief Try to lower insertion of a single element into a zero vector.
7995 /// This is a common pattern that we have especially efficient patterns to lower
7996 /// across all subtarget feature sets.
7997 static SDValue lowerVectorShuffleAsElementInsertion(
7998 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7999 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8000 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8002 MVT EltVT = VT.getVectorElementType();
8004 int V2Index = std::find_if(Mask.begin(), Mask.end(),
8005 [&Mask](int M) { return M >= (int)Mask.size(); }) -
8007 bool IsV1Zeroable = true;
8008 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8009 if (i != V2Index && !Zeroable[i]) {
8010 IsV1Zeroable = false;
8014 // Check for a single input from a SCALAR_TO_VECTOR node.
8015 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8016 // all the smarts here sunk into that routine. However, the current
8017 // lowering of BUILD_VECTOR makes that nearly impossible until the old
8018 // vector shuffle lowering is dead.
8019 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8021 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8022 // We need to zext the scalar if it is smaller than an i32.
8023 V2S = DAG.getBitcast(EltVT, V2S);
8024 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8025 // Using zext to expand a narrow element won't work for non-zero
8030 // Zero-extend directly to i32.
8032 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8034 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8035 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8036 EltVT == MVT::i16) {
8037 // Either not inserting from the low element of the input or the input
8038 // element size is too small to use VZEXT_MOVL to clear the high bits.
8042 if (!IsV1Zeroable) {
8043 // If V1 can't be treated as a zero vector we have fewer options to lower
8044 // this. We can't support integer vectors or non-zero targets cheaply, and
8045 // the V1 elements can't be permuted in any way.
8046 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8047 if (!VT.isFloatingPoint() || V2Index != 0)
8049 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8050 V1Mask[V2Index] = -1;
8051 if (!isNoopShuffleMask(V1Mask))
8053 // This is essentially a special case blend operation, but if we have
8054 // general purpose blend operations, they are always faster. Bail and let
8055 // the rest of the lowering handle these as blends.
8056 if (Subtarget->hasSSE41())
8059 // Otherwise, use MOVSD or MOVSS.
8060 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8061 "Only two types of floating point element types to handle!");
8062 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8066 // This lowering only works for the low element with floating point vectors.
8067 if (VT.isFloatingPoint() && V2Index != 0)
8070 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8072 V2 = DAG.getBitcast(VT, V2);
8075 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8076 // the desired position. Otherwise it is more efficient to do a vector
8077 // shift left. We know that we can do a vector shift left because all
8078 // the inputs are zero.
8079 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8080 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8081 V2Shuffle[V2Index] = 0;
8082 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8084 V2 = DAG.getBitcast(MVT::v2i64, V2);
8086 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8087 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8088 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8089 DAG.getDataLayout(), VT)));
8090 V2 = DAG.getBitcast(VT, V2);
8096 /// \brief Try to lower broadcast of a single - truncated - integer element,
8097 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8099 /// This assumes we have AVX2.
8100 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8102 const X86Subtarget *Subtarget,
8103 SelectionDAG &DAG) {
8104 assert(Subtarget->hasAVX2() &&
8105 "We can only lower integer broadcasts with AVX2!");
8107 EVT EltVT = VT.getVectorElementType();
8108 EVT V0VT = V0.getValueType();
8110 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8111 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8113 EVT V0EltVT = V0VT.getVectorElementType();
8114 if (!V0EltVT.isInteger())
8117 const unsigned EltSize = EltVT.getSizeInBits();
8118 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8120 // This is only a truncation if the original element type is larger.
8121 if (V0EltSize <= EltSize)
8124 assert(((V0EltSize % EltSize) == 0) &&
8125 "Scalar type sizes must all be powers of 2 on x86!");
8127 const unsigned V0Opc = V0.getOpcode();
8128 const unsigned Scale = V0EltSize / EltSize;
8129 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8131 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8132 V0Opc != ISD::BUILD_VECTOR)
8135 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8137 // If we're extracting non-least-significant bits, shift so we can truncate.
8138 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8139 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8140 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8141 if (const int OffsetIdx = BroadcastIdx % Scale)
8142 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8143 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8145 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8146 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8149 /// \brief Try to lower broadcast of a single element.
8151 /// For convenience, this code also bundles all of the subtarget feature set
8152 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8153 /// a convenient way to factor it out.
8154 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8155 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8157 const X86Subtarget *Subtarget,
8158 SelectionDAG &DAG) {
8159 if (!Subtarget->hasAVX())
8161 if (VT.isInteger() && !Subtarget->hasAVX2())
8164 // Check that the mask is a broadcast.
8165 int BroadcastIdx = -1;
8167 if (M >= 0 && BroadcastIdx == -1)
8169 else if (M >= 0 && M != BroadcastIdx)
8172 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8173 "a sorted mask where the broadcast "
8176 // Go up the chain of (vector) values to find a scalar load that we can
8177 // combine with the broadcast.
8179 switch (V.getOpcode()) {
8180 case ISD::CONCAT_VECTORS: {
8181 int OperandSize = Mask.size() / V.getNumOperands();
8182 V = V.getOperand(BroadcastIdx / OperandSize);
8183 BroadcastIdx %= OperandSize;
8187 case ISD::INSERT_SUBVECTOR: {
8188 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8189 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8193 int BeginIdx = (int)ConstantIdx->getZExtValue();
8195 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8196 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8197 BroadcastIdx -= BeginIdx;
8208 // Check if this is a broadcast of a scalar. We special case lowering
8209 // for scalars so that we can more effectively fold with loads.
8210 // First, look through bitcast: if the original value has a larger element
8211 // type than the shuffle, the broadcast element is in essence truncated.
8212 // Make that explicit to ease folding.
8213 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8214 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8215 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8216 return TruncBroadcast;
8218 MVT BroadcastVT = VT;
8220 // Peek through any bitcast (only useful for loads).
8222 while (BC.getOpcode() == ISD::BITCAST)
8223 BC = BC.getOperand(0);
8225 // Also check the simpler case, where we can directly reuse the scalar.
8226 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8227 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8228 V = V.getOperand(BroadcastIdx);
8230 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8231 // Only AVX2 has register broadcasts.
8232 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8234 } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8235 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8236 if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8237 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8239 // If we are broadcasting a load that is only used by the shuffle
8240 // then we can reduce the vector load to the broadcasted scalar load.
8241 LoadSDNode *Ld = cast<LoadSDNode>(BC);
8242 SDValue BaseAddr = Ld->getOperand(1);
8243 EVT AddrVT = BaseAddr.getValueType();
8244 EVT SVT = BroadcastVT.getScalarType();
8245 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8246 SDValue NewAddr = DAG.getNode(
8247 ISD::ADD, DL, AddrVT, BaseAddr,
8248 DAG.getConstant(Offset, DL, AddrVT));
8249 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8250 DAG.getMachineFunction().getMachineMemOperand(
8251 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8252 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8253 // We can't broadcast from a vector register without AVX2, and we can only
8254 // broadcast from the zero-element of a vector register.
8258 V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8259 return DAG.getBitcast(VT, V);
8262 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8263 // INSERTPS when the V1 elements are already in the correct locations
8264 // because otherwise we can just always use two SHUFPS instructions which
8265 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8266 // perform INSERTPS if a single V1 element is out of place and all V2
8267 // elements are zeroable.
8268 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8270 SelectionDAG &DAG) {
8271 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8272 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8273 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8274 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8276 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8279 int V1DstIndex = -1;
8280 int V2DstIndex = -1;
8281 bool V1UsedInPlace = false;
8283 for (int i = 0; i < 4; ++i) {
8284 // Synthesize a zero mask from the zeroable elements (includes undefs).
8290 // Flag if we use any V1 inputs in place.
8292 V1UsedInPlace = true;
8296 // We can only insert a single non-zeroable element.
8297 if (V1DstIndex != -1 || V2DstIndex != -1)
8301 // V1 input out of place for insertion.
8304 // V2 input for insertion.
8309 // Don't bother if we have no (non-zeroable) element for insertion.
8310 if (V1DstIndex == -1 && V2DstIndex == -1)
8313 // Determine element insertion src/dst indices. The src index is from the
8314 // start of the inserted vector, not the start of the concatenated vector.
8315 unsigned V2SrcIndex = 0;
8316 if (V1DstIndex != -1) {
8317 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8318 // and don't use the original V2 at all.
8319 V2SrcIndex = Mask[V1DstIndex];
8320 V2DstIndex = V1DstIndex;
8323 V2SrcIndex = Mask[V2DstIndex] - 4;
8326 // If no V1 inputs are used in place, then the result is created only from
8327 // the zero mask and the V2 insertion - so remove V1 dependency.
8329 V1 = DAG.getUNDEF(MVT::v4f32);
8331 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8332 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8334 // Insert the V2 element into the desired position.
8336 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8337 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8340 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8341 /// UNPCK instruction.
8343 /// This specifically targets cases where we end up with alternating between
8344 /// the two inputs, and so can permute them into something that feeds a single
8345 /// UNPCK instruction. Note that this routine only targets integer vectors
8346 /// because for floating point vectors we have a generalized SHUFPS lowering
8347 /// strategy that handles everything that doesn't *exactly* match an unpack,
8348 /// making this clever lowering unnecessary.
8349 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8350 SDValue V1, SDValue V2,
8352 SelectionDAG &DAG) {
8353 assert(!VT.isFloatingPoint() &&
8354 "This routine only supports integer vectors.");
8355 assert(!isSingleInputShuffleMask(Mask) &&
8356 "This routine should only be used when blending two inputs.");
8357 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8359 int Size = Mask.size();
8361 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8362 return M >= 0 && M % Size < Size / 2;
8364 int NumHiInputs = std::count_if(
8365 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8367 bool UnpackLo = NumLoInputs >= NumHiInputs;
8369 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8370 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8371 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8373 for (int i = 0; i < Size; ++i) {
8377 // Each element of the unpack contains Scale elements from this mask.
8378 int UnpackIdx = i / Scale;
8380 // We only handle the case where V1 feeds the first slots of the unpack.
8381 // We rely on canonicalization to ensure this is the case.
8382 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8385 // Setup the mask for this input. The indexing is tricky as we have to
8386 // handle the unpack stride.
8387 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8388 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8392 // If we will have to shuffle both inputs to use the unpack, check whether
8393 // we can just unpack first and shuffle the result. If so, skip this unpack.
8394 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8395 !isNoopShuffleMask(V2Mask))
8398 // Shuffle the inputs into place.
8399 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8400 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8402 // Cast the inputs to the type we will use to unpack them.
8403 V1 = DAG.getBitcast(UnpackVT, V1);
8404 V2 = DAG.getBitcast(UnpackVT, V2);
8406 // Unpack the inputs and cast the result back to the desired type.
8407 return DAG.getBitcast(
8408 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8412 // We try each unpack from the largest to the smallest to try and find one
8413 // that fits this mask.
8414 int OrigNumElements = VT.getVectorNumElements();
8415 int OrigScalarSize = VT.getScalarSizeInBits();
8416 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8417 int Scale = ScalarSize / OrigScalarSize;
8418 int NumElements = OrigNumElements / Scale;
8419 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8420 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8424 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8426 if (NumLoInputs == 0 || NumHiInputs == 0) {
8427 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8428 "We have to have *some* inputs!");
8429 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8431 // FIXME: We could consider the total complexity of the permute of each
8432 // possible unpacking. Or at the least we should consider how many
8433 // half-crossings are created.
8434 // FIXME: We could consider commuting the unpacks.
8436 SmallVector<int, 32> PermMask;
8437 PermMask.assign(Size, -1);
8438 for (int i = 0; i < Size; ++i) {
8442 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8445 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8447 return DAG.getVectorShuffle(
8448 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8450 DAG.getUNDEF(VT), PermMask);
8456 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8458 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8459 /// support for floating point shuffles but not integer shuffles. These
8460 /// instructions will incur a domain crossing penalty on some chips though so
8461 /// it is better to avoid lowering through this for integer vectors where
8463 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8464 const X86Subtarget *Subtarget,
8465 SelectionDAG &DAG) {
8467 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8468 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8469 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8471 ArrayRef<int> Mask = SVOp->getMask();
8472 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8474 if (isSingleInputShuffleMask(Mask)) {
8475 // Use low duplicate instructions for masks that match their pattern.
8476 if (Subtarget->hasSSE3())
8477 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8478 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8480 // Straight shuffle of a single input vector. Simulate this by using the
8481 // single input as both of the "inputs" to this instruction..
8482 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8484 if (Subtarget->hasAVX()) {
8485 // If we have AVX, we can use VPERMILPS which will allow folding a load
8486 // into the shuffle.
8487 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8488 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8491 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8492 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8494 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8495 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8497 // If we have a single input, insert that into V1 if we can do so cheaply.
8498 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8499 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8500 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8502 // Try inverting the insertion since for v2 masks it is easy to do and we
8503 // can't reliably sort the mask one way or the other.
8504 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8505 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8506 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8507 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8511 // Try to use one of the special instruction patterns to handle two common
8512 // blend patterns if a zero-blend above didn't work.
8513 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8514 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8515 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8516 // We can either use a special instruction to load over the low double or
8517 // to move just the low double.
8519 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8521 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8523 if (Subtarget->hasSSE41())
8524 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8528 // Use dedicated unpack instructions for masks that match their pattern.
8530 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8533 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8534 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8535 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8538 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8540 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8541 /// the integer unit to minimize domain crossing penalties. However, for blends
8542 /// it falls back to the floating point shuffle operation with appropriate bit
8544 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8545 const X86Subtarget *Subtarget,
8546 SelectionDAG &DAG) {
8548 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8549 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8550 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8551 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8552 ArrayRef<int> Mask = SVOp->getMask();
8553 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8555 if (isSingleInputShuffleMask(Mask)) {
8556 // Check for being able to broadcast a single element.
8557 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8558 Mask, Subtarget, DAG))
8561 // Straight shuffle of a single input vector. For everything from SSE2
8562 // onward this has a single fast instruction with no scary immediates.
8563 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8564 V1 = DAG.getBitcast(MVT::v4i32, V1);
8565 int WidenedMask[4] = {
8566 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8567 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8568 return DAG.getBitcast(
8570 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8571 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8573 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8574 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8575 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8576 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8578 // If we have a blend of two PACKUS operations an the blend aligns with the
8579 // low and half halves, we can just merge the PACKUS operations. This is
8580 // particularly important as it lets us merge shuffles that this routine itself
8582 auto GetPackNode = [](SDValue V) {
8583 while (V.getOpcode() == ISD::BITCAST)
8584 V = V.getOperand(0);
8586 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8588 if (SDValue V1Pack = GetPackNode(V1))
8589 if (SDValue V2Pack = GetPackNode(V2))
8590 return DAG.getBitcast(MVT::v2i64,
8591 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8592 Mask[0] == 0 ? V1Pack.getOperand(0)
8593 : V1Pack.getOperand(1),
8594 Mask[1] == 2 ? V2Pack.getOperand(0)
8595 : V2Pack.getOperand(1)));
8597 // Try to use shift instructions.
8599 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8602 // When loading a scalar and then shuffling it into a vector we can often do
8603 // the insertion cheaply.
8604 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8605 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8607 // Try inverting the insertion since for v2 masks it is easy to do and we
8608 // can't reliably sort the mask one way or the other.
8609 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8610 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8611 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8614 // We have different paths for blend lowering, but they all must use the
8615 // *exact* same predicate.
8616 bool IsBlendSupported = Subtarget->hasSSE41();
8617 if (IsBlendSupported)
8618 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8622 // Use dedicated unpack instructions for masks that match their pattern.
8624 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8627 // Try to use byte rotation instructions.
8628 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8629 if (Subtarget->hasSSSE3())
8630 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8631 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8634 // If we have direct support for blends, we should lower by decomposing into
8635 // a permute. That will be faster than the domain cross.
8636 if (IsBlendSupported)
8637 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8640 // We implement this with SHUFPD which is pretty lame because it will likely
8641 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8642 // However, all the alternatives are still more cycles and newer chips don't
8643 // have this problem. It would be really nice if x86 had better shuffles here.
8644 V1 = DAG.getBitcast(MVT::v2f64, V1);
8645 V2 = DAG.getBitcast(MVT::v2f64, V2);
8646 return DAG.getBitcast(MVT::v2i64,
8647 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8650 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8652 /// This is used to disable more specialized lowerings when the shufps lowering
8653 /// will happen to be efficient.
8654 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8655 // This routine only handles 128-bit shufps.
8656 assert(Mask.size() == 4 && "Unsupported mask size!");
8658 // To lower with a single SHUFPS we need to have the low half and high half
8659 // each requiring a single input.
8660 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8662 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8668 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8670 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8671 /// It makes no assumptions about whether this is the *best* lowering, it simply
8673 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8674 ArrayRef<int> Mask, SDValue V1,
8675 SDValue V2, SelectionDAG &DAG) {
8676 SDValue LowV = V1, HighV = V2;
8677 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8680 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8682 if (NumV2Elements == 1) {
8684 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8687 // Compute the index adjacent to V2Index and in the same half by toggling
8689 int V2AdjIndex = V2Index ^ 1;
8691 if (Mask[V2AdjIndex] == -1) {
8692 // Handles all the cases where we have a single V2 element and an undef.
8693 // This will only ever happen in the high lanes because we commute the
8694 // vector otherwise.
8696 std::swap(LowV, HighV);
8697 NewMask[V2Index] -= 4;
8699 // Handle the case where the V2 element ends up adjacent to a V1 element.
8700 // To make this work, blend them together as the first step.
8701 int V1Index = V2AdjIndex;
8702 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8703 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8704 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8706 // Now proceed to reconstruct the final blend as we have the necessary
8707 // high or low half formed.
8714 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8715 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8717 } else if (NumV2Elements == 2) {
8718 if (Mask[0] < 4 && Mask[1] < 4) {
8719 // Handle the easy case where we have V1 in the low lanes and V2 in the
8723 } else if (Mask[2] < 4 && Mask[3] < 4) {
8724 // We also handle the reversed case because this utility may get called
8725 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8726 // arrange things in the right direction.
8732 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8733 // trying to place elements directly, just blend them and set up the final
8734 // shuffle to place them.
8736 // The first two blend mask elements are for V1, the second two are for
8738 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8739 Mask[2] < 4 ? Mask[2] : Mask[3],
8740 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8741 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8742 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8743 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8745 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8748 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8749 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8750 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8751 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8754 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8755 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8758 /// \brief Lower 4-lane 32-bit floating point shuffles.
8760 /// Uses instructions exclusively from the floating point unit to minimize
8761 /// domain crossing penalties, as these are sufficient to implement all v4f32
8763 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8764 const X86Subtarget *Subtarget,
8765 SelectionDAG &DAG) {
8767 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8768 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8769 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8771 ArrayRef<int> Mask = SVOp->getMask();
8772 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8775 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8777 if (NumV2Elements == 0) {
8778 // Check for being able to broadcast a single element.
8779 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8780 Mask, Subtarget, DAG))
8783 // Use even/odd duplicate instructions for masks that match their pattern.
8784 if (Subtarget->hasSSE3()) {
8785 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8786 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8787 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8788 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8791 if (Subtarget->hasAVX()) {
8792 // If we have AVX, we can use VPERMILPS which will allow folding a load
8793 // into the shuffle.
8794 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8795 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8798 // Otherwise, use a straight shuffle of a single input vector. We pass the
8799 // input vector to both operands to simulate this with a SHUFPS.
8800 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8801 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8804 // There are special ways we can lower some single-element blends. However, we
8805 // have custom ways we can lower more complex single-element blends below that
8806 // we defer to if both this and BLENDPS fail to match, so restrict this to
8807 // when the V2 input is targeting element 0 of the mask -- that is the fast
8809 if (NumV2Elements == 1 && Mask[0] >= 4)
8810 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8811 Mask, Subtarget, DAG))
8814 if (Subtarget->hasSSE41()) {
8815 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8819 // Use INSERTPS if we can complete the shuffle efficiently.
8820 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8823 if (!isSingleSHUFPSMask(Mask))
8824 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8825 DL, MVT::v4f32, V1, V2, Mask, DAG))
8829 // Use dedicated unpack instructions for masks that match their pattern.
8831 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8834 // Otherwise fall back to a SHUFPS lowering strategy.
8835 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8838 /// \brief Lower 4-lane i32 vector shuffles.
8840 /// We try to handle these with integer-domain shuffles where we can, but for
8841 /// blends we use the floating point domain blend instructions.
8842 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8843 const X86Subtarget *Subtarget,
8844 SelectionDAG &DAG) {
8846 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8847 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8848 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8849 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8850 ArrayRef<int> Mask = SVOp->getMask();
8851 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8853 // Whenever we can lower this as a zext, that instruction is strictly faster
8854 // than any alternative. It also allows us to fold memory operands into the
8855 // shuffle in many cases.
8856 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8857 Mask, Subtarget, DAG))
8861 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8863 if (NumV2Elements == 0) {
8864 // Check for being able to broadcast a single element.
8865 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8866 Mask, Subtarget, DAG))
8869 // Straight shuffle of a single input vector. For everything from SSE2
8870 // onward this has a single fast instruction with no scary immediates.
8871 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8872 // but we aren't actually going to use the UNPCK instruction because doing
8873 // so prevents folding a load into this instruction or making a copy.
8874 const int UnpackLoMask[] = {0, 0, 1, 1};
8875 const int UnpackHiMask[] = {2, 2, 3, 3};
8876 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8877 Mask = UnpackLoMask;
8878 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8879 Mask = UnpackHiMask;
8881 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8882 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8885 // Try to use shift instructions.
8887 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8890 // There are special ways we can lower some single-element blends.
8891 if (NumV2Elements == 1)
8892 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8893 Mask, Subtarget, DAG))
8896 // We have different paths for blend lowering, but they all must use the
8897 // *exact* same predicate.
8898 bool IsBlendSupported = Subtarget->hasSSE41();
8899 if (IsBlendSupported)
8900 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8904 if (SDValue Masked =
8905 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8908 // Use dedicated unpack instructions for masks that match their pattern.
8910 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8913 // Try to use byte rotation instructions.
8914 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8915 if (Subtarget->hasSSSE3())
8916 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8917 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8920 // If we have direct support for blends, we should lower by decomposing into
8921 // a permute. That will be faster than the domain cross.
8922 if (IsBlendSupported)
8923 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8926 // Try to lower by permuting the inputs into an unpack instruction.
8927 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8931 // We implement this with SHUFPS because it can blend from two vectors.
8932 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8933 // up the inputs, bypassing domain shift penalties that we would encur if we
8934 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8936 return DAG.getBitcast(
8938 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8939 DAG.getBitcast(MVT::v4f32, V2), Mask));
8942 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8943 /// shuffle lowering, and the most complex part.
8945 /// The lowering strategy is to try to form pairs of input lanes which are
8946 /// targeted at the same half of the final vector, and then use a dword shuffle
8947 /// to place them onto the right half, and finally unpack the paired lanes into
8948 /// their final position.
8950 /// The exact breakdown of how to form these dword pairs and align them on the
8951 /// correct sides is really tricky. See the comments within the function for
8952 /// more of the details.
8954 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8955 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8956 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8957 /// vector, form the analogous 128-bit 8-element Mask.
8958 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8959 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8960 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8961 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8962 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8964 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8965 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8966 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8968 SmallVector<int, 4> LoInputs;
8969 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8970 [](int M) { return M >= 0; });
8971 std::sort(LoInputs.begin(), LoInputs.end());
8972 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8973 SmallVector<int, 4> HiInputs;
8974 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8975 [](int M) { return M >= 0; });
8976 std::sort(HiInputs.begin(), HiInputs.end());
8977 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8979 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8980 int NumHToL = LoInputs.size() - NumLToL;
8982 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8983 int NumHToH = HiInputs.size() - NumLToH;
8984 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8985 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8986 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8987 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8989 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8990 // such inputs we can swap two of the dwords across the half mark and end up
8991 // with <=2 inputs to each half in each half. Once there, we can fall through
8992 // to the generic code below. For example:
8994 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8995 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8997 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8998 // and an existing 2-into-2 on the other half. In this case we may have to
8999 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9000 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9001 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9002 // because any other situation (including a 3-into-1 or 1-into-3 in the other
9003 // half than the one we target for fixing) will be fixed when we re-enter this
9004 // path. We will also combine away any sequence of PSHUFD instructions that
9005 // result into a single instruction. Here is an example of the tricky case:
9007 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9008 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9010 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9012 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9013 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9015 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9016 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9018 // The result is fine to be handled by the generic logic.
9019 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9020 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9021 int AOffset, int BOffset) {
9022 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9023 "Must call this with A having 3 or 1 inputs from the A half.");
9024 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9025 "Must call this with B having 1 or 3 inputs from the B half.");
9026 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9027 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9029 bool ThreeAInputs = AToAInputs.size() == 3;
9031 // Compute the index of dword with only one word among the three inputs in
9032 // a half by taking the sum of the half with three inputs and subtracting
9033 // the sum of the actual three inputs. The difference is the remaining
9036 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9037 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9038 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9039 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9040 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9041 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9042 int TripleNonInputIdx =
9043 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9044 TripleDWord = TripleNonInputIdx / 2;
9046 // We use xor with one to compute the adjacent DWord to whichever one the
9048 OneInputDWord = (OneInput / 2) ^ 1;
9050 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9051 // and BToA inputs. If there is also such a problem with the BToB and AToB
9052 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9053 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9054 // is essential that we don't *create* a 3<-1 as then we might oscillate.
9055 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9056 // Compute how many inputs will be flipped by swapping these DWords. We
9058 // to balance this to ensure we don't form a 3-1 shuffle in the other
9060 int NumFlippedAToBInputs =
9061 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9062 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9063 int NumFlippedBToBInputs =
9064 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9065 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9066 if ((NumFlippedAToBInputs == 1 &&
9067 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9068 (NumFlippedBToBInputs == 1 &&
9069 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9070 // We choose whether to fix the A half or B half based on whether that
9071 // half has zero flipped inputs. At zero, we may not be able to fix it
9072 // with that half. We also bias towards fixing the B half because that
9073 // will more commonly be the high half, and we have to bias one way.
9074 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9075 ArrayRef<int> Inputs) {
9076 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9077 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9078 PinnedIdx ^ 1) != Inputs.end();
9079 // Determine whether the free index is in the flipped dword or the
9080 // unflipped dword based on where the pinned index is. We use this bit
9081 // in an xor to conditionally select the adjacent dword.
9082 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9083 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9084 FixFreeIdx) != Inputs.end();
9085 if (IsFixIdxInput == IsFixFreeIdxInput)
9087 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9088 FixFreeIdx) != Inputs.end();
9089 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9090 "We need to be changing the number of flipped inputs!");
9091 int PSHUFHalfMask[] = {0, 1, 2, 3};
9092 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9093 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9095 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9098 if (M != -1 && M == FixIdx)
9100 else if (M != -1 && M == FixFreeIdx)
9103 if (NumFlippedBToBInputs != 0) {
9105 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9106 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9108 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9109 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9110 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9115 int PSHUFDMask[] = {0, 1, 2, 3};
9116 PSHUFDMask[ADWord] = BDWord;
9117 PSHUFDMask[BDWord] = ADWord;
9120 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9121 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9123 // Adjust the mask to match the new locations of A and B.
9125 if (M != -1 && M/2 == ADWord)
9126 M = 2 * BDWord + M % 2;
9127 else if (M != -1 && M/2 == BDWord)
9128 M = 2 * ADWord + M % 2;
9130 // Recurse back into this routine to re-compute state now that this isn't
9131 // a 3 and 1 problem.
9132 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9135 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9136 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9137 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9138 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9140 // At this point there are at most two inputs to the low and high halves from
9141 // each half. That means the inputs can always be grouped into dwords and
9142 // those dwords can then be moved to the correct half with a dword shuffle.
9143 // We use at most one low and one high word shuffle to collect these paired
9144 // inputs into dwords, and finally a dword shuffle to place them.
9145 int PSHUFLMask[4] = {-1, -1, -1, -1};
9146 int PSHUFHMask[4] = {-1, -1, -1, -1};
9147 int PSHUFDMask[4] = {-1, -1, -1, -1};
9149 // First fix the masks for all the inputs that are staying in their
9150 // original halves. This will then dictate the targets of the cross-half
9152 auto fixInPlaceInputs =
9153 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9154 MutableArrayRef<int> SourceHalfMask,
9155 MutableArrayRef<int> HalfMask, int HalfOffset) {
9156 if (InPlaceInputs.empty())
9158 if (InPlaceInputs.size() == 1) {
9159 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9160 InPlaceInputs[0] - HalfOffset;
9161 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9164 if (IncomingInputs.empty()) {
9165 // Just fix all of the in place inputs.
9166 for (int Input : InPlaceInputs) {
9167 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9168 PSHUFDMask[Input / 2] = Input / 2;
9173 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9174 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9175 InPlaceInputs[0] - HalfOffset;
9176 // Put the second input next to the first so that they are packed into
9177 // a dword. We find the adjacent index by toggling the low bit.
9178 int AdjIndex = InPlaceInputs[0] ^ 1;
9179 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9180 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9181 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9183 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9184 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9186 // Now gather the cross-half inputs and place them into a free dword of
9187 // their target half.
9188 // FIXME: This operation could almost certainly be simplified dramatically to
9189 // look more like the 3-1 fixing operation.
9190 auto moveInputsToRightHalf = [&PSHUFDMask](
9191 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9192 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9193 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9195 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9196 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9198 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9200 int LowWord = Word & ~1;
9201 int HighWord = Word | 1;
9202 return isWordClobbered(SourceHalfMask, LowWord) ||
9203 isWordClobbered(SourceHalfMask, HighWord);
9206 if (IncomingInputs.empty())
9209 if (ExistingInputs.empty()) {
9210 // Map any dwords with inputs from them into the right half.
9211 for (int Input : IncomingInputs) {
9212 // If the source half mask maps over the inputs, turn those into
9213 // swaps and use the swapped lane.
9214 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9215 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9216 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9217 Input - SourceOffset;
9218 // We have to swap the uses in our half mask in one sweep.
9219 for (int &M : HalfMask)
9220 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9222 else if (M == Input)
9223 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9225 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9226 Input - SourceOffset &&
9227 "Previous placement doesn't match!");
9229 // Note that this correctly re-maps both when we do a swap and when
9230 // we observe the other side of the swap above. We rely on that to
9231 // avoid swapping the members of the input list directly.
9232 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9235 // Map the input's dword into the correct half.
9236 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9237 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9239 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9241 "Previous placement doesn't match!");
9244 // And just directly shift any other-half mask elements to be same-half
9245 // as we will have mirrored the dword containing the element into the
9246 // same position within that half.
9247 for (int &M : HalfMask)
9248 if (M >= SourceOffset && M < SourceOffset + 4) {
9249 M = M - SourceOffset + DestOffset;
9250 assert(M >= 0 && "This should never wrap below zero!");
9255 // Ensure we have the input in a viable dword of its current half. This
9256 // is particularly tricky because the original position may be clobbered
9257 // by inputs being moved and *staying* in that half.
9258 if (IncomingInputs.size() == 1) {
9259 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9260 int InputFixed = std::find(std::begin(SourceHalfMask),
9261 std::end(SourceHalfMask), -1) -
9262 std::begin(SourceHalfMask) + SourceOffset;
9263 SourceHalfMask[InputFixed - SourceOffset] =
9264 IncomingInputs[0] - SourceOffset;
9265 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9267 IncomingInputs[0] = InputFixed;
9269 } else if (IncomingInputs.size() == 2) {
9270 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9271 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9272 // We have two non-adjacent or clobbered inputs we need to extract from
9273 // the source half. To do this, we need to map them into some adjacent
9274 // dword slot in the source mask.
9275 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9276 IncomingInputs[1] - SourceOffset};
9278 // If there is a free slot in the source half mask adjacent to one of
9279 // the inputs, place the other input in it. We use (Index XOR 1) to
9280 // compute an adjacent index.
9281 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9282 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9283 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9284 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9285 InputsFixed[1] = InputsFixed[0] ^ 1;
9286 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9287 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9288 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9289 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9290 InputsFixed[0] = InputsFixed[1] ^ 1;
9291 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9292 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9293 // The two inputs are in the same DWord but it is clobbered and the
9294 // adjacent DWord isn't used at all. Move both inputs to the free
9296 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9297 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9298 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9299 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9301 // The only way we hit this point is if there is no clobbering
9302 // (because there are no off-half inputs to this half) and there is no
9303 // free slot adjacent to one of the inputs. In this case, we have to
9304 // swap an input with a non-input.
9305 for (int i = 0; i < 4; ++i)
9306 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9307 "We can't handle any clobbers here!");
9308 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9309 "Cannot have adjacent inputs here!");
9311 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9312 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9314 // We also have to update the final source mask in this case because
9315 // it may need to undo the above swap.
9316 for (int &M : FinalSourceHalfMask)
9317 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9318 M = InputsFixed[1] + SourceOffset;
9319 else if (M == InputsFixed[1] + SourceOffset)
9320 M = (InputsFixed[0] ^ 1) + SourceOffset;
9322 InputsFixed[1] = InputsFixed[0] ^ 1;
9325 // Point everything at the fixed inputs.
9326 for (int &M : HalfMask)
9327 if (M == IncomingInputs[0])
9328 M = InputsFixed[0] + SourceOffset;
9329 else if (M == IncomingInputs[1])
9330 M = InputsFixed[1] + SourceOffset;
9332 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9333 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9336 llvm_unreachable("Unhandled input size!");
9339 // Now hoist the DWord down to the right half.
9340 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9341 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9342 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9343 for (int &M : HalfMask)
9344 for (int Input : IncomingInputs)
9346 M = FreeDWord * 2 + Input % 2;
9348 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9349 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9350 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9351 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9353 // Now enact all the shuffles we've computed to move the inputs into their
9355 if (!isNoopShuffleMask(PSHUFLMask))
9356 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9357 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9358 if (!isNoopShuffleMask(PSHUFHMask))
9359 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9360 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9361 if (!isNoopShuffleMask(PSHUFDMask))
9364 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9365 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9367 // At this point, each half should contain all its inputs, and we can then
9368 // just shuffle them into their final position.
9369 assert(std::count_if(LoMask.begin(), LoMask.end(),
9370 [](int M) { return M >= 4; }) == 0 &&
9371 "Failed to lift all the high half inputs to the low mask!");
9372 assert(std::count_if(HiMask.begin(), HiMask.end(),
9373 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9374 "Failed to lift all the low half inputs to the high mask!");
9376 // Do a half shuffle for the low mask.
9377 if (!isNoopShuffleMask(LoMask))
9378 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9379 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9381 // Do a half shuffle with the high mask after shifting its values down.
9382 for (int &M : HiMask)
9385 if (!isNoopShuffleMask(HiMask))
9386 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9387 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9392 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9393 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9394 SDValue V2, ArrayRef<int> Mask,
9395 SelectionDAG &DAG, bool &V1InUse,
9397 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9403 int Size = Mask.size();
9404 int Scale = 16 / Size;
9405 for (int i = 0; i < 16; ++i) {
9406 if (Mask[i / Scale] == -1) {
9407 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9409 const int ZeroMask = 0x80;
9410 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9412 int V2Idx = Mask[i / Scale] < Size
9414 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9415 if (Zeroable[i / Scale])
9416 V1Idx = V2Idx = ZeroMask;
9417 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9418 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9419 V1InUse |= (ZeroMask != V1Idx);
9420 V2InUse |= (ZeroMask != V2Idx);
9425 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9426 DAG.getBitcast(MVT::v16i8, V1),
9427 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9429 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9430 DAG.getBitcast(MVT::v16i8, V2),
9431 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9433 // If we need shuffled inputs from both, blend the two.
9435 if (V1InUse && V2InUse)
9436 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9438 V = V1InUse ? V1 : V2;
9440 // Cast the result back to the correct type.
9441 return DAG.getBitcast(VT, V);
9444 /// \brief Generic lowering of 8-lane i16 shuffles.
9446 /// This handles both single-input shuffles and combined shuffle/blends with
9447 /// two inputs. The single input shuffles are immediately delegated to
9448 /// a dedicated lowering routine.
9450 /// The blends are lowered in one of three fundamental ways. If there are few
9451 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9452 /// of the input is significantly cheaper when lowered as an interleaving of
9453 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9454 /// halves of the inputs separately (making them have relatively few inputs)
9455 /// and then concatenate them.
9456 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9457 const X86Subtarget *Subtarget,
9458 SelectionDAG &DAG) {
9460 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9461 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9462 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9463 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9464 ArrayRef<int> OrigMask = SVOp->getMask();
9465 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9466 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9467 MutableArrayRef<int> Mask(MaskStorage);
9469 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9471 // Whenever we can lower this as a zext, that instruction is strictly faster
9472 // than any alternative.
9473 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9474 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9477 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9479 auto isV2 = [](int M) { return M >= 8; };
9481 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9483 if (NumV2Inputs == 0) {
9484 // Check for being able to broadcast a single element.
9485 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9486 Mask, Subtarget, DAG))
9489 // Try to use shift instructions.
9491 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9494 // Use dedicated unpack instructions for masks that match their pattern.
9496 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9499 // Try to use byte rotation instructions.
9500 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9501 Mask, Subtarget, DAG))
9504 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9508 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9509 "All single-input shuffles should be canonicalized to be V1-input "
9512 // Try to use shift instructions.
9514 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9517 // See if we can use SSE4A Extraction / Insertion.
9518 if (Subtarget->hasSSE4A())
9519 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9522 // There are special ways we can lower some single-element blends.
9523 if (NumV2Inputs == 1)
9524 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9525 Mask, Subtarget, DAG))
9528 // We have different paths for blend lowering, but they all must use the
9529 // *exact* same predicate.
9530 bool IsBlendSupported = Subtarget->hasSSE41();
9531 if (IsBlendSupported)
9532 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9536 if (SDValue Masked =
9537 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9540 // Use dedicated unpack instructions for masks that match their pattern.
9542 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9545 // Try to use byte rotation instructions.
9546 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9547 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9550 if (SDValue BitBlend =
9551 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9554 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9558 // If we can't directly blend but can use PSHUFB, that will be better as it
9559 // can both shuffle and set up the inefficient blend.
9560 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9561 bool V1InUse, V2InUse;
9562 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9566 // We can always bit-blend if we have to so the fallback strategy is to
9567 // decompose into single-input permutes and blends.
9568 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9572 /// \brief Check whether a compaction lowering can be done by dropping even
9573 /// elements and compute how many times even elements must be dropped.
9575 /// This handles shuffles which take every Nth element where N is a power of
9576 /// two. Example shuffle masks:
9578 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9579 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9580 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9581 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9582 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9583 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9585 /// Any of these lanes can of course be undef.
9587 /// This routine only supports N <= 3.
9588 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9591 /// \returns N above, or the number of times even elements must be dropped if
9592 /// there is such a number. Otherwise returns zero.
9593 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9594 // Figure out whether we're looping over two inputs or just one.
9595 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9597 // The modulus for the shuffle vector entries is based on whether this is
9598 // a single input or not.
9599 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9600 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9601 "We should only be called with masks with a power-of-2 size!");
9603 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9605 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9606 // and 2^3 simultaneously. This is because we may have ambiguity with
9607 // partially undef inputs.
9608 bool ViableForN[3] = {true, true, true};
9610 for (int i = 0, e = Mask.size(); i < e; ++i) {
9611 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9616 bool IsAnyViable = false;
9617 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9618 if (ViableForN[j]) {
9621 // The shuffle mask must be equal to (i * 2^N) % M.
9622 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9625 ViableForN[j] = false;
9627 // Early exit if we exhaust the possible powers of two.
9632 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9636 // Return 0 as there is no viable power of two.
9640 /// \brief Generic lowering of v16i8 shuffles.
9642 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9643 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9644 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9645 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9647 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9648 const X86Subtarget *Subtarget,
9649 SelectionDAG &DAG) {
9651 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9652 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9653 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9654 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9655 ArrayRef<int> Mask = SVOp->getMask();
9656 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9658 // Try to use shift instructions.
9660 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9663 // Try to use byte rotation instructions.
9664 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9665 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9668 // Try to use a zext lowering.
9669 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9670 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9673 // See if we can use SSE4A Extraction / Insertion.
9674 if (Subtarget->hasSSE4A())
9675 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9679 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9681 // For single-input shuffles, there are some nicer lowering tricks we can use.
9682 if (NumV2Elements == 0) {
9683 // Check for being able to broadcast a single element.
9684 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9685 Mask, Subtarget, DAG))
9688 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9689 // Notably, this handles splat and partial-splat shuffles more efficiently.
9690 // However, it only makes sense if the pre-duplication shuffle simplifies
9691 // things significantly. Currently, this means we need to be able to
9692 // express the pre-duplication shuffle as an i16 shuffle.
9694 // FIXME: We should check for other patterns which can be widened into an
9695 // i16 shuffle as well.
9696 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9697 for (int i = 0; i < 16; i += 2)
9698 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9703 auto tryToWidenViaDuplication = [&]() -> SDValue {
9704 if (!canWidenViaDuplication(Mask))
9706 SmallVector<int, 4> LoInputs;
9707 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9708 [](int M) { return M >= 0 && M < 8; });
9709 std::sort(LoInputs.begin(), LoInputs.end());
9710 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9712 SmallVector<int, 4> HiInputs;
9713 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9714 [](int M) { return M >= 8; });
9715 std::sort(HiInputs.begin(), HiInputs.end());
9716 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9719 bool TargetLo = LoInputs.size() >= HiInputs.size();
9720 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9721 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9723 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9724 SmallDenseMap<int, int, 8> LaneMap;
9725 for (int I : InPlaceInputs) {
9726 PreDupI16Shuffle[I/2] = I/2;
9729 int j = TargetLo ? 0 : 4, je = j + 4;
9730 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9731 // Check if j is already a shuffle of this input. This happens when
9732 // there are two adjacent bytes after we move the low one.
9733 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9734 // If we haven't yet mapped the input, search for a slot into which
9736 while (j < je && PreDupI16Shuffle[j] != -1)
9740 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9743 // Map this input with the i16 shuffle.
9744 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9747 // Update the lane map based on the mapping we ended up with.
9748 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9750 V1 = DAG.getBitcast(
9752 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9753 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9755 // Unpack the bytes to form the i16s that will be shuffled into place.
9756 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9757 MVT::v16i8, V1, V1);
9759 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9760 for (int i = 0; i < 16; ++i)
9761 if (Mask[i] != -1) {
9762 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9763 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9764 if (PostDupI16Shuffle[i / 2] == -1)
9765 PostDupI16Shuffle[i / 2] = MappedMask;
9767 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9768 "Conflicting entrties in the original shuffle!");
9770 return DAG.getBitcast(
9772 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9773 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9775 if (SDValue V = tryToWidenViaDuplication())
9779 if (SDValue Masked =
9780 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9783 // Use dedicated unpack instructions for masks that match their pattern.
9785 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9788 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9789 // with PSHUFB. It is important to do this before we attempt to generate any
9790 // blends but after all of the single-input lowerings. If the single input
9791 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9792 // want to preserve that and we can DAG combine any longer sequences into
9793 // a PSHUFB in the end. But once we start blending from multiple inputs,
9794 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9795 // and there are *very* few patterns that would actually be faster than the
9796 // PSHUFB approach because of its ability to zero lanes.
9798 // FIXME: The only exceptions to the above are blends which are exact
9799 // interleavings with direct instructions supporting them. We currently don't
9800 // handle those well here.
9801 if (Subtarget->hasSSSE3()) {
9802 bool V1InUse = false;
9803 bool V2InUse = false;
9805 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9806 DAG, V1InUse, V2InUse);
9808 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9809 // do so. This avoids using them to handle blends-with-zero which is
9810 // important as a single pshufb is significantly faster for that.
9811 if (V1InUse && V2InUse) {
9812 if (Subtarget->hasSSE41())
9813 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9814 Mask, Subtarget, DAG))
9817 // We can use an unpack to do the blending rather than an or in some
9818 // cases. Even though the or may be (very minorly) more efficient, we
9819 // preference this lowering because there are common cases where part of
9820 // the complexity of the shuffles goes away when we do the final blend as
9822 // FIXME: It might be worth trying to detect if the unpack-feeding
9823 // shuffles will both be pshufb, in which case we shouldn't bother with
9825 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9826 DL, MVT::v16i8, V1, V2, Mask, DAG))
9833 // There are special ways we can lower some single-element blends.
9834 if (NumV2Elements == 1)
9835 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9836 Mask, Subtarget, DAG))
9839 if (SDValue BitBlend =
9840 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9843 // Check whether a compaction lowering can be done. This handles shuffles
9844 // which take every Nth element for some even N. See the helper function for
9847 // We special case these as they can be particularly efficiently handled with
9848 // the PACKUSB instruction on x86 and they show up in common patterns of
9849 // rearranging bytes to truncate wide elements.
9850 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9851 // NumEvenDrops is the power of two stride of the elements. Another way of
9852 // thinking about it is that we need to drop the even elements this many
9853 // times to get the original input.
9854 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9856 // First we need to zero all the dropped bytes.
9857 assert(NumEvenDrops <= 3 &&
9858 "No support for dropping even elements more than 3 times.");
9859 // We use the mask type to pick which bytes are preserved based on how many
9860 // elements are dropped.
9861 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9862 SDValue ByteClearMask = DAG.getBitcast(
9863 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9864 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9866 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9868 // Now pack things back together.
9869 V1 = DAG.getBitcast(MVT::v8i16, V1);
9870 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9871 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9872 for (int i = 1; i < NumEvenDrops; ++i) {
9873 Result = DAG.getBitcast(MVT::v8i16, Result);
9874 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9880 // Handle multi-input cases by blending single-input shuffles.
9881 if (NumV2Elements > 0)
9882 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9885 // The fallback path for single-input shuffles widens this into two v8i16
9886 // vectors with unpacks, shuffles those, and then pulls them back together
9890 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9891 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9892 for (int i = 0; i < 16; ++i)
9894 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9896 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9898 SDValue VLoHalf, VHiHalf;
9899 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9900 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9902 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9903 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9904 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9905 [](int M) { return M >= 0 && M % 2 == 1; })) {
9906 // Use a mask to drop the high bytes.
9907 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9908 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9909 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9911 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9912 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9914 // Squash the masks to point directly into VLoHalf.
9915 for (int &M : LoBlendMask)
9918 for (int &M : HiBlendMask)
9922 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9923 // VHiHalf so that we can blend them as i16s.
9924 VLoHalf = DAG.getBitcast(
9925 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9926 VHiHalf = DAG.getBitcast(
9927 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9930 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9931 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9933 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9936 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9938 /// This routine breaks down the specific type of 128-bit shuffle and
9939 /// dispatches to the lowering routines accordingly.
9940 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9941 MVT VT, const X86Subtarget *Subtarget,
9942 SelectionDAG &DAG) {
9943 switch (VT.SimpleTy) {
9945 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9947 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9949 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9951 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9953 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9955 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9958 llvm_unreachable("Unimplemented!");
9962 /// \brief Helper function to test whether a shuffle mask could be
9963 /// simplified by widening the elements being shuffled.
9965 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9966 /// leaves it in an unspecified state.
9968 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9969 /// shuffle masks. The latter have the special property of a '-2' representing
9970 /// a zero-ed lane of a vector.
9971 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9972 SmallVectorImpl<int> &WidenedMask) {
9973 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9974 // If both elements are undef, its trivial.
9975 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9976 WidenedMask.push_back(SM_SentinelUndef);
9980 // Check for an undef mask and a mask value properly aligned to fit with
9981 // a pair of values. If we find such a case, use the non-undef mask's value.
9982 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9983 WidenedMask.push_back(Mask[i + 1] / 2);
9986 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9987 WidenedMask.push_back(Mask[i] / 2);
9991 // When zeroing, we need to spread the zeroing across both lanes to widen.
9992 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9993 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9994 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9995 WidenedMask.push_back(SM_SentinelZero);
10001 // Finally check if the two mask values are adjacent and aligned with
10003 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10004 WidenedMask.push_back(Mask[i] / 2);
10008 // Otherwise we can't safely widen the elements used in this shuffle.
10011 assert(WidenedMask.size() == Mask.size() / 2 &&
10012 "Incorrect size of mask after widening the elements!");
10017 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10019 /// This routine just extracts two subvectors, shuffles them independently, and
10020 /// then concatenates them back together. This should work effectively with all
10021 /// AVX vector shuffle types.
10022 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10023 SDValue V2, ArrayRef<int> Mask,
10024 SelectionDAG &DAG) {
10025 assert(VT.getSizeInBits() >= 256 &&
10026 "Only for 256-bit or wider vector shuffles!");
10027 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10028 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10030 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10031 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10033 int NumElements = VT.getVectorNumElements();
10034 int SplitNumElements = NumElements / 2;
10035 MVT ScalarVT = VT.getVectorElementType();
10036 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10038 // Rather than splitting build-vectors, just build two narrower build
10039 // vectors. This helps shuffling with splats and zeros.
10040 auto SplitVector = [&](SDValue V) {
10041 while (V.getOpcode() == ISD::BITCAST)
10042 V = V->getOperand(0);
10044 MVT OrigVT = V.getSimpleValueType();
10045 int OrigNumElements = OrigVT.getVectorNumElements();
10046 int OrigSplitNumElements = OrigNumElements / 2;
10047 MVT OrigScalarVT = OrigVT.getVectorElementType();
10048 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10052 auto *BV = dyn_cast<BuildVectorSDNode>(V);
10054 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10055 DAG.getIntPtrConstant(0, DL));
10056 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10057 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10060 SmallVector<SDValue, 16> LoOps, HiOps;
10061 for (int i = 0; i < OrigSplitNumElements; ++i) {
10062 LoOps.push_back(BV->getOperand(i));
10063 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10065 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10066 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10068 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10069 DAG.getBitcast(SplitVT, HiV));
10072 SDValue LoV1, HiV1, LoV2, HiV2;
10073 std::tie(LoV1, HiV1) = SplitVector(V1);
10074 std::tie(LoV2, HiV2) = SplitVector(V2);
10076 // Now create two 4-way blends of these half-width vectors.
10077 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10078 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10079 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10080 for (int i = 0; i < SplitNumElements; ++i) {
10081 int M = HalfMask[i];
10082 if (M >= NumElements) {
10083 if (M >= NumElements + SplitNumElements)
10087 V2BlendMask.push_back(M - NumElements);
10088 V1BlendMask.push_back(-1);
10089 BlendMask.push_back(SplitNumElements + i);
10090 } else if (M >= 0) {
10091 if (M >= SplitNumElements)
10095 V2BlendMask.push_back(-1);
10096 V1BlendMask.push_back(M);
10097 BlendMask.push_back(i);
10099 V2BlendMask.push_back(-1);
10100 V1BlendMask.push_back(-1);
10101 BlendMask.push_back(-1);
10105 // Because the lowering happens after all combining takes place, we need to
10106 // manually combine these blend masks as much as possible so that we create
10107 // a minimal number of high-level vector shuffle nodes.
10109 // First try just blending the halves of V1 or V2.
10110 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10111 return DAG.getUNDEF(SplitVT);
10112 if (!UseLoV2 && !UseHiV2)
10113 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10114 if (!UseLoV1 && !UseHiV1)
10115 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10117 SDValue V1Blend, V2Blend;
10118 if (UseLoV1 && UseHiV1) {
10120 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10122 // We only use half of V1 so map the usage down into the final blend mask.
10123 V1Blend = UseLoV1 ? LoV1 : HiV1;
10124 for (int i = 0; i < SplitNumElements; ++i)
10125 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10126 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10128 if (UseLoV2 && UseHiV2) {
10130 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10132 // We only use half of V2 so map the usage down into the final blend mask.
10133 V2Blend = UseLoV2 ? LoV2 : HiV2;
10134 for (int i = 0; i < SplitNumElements; ++i)
10135 if (BlendMask[i] >= SplitNumElements)
10136 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10138 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10140 SDValue Lo = HalfBlend(LoMask);
10141 SDValue Hi = HalfBlend(HiMask);
10142 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10145 /// \brief Either split a vector in halves or decompose the shuffles and the
10148 /// This is provided as a good fallback for many lowerings of non-single-input
10149 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10150 /// between splitting the shuffle into 128-bit components and stitching those
10151 /// back together vs. extracting the single-input shuffles and blending those
10153 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10154 SDValue V2, ArrayRef<int> Mask,
10155 SelectionDAG &DAG) {
10156 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10157 "lower single-input shuffles as it "
10158 "could then recurse on itself.");
10159 int Size = Mask.size();
10161 // If this can be modeled as a broadcast of two elements followed by a blend,
10162 // prefer that lowering. This is especially important because broadcasts can
10163 // often fold with memory operands.
10164 auto DoBothBroadcast = [&] {
10165 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10168 if (V2BroadcastIdx == -1)
10169 V2BroadcastIdx = M - Size;
10170 else if (M - Size != V2BroadcastIdx)
10172 } else if (M >= 0) {
10173 if (V1BroadcastIdx == -1)
10174 V1BroadcastIdx = M;
10175 else if (M != V1BroadcastIdx)
10180 if (DoBothBroadcast())
10181 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10184 // If the inputs all stem from a single 128-bit lane of each input, then we
10185 // split them rather than blending because the split will decompose to
10186 // unusually few instructions.
10187 int LaneCount = VT.getSizeInBits() / 128;
10188 int LaneSize = Size / LaneCount;
10189 SmallBitVector LaneInputs[2];
10190 LaneInputs[0].resize(LaneCount, false);
10191 LaneInputs[1].resize(LaneCount, false);
10192 for (int i = 0; i < Size; ++i)
10194 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10195 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10196 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10198 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10199 // that the decomposed single-input shuffles don't end up here.
10200 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10203 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10204 /// a permutation and blend of those lanes.
10206 /// This essentially blends the out-of-lane inputs to each lane into the lane
10207 /// from a permuted copy of the vector. This lowering strategy results in four
10208 /// instructions in the worst case for a single-input cross lane shuffle which
10209 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10210 /// of. Special cases for each particular shuffle pattern should be handled
10211 /// prior to trying this lowering.
10212 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10213 SDValue V1, SDValue V2,
10214 ArrayRef<int> Mask,
10215 SelectionDAG &DAG) {
10216 // FIXME: This should probably be generalized for 512-bit vectors as well.
10217 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10218 int LaneSize = Mask.size() / 2;
10220 // If there are only inputs from one 128-bit lane, splitting will in fact be
10221 // less expensive. The flags track whether the given lane contains an element
10222 // that crosses to another lane.
10223 bool LaneCrossing[2] = {false, false};
10224 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10225 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10226 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10227 if (!LaneCrossing[0] || !LaneCrossing[1])
10228 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10230 if (isSingleInputShuffleMask(Mask)) {
10231 SmallVector<int, 32> FlippedBlendMask;
10232 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10233 FlippedBlendMask.push_back(
10234 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10236 : Mask[i] % LaneSize +
10237 (i / LaneSize) * LaneSize + Size));
10239 // Flip the vector, and blend the results which should now be in-lane. The
10240 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10241 // 5 for the high source. The value 3 selects the high half of source 2 and
10242 // the value 2 selects the low half of source 2. We only use source 2 to
10243 // allow folding it into a memory operand.
10244 unsigned PERMMask = 3 | 2 << 4;
10245 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10246 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10247 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10250 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10251 // will be handled by the above logic and a blend of the results, much like
10252 // other patterns in AVX.
10253 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10256 /// \brief Handle lowering 2-lane 128-bit shuffles.
10257 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10258 SDValue V2, ArrayRef<int> Mask,
10259 const X86Subtarget *Subtarget,
10260 SelectionDAG &DAG) {
10261 // TODO: If minimizing size and one of the inputs is a zero vector and the
10262 // the zero vector has only one use, we could use a VPERM2X128 to save the
10263 // instruction bytes needed to explicitly generate the zero vector.
10265 // Blends are faster and handle all the non-lane-crossing cases.
10266 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10270 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10271 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10273 // If either input operand is a zero vector, use VPERM2X128 because its mask
10274 // allows us to replace the zero input with an implicit zero.
10275 if (!IsV1Zero && !IsV2Zero) {
10276 // Check for patterns which can be matched with a single insert of a 128-bit
10278 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10279 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10280 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10281 VT.getVectorNumElements() / 2);
10282 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10283 DAG.getIntPtrConstant(0, DL));
10284 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10285 OnlyUsesV1 ? V1 : V2,
10286 DAG.getIntPtrConstant(0, DL));
10287 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10291 // Otherwise form a 128-bit permutation. After accounting for undefs,
10292 // convert the 64-bit shuffle mask selection values into 128-bit
10293 // selection bits by dividing the indexes by 2 and shifting into positions
10294 // defined by a vperm2*128 instruction's immediate control byte.
10296 // The immediate permute control byte looks like this:
10297 // [1:0] - select 128 bits from sources for low half of destination
10299 // [3] - zero low half of destination
10300 // [5:4] - select 128 bits from sources for high half of destination
10302 // [7] - zero high half of destination
10304 int MaskLO = Mask[0];
10305 if (MaskLO == SM_SentinelUndef)
10306 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10308 int MaskHI = Mask[2];
10309 if (MaskHI == SM_SentinelUndef)
10310 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10312 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10314 // If either input is a zero vector, replace it with an undef input.
10315 // Shuffle mask values < 4 are selecting elements of V1.
10316 // Shuffle mask values >= 4 are selecting elements of V2.
10317 // Adjust each half of the permute mask by clearing the half that was
10318 // selecting the zero vector and setting the zero mask bit.
10320 V1 = DAG.getUNDEF(VT);
10322 PermMask = (PermMask & 0xf0) | 0x08;
10324 PermMask = (PermMask & 0x0f) | 0x80;
10327 V2 = DAG.getUNDEF(VT);
10329 PermMask = (PermMask & 0xf0) | 0x08;
10331 PermMask = (PermMask & 0x0f) | 0x80;
10334 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10335 DAG.getConstant(PermMask, DL, MVT::i8));
10338 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10339 /// shuffling each lane.
10341 /// This will only succeed when the result of fixing the 128-bit lanes results
10342 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10343 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10344 /// the lane crosses early and then use simpler shuffles within each lane.
10346 /// FIXME: It might be worthwhile at some point to support this without
10347 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10348 /// in x86 only floating point has interesting non-repeating shuffles, and even
10349 /// those are still *marginally* more expensive.
10350 static SDValue lowerVectorShuffleByMerging128BitLanes(
10351 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10352 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10353 assert(!isSingleInputShuffleMask(Mask) &&
10354 "This is only useful with multiple inputs.");
10356 int Size = Mask.size();
10357 int LaneSize = 128 / VT.getScalarSizeInBits();
10358 int NumLanes = Size / LaneSize;
10359 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10361 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10362 // check whether the in-128-bit lane shuffles share a repeating pattern.
10363 SmallVector<int, 4> Lanes;
10364 Lanes.resize(NumLanes, -1);
10365 SmallVector<int, 4> InLaneMask;
10366 InLaneMask.resize(LaneSize, -1);
10367 for (int i = 0; i < Size; ++i) {
10371 int j = i / LaneSize;
10373 if (Lanes[j] < 0) {
10374 // First entry we've seen for this lane.
10375 Lanes[j] = Mask[i] / LaneSize;
10376 } else if (Lanes[j] != Mask[i] / LaneSize) {
10377 // This doesn't match the lane selected previously!
10381 // Check that within each lane we have a consistent shuffle mask.
10382 int k = i % LaneSize;
10383 if (InLaneMask[k] < 0) {
10384 InLaneMask[k] = Mask[i] % LaneSize;
10385 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10386 // This doesn't fit a repeating in-lane mask.
10391 // First shuffle the lanes into place.
10392 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10393 VT.getSizeInBits() / 64);
10394 SmallVector<int, 8> LaneMask;
10395 LaneMask.resize(NumLanes * 2, -1);
10396 for (int i = 0; i < NumLanes; ++i)
10397 if (Lanes[i] >= 0) {
10398 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10399 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10402 V1 = DAG.getBitcast(LaneVT, V1);
10403 V2 = DAG.getBitcast(LaneVT, V2);
10404 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10406 // Cast it back to the type we actually want.
10407 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10409 // Now do a simple shuffle that isn't lane crossing.
10410 SmallVector<int, 8> NewMask;
10411 NewMask.resize(Size, -1);
10412 for (int i = 0; i < Size; ++i)
10414 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10415 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10416 "Must not introduce lane crosses at this point!");
10418 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10421 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10422 /// This allows for fast cases such as subvector extraction/insertion
10423 /// or shuffling smaller vector types which can lower more efficiently.
10424 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10425 SDValue V2, ArrayRef<int> Mask,
10426 const X86Subtarget *Subtarget,
10427 SelectionDAG &DAG) {
10428 assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10430 unsigned NumElts = VT.getVectorNumElements();
10431 unsigned HalfNumElts = NumElts / 2;
10432 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10434 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10435 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10436 if (!UndefLower && !UndefUpper)
10439 // Upper half is undef and lower half is whole upper subvector.
10440 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10442 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10443 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10444 DAG.getIntPtrConstant(HalfNumElts, DL));
10445 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10446 DAG.getIntPtrConstant(0, DL));
10449 // Lower half is undef and upper half is whole lower subvector.
10450 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10452 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10453 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10454 DAG.getIntPtrConstant(0, DL));
10455 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10456 DAG.getIntPtrConstant(HalfNumElts, DL));
10459 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10460 if (UndefLower && Subtarget->hasAVX2() &&
10461 (VT == MVT::v4f64 || VT == MVT::v4i64))
10464 // If the shuffle only uses the lower halves of the input operands,
10465 // then extract them and perform the 'half' shuffle at half width.
10466 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10467 int HalfIdx1 = -1, HalfIdx2 = -1;
10468 SmallVector<int, 8> HalfMask;
10469 unsigned Offset = UndefLower ? HalfNumElts : 0;
10470 for (unsigned i = 0; i != HalfNumElts; ++i) {
10471 int M = Mask[i + Offset];
10473 HalfMask.push_back(M);
10477 // Determine which of the 4 half vectors this element is from.
10478 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10479 int HalfIdx = M / HalfNumElts;
10481 // Only shuffle using the lower halves of the inputs.
10482 // TODO: Investigate usefulness of shuffling with upper halves.
10483 if (HalfIdx != 0 && HalfIdx != 2)
10486 // Determine the element index into its half vector source.
10487 int HalfElt = M % HalfNumElts;
10489 // We can shuffle with up to 2 half vectors, set the new 'half'
10490 // shuffle mask accordingly.
10491 if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10492 HalfMask.push_back(HalfElt);
10493 HalfIdx1 = HalfIdx;
10496 if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10497 HalfMask.push_back(HalfElt + HalfNumElts);
10498 HalfIdx2 = HalfIdx;
10502 // Too many half vectors referenced.
10505 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10507 auto GetHalfVector = [&](int HalfIdx) {
10509 return DAG.getUNDEF(HalfVT);
10510 SDValue V = (HalfIdx < 2 ? V1 : V2);
10511 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10512 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10513 DAG.getIntPtrConstant(HalfIdx, DL));
10516 SDValue Half1 = GetHalfVector(HalfIdx1);
10517 SDValue Half2 = GetHalfVector(HalfIdx2);
10518 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10519 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10520 DAG.getIntPtrConstant(Offset, DL));
10523 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10526 /// This returns true if the elements from a particular input are already in the
10527 /// slot required by the given mask and require no permutation.
10528 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10529 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10530 int Size = Mask.size();
10531 for (int i = 0; i < Size; ++i)
10532 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10538 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10539 ArrayRef<int> Mask, SDValue V1,
10540 SDValue V2, SelectionDAG &DAG) {
10542 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10543 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10544 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10545 int NumElts = VT.getVectorNumElements();
10546 bool ShufpdMask = true;
10547 bool CommutableMask = true;
10548 unsigned Immediate = 0;
10549 for (int i = 0; i < NumElts; ++i) {
10552 int Val = (i & 6) + NumElts * (i & 1);
10553 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10554 if (Mask[i] < Val || Mask[i] > Val + 1)
10555 ShufpdMask = false;
10556 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10557 CommutableMask = false;
10558 Immediate |= (Mask[i] % 2) << i;
10561 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10562 DAG.getConstant(Immediate, DL, MVT::i8));
10563 if (CommutableMask)
10564 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10565 DAG.getConstant(Immediate, DL, MVT::i8));
10569 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10571 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10572 /// isn't available.
10573 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10574 const X86Subtarget *Subtarget,
10575 SelectionDAG &DAG) {
10577 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10578 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10579 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580 ArrayRef<int> Mask = SVOp->getMask();
10581 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10583 SmallVector<int, 4> WidenedMask;
10584 if (canWidenShuffleElements(Mask, WidenedMask))
10585 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10588 if (isSingleInputShuffleMask(Mask)) {
10589 // Check for being able to broadcast a single element.
10590 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10591 Mask, Subtarget, DAG))
10594 // Use low duplicate instructions for masks that match their pattern.
10595 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10596 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10598 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10599 // Non-half-crossing single input shuffles can be lowerid with an
10600 // interleaved permutation.
10601 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10602 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10603 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10604 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10607 // With AVX2 we have direct support for this permutation.
10608 if (Subtarget->hasAVX2())
10609 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10610 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10612 // Otherwise, fall back.
10613 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10617 // Use dedicated unpack instructions for masks that match their pattern.
10619 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10622 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10626 // Check if the blend happens to exactly fit that of SHUFPD.
10628 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10631 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10632 // shuffle. However, if we have AVX2 and either inputs are already in place,
10633 // we will be able to shuffle even across lanes the other input in a single
10634 // instruction so skip this pattern.
10635 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10636 isShuffleMaskInputInPlace(1, Mask))))
10637 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10638 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10641 // If we have AVX2 then we always want to lower with a blend because an v4 we
10642 // can fully permute the elements.
10643 if (Subtarget->hasAVX2())
10644 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10647 // Otherwise fall back on generic lowering.
10648 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10651 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10653 /// This routine is only called when we have AVX2 and thus a reasonable
10654 /// instruction set for v4i64 shuffling..
10655 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10656 const X86Subtarget *Subtarget,
10657 SelectionDAG &DAG) {
10659 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10660 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10661 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10662 ArrayRef<int> Mask = SVOp->getMask();
10663 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10664 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10666 SmallVector<int, 4> WidenedMask;
10667 if (canWidenShuffleElements(Mask, WidenedMask))
10668 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10671 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10675 // Check for being able to broadcast a single element.
10676 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10677 Mask, Subtarget, DAG))
10680 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10681 // use lower latency instructions that will operate on both 128-bit lanes.
10682 SmallVector<int, 2> RepeatedMask;
10683 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10684 if (isSingleInputShuffleMask(Mask)) {
10685 int PSHUFDMask[] = {-1, -1, -1, -1};
10686 for (int i = 0; i < 2; ++i)
10687 if (RepeatedMask[i] >= 0) {
10688 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10689 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10691 return DAG.getBitcast(
10693 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10694 DAG.getBitcast(MVT::v8i32, V1),
10695 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10699 // AVX2 provides a direct instruction for permuting a single input across
10701 if (isSingleInputShuffleMask(Mask))
10702 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10703 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10705 // Try to use shift instructions.
10706 if (SDValue Shift =
10707 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10710 // Use dedicated unpack instructions for masks that match their pattern.
10712 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10715 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10716 // shuffle. However, if we have AVX2 and either inputs are already in place,
10717 // we will be able to shuffle even across lanes the other input in a single
10718 // instruction so skip this pattern.
10719 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10720 isShuffleMaskInputInPlace(1, Mask))))
10721 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10722 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10725 // Otherwise fall back on generic blend lowering.
10726 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10730 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10732 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10733 /// isn't available.
10734 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10735 const X86Subtarget *Subtarget,
10736 SelectionDAG &DAG) {
10738 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10739 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10740 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10741 ArrayRef<int> Mask = SVOp->getMask();
10742 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10744 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10748 // Check for being able to broadcast a single element.
10749 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10750 Mask, Subtarget, DAG))
10753 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10754 // options to efficiently lower the shuffle.
10755 SmallVector<int, 4> RepeatedMask;
10756 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10757 assert(RepeatedMask.size() == 4 &&
10758 "Repeated masks must be half the mask width!");
10760 // Use even/odd duplicate instructions for masks that match their pattern.
10761 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10762 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10763 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10764 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10766 if (isSingleInputShuffleMask(Mask))
10767 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10768 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10770 // Use dedicated unpack instructions for masks that match their pattern.
10772 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10775 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10776 // have already handled any direct blends. We also need to squash the
10777 // repeated mask into a simulated v4f32 mask.
10778 for (int i = 0; i < 4; ++i)
10779 if (RepeatedMask[i] >= 8)
10780 RepeatedMask[i] -= 4;
10781 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10784 // If we have a single input shuffle with different shuffle patterns in the
10785 // two 128-bit lanes use the variable mask to VPERMILPS.
10786 if (isSingleInputShuffleMask(Mask)) {
10787 SDValue VPermMask[8];
10788 for (int i = 0; i < 8; ++i)
10789 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10790 : DAG.getConstant(Mask[i], DL, MVT::i32);
10791 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10792 return DAG.getNode(
10793 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10794 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10796 if (Subtarget->hasAVX2())
10797 return DAG.getNode(
10798 X86ISD::VPERMV, DL, MVT::v8f32,
10799 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10801 // Otherwise, fall back.
10802 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10806 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10808 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10809 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10812 // If we have AVX2 then we always want to lower with a blend because at v8 we
10813 // can fully permute the elements.
10814 if (Subtarget->hasAVX2())
10815 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10818 // Otherwise fall back on generic lowering.
10819 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10822 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10824 /// This routine is only called when we have AVX2 and thus a reasonable
10825 /// instruction set for v8i32 shuffling..
10826 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10827 const X86Subtarget *Subtarget,
10828 SelectionDAG &DAG) {
10830 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10831 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10833 ArrayRef<int> Mask = SVOp->getMask();
10834 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10835 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10837 // Whenever we can lower this as a zext, that instruction is strictly faster
10838 // than any alternative. It also allows us to fold memory operands into the
10839 // shuffle in many cases.
10840 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10841 Mask, Subtarget, DAG))
10844 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10848 // Check for being able to broadcast a single element.
10849 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10850 Mask, Subtarget, DAG))
10853 // If the shuffle mask is repeated in each 128-bit lane we can use more
10854 // efficient instructions that mirror the shuffles across the two 128-bit
10856 SmallVector<int, 4> RepeatedMask;
10857 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10858 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10859 if (isSingleInputShuffleMask(Mask))
10860 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10861 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10863 // Use dedicated unpack instructions for masks that match their pattern.
10865 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10869 // Try to use shift instructions.
10870 if (SDValue Shift =
10871 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10874 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10875 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10878 // If the shuffle patterns aren't repeated but it is a single input, directly
10879 // generate a cross-lane VPERMD instruction.
10880 if (isSingleInputShuffleMask(Mask)) {
10881 SDValue VPermMask[8];
10882 for (int i = 0; i < 8; ++i)
10883 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10884 : DAG.getConstant(Mask[i], DL, MVT::i32);
10885 return DAG.getNode(
10886 X86ISD::VPERMV, DL, MVT::v8i32,
10887 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10890 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10892 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10893 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10896 // Otherwise fall back on generic blend lowering.
10897 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10901 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10903 /// This routine is only called when we have AVX2 and thus a reasonable
10904 /// instruction set for v16i16 shuffling..
10905 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10906 const X86Subtarget *Subtarget,
10907 SelectionDAG &DAG) {
10909 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10910 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10911 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10912 ArrayRef<int> Mask = SVOp->getMask();
10913 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10914 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10916 // Whenever we can lower this as a zext, that instruction is strictly faster
10917 // than any alternative. It also allows us to fold memory operands into the
10918 // shuffle in many cases.
10919 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10920 Mask, Subtarget, DAG))
10923 // Check for being able to broadcast a single element.
10924 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10925 Mask, Subtarget, DAG))
10928 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10932 // Use dedicated unpack instructions for masks that match their pattern.
10934 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10937 // Try to use shift instructions.
10938 if (SDValue Shift =
10939 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10942 // Try to use byte rotation instructions.
10943 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10944 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10947 if (isSingleInputShuffleMask(Mask)) {
10948 // There are no generalized cross-lane shuffle operations available on i16
10950 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10951 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10954 SmallVector<int, 8> RepeatedMask;
10955 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10956 // As this is a single-input shuffle, the repeated mask should be
10957 // a strictly valid v8i16 mask that we can pass through to the v8i16
10958 // lowering to handle even the v16 case.
10959 return lowerV8I16GeneralSingleInputVectorShuffle(
10960 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10963 SDValue PSHUFBMask[32];
10964 for (int i = 0; i < 16; ++i) {
10965 if (Mask[i] == -1) {
10966 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10970 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10971 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10972 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10973 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10975 return DAG.getBitcast(MVT::v16i16,
10976 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10977 DAG.getBitcast(MVT::v32i8, V1),
10978 DAG.getNode(ISD::BUILD_VECTOR, DL,
10979 MVT::v32i8, PSHUFBMask)));
10982 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10984 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10985 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10988 // Otherwise fall back on generic lowering.
10989 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10992 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10994 /// This routine is only called when we have AVX2 and thus a reasonable
10995 /// instruction set for v32i8 shuffling..
10996 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10997 const X86Subtarget *Subtarget,
10998 SelectionDAG &DAG) {
11000 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11001 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11002 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11003 ArrayRef<int> Mask = SVOp->getMask();
11004 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11005 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
11007 // Whenever we can lower this as a zext, that instruction is strictly faster
11008 // than any alternative. It also allows us to fold memory operands into the
11009 // shuffle in many cases.
11010 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11011 Mask, Subtarget, DAG))
11014 // Check for being able to broadcast a single element.
11015 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
11016 Mask, Subtarget, DAG))
11019 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11023 // Use dedicated unpack instructions for masks that match their pattern.
11025 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11028 // Try to use shift instructions.
11029 if (SDValue Shift =
11030 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
11033 // Try to use byte rotation instructions.
11034 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11035 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11038 if (isSingleInputShuffleMask(Mask)) {
11039 // There are no generalized cross-lane shuffle operations available on i8
11041 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11042 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11045 SDValue PSHUFBMask[32];
11046 for (int i = 0; i < 32; ++i)
11049 ? DAG.getUNDEF(MVT::i8)
11050 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11053 return DAG.getNode(
11054 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11055 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11058 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11060 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11061 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11064 // Otherwise fall back on generic lowering.
11065 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11068 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11070 /// This routine either breaks down the specific type of a 256-bit x86 vector
11071 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11072 /// together based on the available instructions.
11073 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11074 MVT VT, const X86Subtarget *Subtarget,
11075 SelectionDAG &DAG) {
11077 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11078 ArrayRef<int> Mask = SVOp->getMask();
11080 // If we have a single input to the zero element, insert that into V1 if we
11081 // can do so cheaply.
11082 int NumElts = VT.getVectorNumElements();
11083 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11084 return M >= NumElts;
11087 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11088 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11089 DL, VT, V1, V2, Mask, Subtarget, DAG))
11092 // Handle special cases where the lower or upper half is UNDEF.
11094 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11097 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11098 // can check for those subtargets here and avoid much of the subtarget
11099 // querying in the per-vector-type lowering routines. With AVX1 we have
11100 // essentially *zero* ability to manipulate a 256-bit vector with integer
11101 // types. Since we'll use floating point types there eventually, just
11102 // immediately cast everything to a float and operate entirely in that domain.
11103 if (VT.isInteger() && !Subtarget->hasAVX2()) {
11104 int ElementBits = VT.getScalarSizeInBits();
11105 if (ElementBits < 32)
11106 // No floating point type available, decompose into 128-bit vectors.
11107 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11109 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11110 VT.getVectorNumElements());
11111 V1 = DAG.getBitcast(FpVT, V1);
11112 V2 = DAG.getBitcast(FpVT, V2);
11113 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11116 switch (VT.SimpleTy) {
11118 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11120 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11122 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11124 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11126 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11128 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11131 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11135 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11136 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11137 ArrayRef<int> Mask,
11138 SDValue V1, SDValue V2,
11139 SelectionDAG &DAG) {
11140 assert(VT.getScalarSizeInBits() == 64 &&
11141 "Unexpected element type size for 128bit shuffle.");
11143 // To handle 256 bit vector requires VLX and most probably
11144 // function lowerV2X128VectorShuffle() is better solution.
11145 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11147 SmallVector<int, 4> WidenedMask;
11148 if (!canWidenShuffleElements(Mask, WidenedMask))
11151 // Form a 128-bit permutation.
11152 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11153 // bits defined by a vshuf64x2 instruction's immediate control byte.
11154 unsigned PermMask = 0, Imm = 0;
11155 unsigned ControlBitsNum = WidenedMask.size() / 2;
11157 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11158 if (WidenedMask[i] == SM_SentinelZero)
11161 // Use first element in place of undef mask.
11162 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11163 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11166 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11167 DAG.getConstant(PermMask, DL, MVT::i8));
11170 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11171 ArrayRef<int> Mask, SDValue V1,
11172 SDValue V2, SelectionDAG &DAG) {
11174 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11176 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11177 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11179 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11180 if (isSingleInputShuffleMask(Mask))
11181 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11183 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11186 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11187 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11188 const X86Subtarget *Subtarget,
11189 SelectionDAG &DAG) {
11191 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11192 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11193 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11194 ArrayRef<int> Mask = SVOp->getMask();
11195 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11197 if (SDValue Shuf128 =
11198 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11201 if (SDValue Unpck =
11202 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11205 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11208 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11209 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11210 const X86Subtarget *Subtarget,
11211 SelectionDAG &DAG) {
11213 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11214 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11215 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11216 ArrayRef<int> Mask = SVOp->getMask();
11217 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11219 if (SDValue Unpck =
11220 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11223 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11226 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11227 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11228 const X86Subtarget *Subtarget,
11229 SelectionDAG &DAG) {
11231 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11232 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11233 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11234 ArrayRef<int> Mask = SVOp->getMask();
11235 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11237 if (SDValue Shuf128 =
11238 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11241 if (SDValue Unpck =
11242 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11245 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11248 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11249 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11250 const X86Subtarget *Subtarget,
11251 SelectionDAG &DAG) {
11253 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11254 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11255 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11256 ArrayRef<int> Mask = SVOp->getMask();
11257 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11259 if (SDValue Unpck =
11260 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11263 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11266 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11267 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11268 const X86Subtarget *Subtarget,
11269 SelectionDAG &DAG) {
11271 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11272 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11274 ArrayRef<int> Mask = SVOp->getMask();
11275 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11276 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11278 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11281 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11282 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11283 const X86Subtarget *Subtarget,
11284 SelectionDAG &DAG) {
11286 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11287 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11288 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11289 ArrayRef<int> Mask = SVOp->getMask();
11290 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11291 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11293 // FIXME: Implement direct support for this type!
11294 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11297 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11299 /// This routine either breaks down the specific type of a 512-bit x86 vector
11300 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11301 /// together based on the available instructions.
11302 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11303 MVT VT, const X86Subtarget *Subtarget,
11304 SelectionDAG &DAG) {
11306 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11307 ArrayRef<int> Mask = SVOp->getMask();
11308 assert(Subtarget->hasAVX512() &&
11309 "Cannot lower 512-bit vectors w/ basic ISA!");
11311 // Check for being able to broadcast a single element.
11312 if (SDValue Broadcast =
11313 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11316 // Dispatch to each element type for lowering. If we don't have supprot for
11317 // specific element type shuffles at 512 bits, immediately split them and
11318 // lower them. Each lowering routine of a given type is allowed to assume that
11319 // the requisite ISA extensions for that element type are available.
11320 switch (VT.SimpleTy) {
11322 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11324 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11326 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11328 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11330 if (Subtarget->hasBWI())
11331 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11334 if (Subtarget->hasBWI())
11335 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11339 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11342 // Otherwise fall back on splitting.
11343 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11346 // Lower vXi1 vector shuffles.
11347 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11348 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11349 // vector, shuffle and then truncate it back.
11350 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11351 MVT VT, const X86Subtarget *Subtarget,
11352 SelectionDAG &DAG) {
11354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11355 ArrayRef<int> Mask = SVOp->getMask();
11356 assert(Subtarget->hasAVX512() &&
11357 "Cannot lower 512-bit vectors w/o basic ISA!");
11359 switch (VT.SimpleTy) {
11361 llvm_unreachable("Expected a vector of i1 elements");
11363 ExtVT = MVT::v2i64;
11366 ExtVT = MVT::v4i32;
11369 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11372 ExtVT = MVT::v16i32;
11375 ExtVT = MVT::v32i16;
11378 ExtVT = MVT::v64i8;
11382 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11383 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11384 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11385 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11387 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11390 V2 = DAG.getUNDEF(ExtVT);
11391 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11392 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11393 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11394 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11396 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11397 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11398 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11400 /// \brief Top-level lowering for x86 vector shuffles.
11402 /// This handles decomposition, canonicalization, and lowering of all x86
11403 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11404 /// above in helper routines. The canonicalization attempts to widen shuffles
11405 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11406 /// s.t. only one of the two inputs needs to be tested, etc.
11407 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11408 SelectionDAG &DAG) {
11409 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11410 ArrayRef<int> Mask = SVOp->getMask();
11411 SDValue V1 = Op.getOperand(0);
11412 SDValue V2 = Op.getOperand(1);
11413 MVT VT = Op.getSimpleValueType();
11414 int NumElements = VT.getVectorNumElements();
11416 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11418 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11419 "Can't lower MMX shuffles");
11421 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11422 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11423 if (V1IsUndef && V2IsUndef)
11424 return DAG.getUNDEF(VT);
11426 // When we create a shuffle node we put the UNDEF node to second operand,
11427 // but in some cases the first operand may be transformed to UNDEF.
11428 // In this case we should just commute the node.
11430 return DAG.getCommutedVectorShuffle(*SVOp);
11432 // Check for non-undef masks pointing at an undef vector and make the masks
11433 // undef as well. This makes it easier to match the shuffle based solely on
11437 if (M >= NumElements) {
11438 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11439 for (int &M : NewMask)
11440 if (M >= NumElements)
11442 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11445 // We actually see shuffles that are entirely re-arrangements of a set of
11446 // zero inputs. This mostly happens while decomposing complex shuffles into
11447 // simple ones. Directly lower these as a buildvector of zeros.
11448 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11449 if (Zeroable.all())
11450 return getZeroVector(VT, Subtarget, DAG, dl);
11452 // Try to collapse shuffles into using a vector type with fewer elements but
11453 // wider element types. We cap this to not form integers or floating point
11454 // elements wider than 64 bits, but it might be interesting to form i128
11455 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11456 SmallVector<int, 16> WidenedMask;
11457 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11458 canWidenShuffleElements(Mask, WidenedMask)) {
11459 MVT NewEltVT = VT.isFloatingPoint()
11460 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11461 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11462 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11463 // Make sure that the new vector type is legal. For example, v2f64 isn't
11465 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11466 V1 = DAG.getBitcast(NewVT, V1);
11467 V2 = DAG.getBitcast(NewVT, V2);
11468 return DAG.getBitcast(
11469 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11473 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11474 for (int M : SVOp->getMask())
11476 ++NumUndefElements;
11477 else if (M < NumElements)
11482 // Commute the shuffle as needed such that more elements come from V1 than
11483 // V2. This allows us to match the shuffle pattern strictly on how many
11484 // elements come from V1 without handling the symmetric cases.
11485 if (NumV2Elements > NumV1Elements)
11486 return DAG.getCommutedVectorShuffle(*SVOp);
11488 // When the number of V1 and V2 elements are the same, try to minimize the
11489 // number of uses of V2 in the low half of the vector. When that is tied,
11490 // ensure that the sum of indices for V1 is equal to or lower than the sum
11491 // indices for V2. When those are equal, try to ensure that the number of odd
11492 // indices for V1 is lower than the number of odd indices for V2.
11493 if (NumV1Elements == NumV2Elements) {
11494 int LowV1Elements = 0, LowV2Elements = 0;
11495 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11496 if (M >= NumElements)
11500 if (LowV2Elements > LowV1Elements) {
11501 return DAG.getCommutedVectorShuffle(*SVOp);
11502 } else if (LowV2Elements == LowV1Elements) {
11503 int SumV1Indices = 0, SumV2Indices = 0;
11504 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11505 if (SVOp->getMask()[i] >= NumElements)
11507 else if (SVOp->getMask()[i] >= 0)
11509 if (SumV2Indices < SumV1Indices) {
11510 return DAG.getCommutedVectorShuffle(*SVOp);
11511 } else if (SumV2Indices == SumV1Indices) {
11512 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11513 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11514 if (SVOp->getMask()[i] >= NumElements)
11515 NumV2OddIndices += i % 2;
11516 else if (SVOp->getMask()[i] >= 0)
11517 NumV1OddIndices += i % 2;
11518 if (NumV2OddIndices < NumV1OddIndices)
11519 return DAG.getCommutedVectorShuffle(*SVOp);
11524 // For each vector width, delegate to a specialized lowering routine.
11525 if (VT.is128BitVector())
11526 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11528 if (VT.is256BitVector())
11529 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11531 if (VT.is512BitVector())
11532 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11535 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11536 llvm_unreachable("Unimplemented!");
11539 // This function assumes its argument is a BUILD_VECTOR of constants or
11540 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11542 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11543 unsigned &MaskValue) {
11545 unsigned NumElems = BuildVector->getNumOperands();
11547 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11548 // We don't handle the >2 lanes case right now.
11549 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11553 unsigned NumElemsInLane = NumElems / NumLanes;
11555 // Blend for v16i16 should be symmetric for the both lanes.
11556 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11557 SDValue EltCond = BuildVector->getOperand(i);
11558 SDValue SndLaneEltCond =
11559 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11561 int Lane1Cond = -1, Lane2Cond = -1;
11562 if (isa<ConstantSDNode>(EltCond))
11563 Lane1Cond = !isNullConstant(EltCond);
11564 if (isa<ConstantSDNode>(SndLaneEltCond))
11565 Lane2Cond = !isNullConstant(SndLaneEltCond);
11567 unsigned LaneMask = 0;
11568 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11569 // Lane1Cond != 0, means we want the first argument.
11570 // Lane1Cond == 0, means we want the second argument.
11571 // The encoding of this argument is 0 for the first argument, 1
11572 // for the second. Therefore, invert the condition.
11573 LaneMask = !Lane1Cond << i;
11574 else if (Lane1Cond < 0)
11575 LaneMask = !Lane2Cond << i;
11579 MaskValue |= LaneMask;
11581 MaskValue |= LaneMask << NumElemsInLane;
11586 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11587 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11588 const X86Subtarget *Subtarget,
11589 SelectionDAG &DAG) {
11590 SDValue Cond = Op.getOperand(0);
11591 SDValue LHS = Op.getOperand(1);
11592 SDValue RHS = Op.getOperand(2);
11594 MVT VT = Op.getSimpleValueType();
11596 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11598 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11600 // Only non-legal VSELECTs reach this lowering, convert those into generic
11601 // shuffles and re-use the shuffle lowering path for blends.
11602 SmallVector<int, 32> Mask;
11603 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11604 SDValue CondElt = CondBV->getOperand(i);
11606 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11609 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11612 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11613 // A vselect where all conditions and data are constants can be optimized into
11614 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11615 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11616 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11617 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11620 // Try to lower this to a blend-style vector shuffle. This can handle all
11621 // constant condition cases.
11622 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11625 // Variable blends are only legal from SSE4.1 onward.
11626 if (!Subtarget->hasSSE41())
11629 // Only some types will be legal on some subtargets. If we can emit a legal
11630 // VSELECT-matching blend, return Op, and but if we need to expand, return
11632 switch (Op.getSimpleValueType().SimpleTy) {
11634 // Most of the vector types have blends past SSE4.1.
11638 // The byte blends for AVX vectors were introduced only in AVX2.
11639 if (Subtarget->hasAVX2())
11646 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11647 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11650 // FIXME: We should custom lower this by fixing the condition and using i8
11656 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11657 MVT VT = Op.getSimpleValueType();
11660 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11663 if (VT.getSizeInBits() == 8) {
11664 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11665 Op.getOperand(0), Op.getOperand(1));
11666 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11667 DAG.getValueType(VT));
11668 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11671 if (VT.getSizeInBits() == 16) {
11672 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11673 if (isNullConstant(Op.getOperand(1)))
11674 return DAG.getNode(
11675 ISD::TRUNCATE, dl, MVT::i16,
11676 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11677 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11678 Op.getOperand(1)));
11679 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11680 Op.getOperand(0), Op.getOperand(1));
11681 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11682 DAG.getValueType(VT));
11683 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11686 if (VT == MVT::f32) {
11687 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11688 // the result back to FR32 register. It's only worth matching if the
11689 // result has a single use which is a store or a bitcast to i32. And in
11690 // the case of a store, it's not worth it if the index is a constant 0,
11691 // because a MOVSSmr can be used instead, which is smaller and faster.
11692 if (!Op.hasOneUse())
11694 SDNode *User = *Op.getNode()->use_begin();
11695 if ((User->getOpcode() != ISD::STORE ||
11696 isNullConstant(Op.getOperand(1))) &&
11697 (User->getOpcode() != ISD::BITCAST ||
11698 User->getValueType(0) != MVT::i32))
11700 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11701 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11703 return DAG.getBitcast(MVT::f32, Extract);
11706 if (VT == MVT::i32 || VT == MVT::i64) {
11707 // ExtractPS/pextrq works with constant index.
11708 if (isa<ConstantSDNode>(Op.getOperand(1)))
11714 /// Extract one bit from mask vector, like v16i1 or v8i1.
11715 /// AVX-512 feature.
11717 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11718 SDValue Vec = Op.getOperand(0);
11720 MVT VecVT = Vec.getSimpleValueType();
11721 SDValue Idx = Op.getOperand(1);
11722 MVT EltVT = Op.getSimpleValueType();
11724 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11725 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11726 "Unexpected vector type in ExtractBitFromMaskVector");
11728 // variable index can't be handled in mask registers,
11729 // extend vector to VR512
11730 if (!isa<ConstantSDNode>(Idx)) {
11731 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11732 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11733 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11734 ExtVT.getVectorElementType(), Ext, Idx);
11735 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11738 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11739 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11740 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11741 rc = getRegClassFor(MVT::v16i1);
11742 unsigned MaxSift = rc->getSize()*8 - 1;
11743 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11744 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11745 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11746 DAG.getConstant(MaxSift, dl, MVT::i8));
11747 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11748 DAG.getIntPtrConstant(0, dl));
11752 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11753 SelectionDAG &DAG) const {
11755 SDValue Vec = Op.getOperand(0);
11756 MVT VecVT = Vec.getSimpleValueType();
11757 SDValue Idx = Op.getOperand(1);
11759 if (Op.getSimpleValueType() == MVT::i1)
11760 return ExtractBitFromMaskVector(Op, DAG);
11762 if (!isa<ConstantSDNode>(Idx)) {
11763 if (VecVT.is512BitVector() ||
11764 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11765 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11768 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11769 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11770 MaskEltVT.getSizeInBits());
11772 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11773 auto PtrVT = getPointerTy(DAG.getDataLayout());
11774 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11775 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11776 DAG.getConstant(0, dl, PtrVT));
11777 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11779 DAG.getConstant(0, dl, PtrVT));
11784 // If this is a 256-bit vector result, first extract the 128-bit vector and
11785 // then extract the element from the 128-bit vector.
11786 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11788 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11789 // Get the 128-bit vector.
11790 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11791 MVT EltVT = VecVT.getVectorElementType();
11793 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11794 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11796 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11797 // this can be done with a mask.
11798 IdxVal &= ElemsPerChunk - 1;
11799 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11800 DAG.getConstant(IdxVal, dl, MVT::i32));
11803 assert(VecVT.is128BitVector() && "Unexpected vector length");
11805 if (Subtarget->hasSSE41())
11806 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11809 MVT VT = Op.getSimpleValueType();
11810 // TODO: handle v16i8.
11811 if (VT.getSizeInBits() == 16) {
11812 SDValue Vec = Op.getOperand(0);
11813 if (isNullConstant(Op.getOperand(1)))
11814 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11815 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11816 DAG.getBitcast(MVT::v4i32, Vec),
11817 Op.getOperand(1)));
11818 // Transform it so it match pextrw which produces a 32-bit result.
11819 MVT EltVT = MVT::i32;
11820 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11821 Op.getOperand(0), Op.getOperand(1));
11822 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11823 DAG.getValueType(VT));
11824 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11827 if (VT.getSizeInBits() == 32) {
11828 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11832 // SHUFPS the element to the lowest double word, then movss.
11833 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11834 MVT VVT = Op.getOperand(0).getSimpleValueType();
11835 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11836 DAG.getUNDEF(VVT), Mask);
11837 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11838 DAG.getIntPtrConstant(0, dl));
11841 if (VT.getSizeInBits() == 64) {
11842 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11843 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11844 // to match extract_elt for f64.
11845 if (isNullConstant(Op.getOperand(1)))
11848 // UNPCKHPD the element to the lowest double word, then movsd.
11849 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11850 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11851 int Mask[2] = { 1, -1 };
11852 MVT VVT = Op.getOperand(0).getSimpleValueType();
11853 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11854 DAG.getUNDEF(VVT), Mask);
11855 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11856 DAG.getIntPtrConstant(0, dl));
11862 /// Insert one bit to mask vector, like v16i1 or v8i1.
11863 /// AVX-512 feature.
11865 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11867 SDValue Vec = Op.getOperand(0);
11868 SDValue Elt = Op.getOperand(1);
11869 SDValue Idx = Op.getOperand(2);
11870 MVT VecVT = Vec.getSimpleValueType();
11872 if (!isa<ConstantSDNode>(Idx)) {
11873 // Non constant index. Extend source and destination,
11874 // insert element and then truncate the result.
11875 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11876 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11877 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11878 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11879 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11880 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11883 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11884 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11886 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11887 DAG.getConstant(IdxVal, dl, MVT::i8));
11888 if (Vec.getOpcode() == ISD::UNDEF)
11890 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11893 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11894 SelectionDAG &DAG) const {
11895 MVT VT = Op.getSimpleValueType();
11896 MVT EltVT = VT.getVectorElementType();
11898 if (EltVT == MVT::i1)
11899 return InsertBitToMaskVector(Op, DAG);
11902 SDValue N0 = Op.getOperand(0);
11903 SDValue N1 = Op.getOperand(1);
11904 SDValue N2 = Op.getOperand(2);
11905 if (!isa<ConstantSDNode>(N2))
11907 auto *N2C = cast<ConstantSDNode>(N2);
11908 unsigned IdxVal = N2C->getZExtValue();
11910 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11911 // into that, and then insert the subvector back into the result.
11912 if (VT.is256BitVector() || VT.is512BitVector()) {
11913 // With a 256-bit vector, we can insert into the zero element efficiently
11914 // using a blend if we have AVX or AVX2 and the right data type.
11915 if (VT.is256BitVector() && IdxVal == 0) {
11916 // TODO: It is worthwhile to cast integer to floating point and back
11917 // and incur a domain crossing penalty if that's what we'll end up
11918 // doing anyway after extracting to a 128-bit vector.
11919 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11920 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11921 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11922 N2 = DAG.getIntPtrConstant(1, dl);
11923 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11927 // Get the desired 128-bit vector chunk.
11928 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11930 // Insert the element into the desired chunk.
11931 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11932 assert(isPowerOf2_32(NumEltsIn128));
11933 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11934 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11936 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11937 DAG.getConstant(IdxIn128, dl, MVT::i32));
11939 // Insert the changed part back into the bigger vector
11940 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11942 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11944 if (Subtarget->hasSSE41()) {
11945 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11947 if (VT == MVT::v8i16) {
11948 Opc = X86ISD::PINSRW;
11950 assert(VT == MVT::v16i8);
11951 Opc = X86ISD::PINSRB;
11954 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11956 if (N1.getValueType() != MVT::i32)
11957 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11958 if (N2.getValueType() != MVT::i32)
11959 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11960 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11963 if (EltVT == MVT::f32) {
11964 // Bits [7:6] of the constant are the source select. This will always be
11965 // zero here. The DAG Combiner may combine an extract_elt index into
11966 // these bits. For example (insert (extract, 3), 2) could be matched by
11967 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11968 // Bits [5:4] of the constant are the destination select. This is the
11969 // value of the incoming immediate.
11970 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11971 // combine either bitwise AND or insert of float 0.0 to set these bits.
11973 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11974 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11975 // If this is an insertion of 32-bits into the low 32-bits of
11976 // a vector, we prefer to generate a blend with immediate rather
11977 // than an insertps. Blends are simpler operations in hardware and so
11978 // will always have equal or better performance than insertps.
11979 // But if optimizing for size and there's a load folding opportunity,
11980 // generate insertps because blendps does not have a 32-bit memory
11982 N2 = DAG.getIntPtrConstant(1, dl);
11983 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11984 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11986 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11987 // Create this as a scalar to vector..
11988 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11989 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11992 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11993 // PINSR* works with constant index.
11998 if (EltVT == MVT::i8)
12001 if (EltVT.getSizeInBits() == 16) {
12002 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12003 // as its second argument.
12004 if (N1.getValueType() != MVT::i32)
12005 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12006 if (N2.getValueType() != MVT::i32)
12007 N2 = DAG.getIntPtrConstant(IdxVal, dl);
12008 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12013 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12015 MVT OpVT = Op.getSimpleValueType();
12017 // If this is a 256-bit vector result, first insert into a 128-bit
12018 // vector and then insert into the 256-bit vector.
12019 if (!OpVT.is128BitVector()) {
12020 // Insert into a 128-bit vector.
12021 unsigned SizeFactor = OpVT.getSizeInBits()/128;
12022 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12023 OpVT.getVectorNumElements() / SizeFactor);
12025 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12027 // Insert the 128-bit vector.
12028 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12031 if (OpVT == MVT::v1i64 &&
12032 Op.getOperand(0).getValueType() == MVT::i64)
12033 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12035 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12036 assert(OpVT.is128BitVector() && "Expected an SSE type!");
12037 return DAG.getBitcast(
12038 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12041 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12042 // a simple subregister reference or explicit instructions to grab
12043 // upper bits of a vector.
12044 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12045 SelectionDAG &DAG) {
12047 SDValue In = Op.getOperand(0);
12048 SDValue Idx = Op.getOperand(1);
12049 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12050 MVT ResVT = Op.getSimpleValueType();
12051 MVT InVT = In.getSimpleValueType();
12053 if (Subtarget->hasFp256()) {
12054 if (ResVT.is128BitVector() &&
12055 (InVT.is256BitVector() || InVT.is512BitVector()) &&
12056 isa<ConstantSDNode>(Idx)) {
12057 return Extract128BitVector(In, IdxVal, DAG, dl);
12059 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12060 isa<ConstantSDNode>(Idx)) {
12061 return Extract256BitVector(In, IdxVal, DAG, dl);
12067 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12068 // simple superregister reference or explicit instructions to insert
12069 // the upper bits of a vector.
12070 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12071 SelectionDAG &DAG) {
12072 if (!Subtarget->hasAVX())
12076 SDValue Vec = Op.getOperand(0);
12077 SDValue SubVec = Op.getOperand(1);
12078 SDValue Idx = Op.getOperand(2);
12080 if (!isa<ConstantSDNode>(Idx))
12083 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12084 MVT OpVT = Op.getSimpleValueType();
12085 MVT SubVecVT = SubVec.getSimpleValueType();
12087 // Fold two 16-byte subvector loads into one 32-byte load:
12088 // (insert_subvector (insert_subvector undef, (load addr), 0),
12089 // (load addr + 16), Elts/2)
12091 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12092 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12093 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12094 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12095 if (Idx2 && Idx2->getZExtValue() == 0) {
12096 SDValue SubVec2 = Vec.getOperand(1);
12097 // If needed, look through a bitcast to get to the load.
12098 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12099 SubVec2 = SubVec2.getOperand(0);
12101 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12103 unsigned Alignment = FirstLd->getAlignment();
12104 unsigned AS = FirstLd->getAddressSpace();
12105 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12106 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12107 OpVT, AS, Alignment, &Fast) && Fast) {
12108 SDValue Ops[] = { SubVec2, SubVec };
12109 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12116 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12117 SubVecVT.is128BitVector())
12118 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12120 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12121 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12123 if (OpVT.getVectorElementType() == MVT::i1)
12124 return Insert1BitVector(Op, DAG);
12129 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12130 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12131 // one of the above mentioned nodes. It has to be wrapped because otherwise
12132 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12133 // be used to form addressing mode. These wrapped nodes will be selected
12136 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12137 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12139 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12140 // global base reg.
12141 unsigned char OpFlag = 0;
12142 unsigned WrapperKind = X86ISD::Wrapper;
12143 CodeModel::Model M = DAG.getTarget().getCodeModel();
12145 if (Subtarget->isPICStyleRIPRel() &&
12146 (M == CodeModel::Small || M == CodeModel::Kernel))
12147 WrapperKind = X86ISD::WrapperRIP;
12148 else if (Subtarget->isPICStyleGOT())
12149 OpFlag = X86II::MO_GOTOFF;
12150 else if (Subtarget->isPICStyleStubPIC())
12151 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12153 auto PtrVT = getPointerTy(DAG.getDataLayout());
12154 SDValue Result = DAG.getTargetConstantPool(
12155 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12157 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12158 // With PIC, the address is actually $g + Offset.
12161 DAG.getNode(ISD::ADD, DL, PtrVT,
12162 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12168 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12169 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12171 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12172 // global base reg.
12173 unsigned char OpFlag = 0;
12174 unsigned WrapperKind = X86ISD::Wrapper;
12175 CodeModel::Model M = DAG.getTarget().getCodeModel();
12177 if (Subtarget->isPICStyleRIPRel() &&
12178 (M == CodeModel::Small || M == CodeModel::Kernel))
12179 WrapperKind = X86ISD::WrapperRIP;
12180 else if (Subtarget->isPICStyleGOT())
12181 OpFlag = X86II::MO_GOTOFF;
12182 else if (Subtarget->isPICStyleStubPIC())
12183 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12185 auto PtrVT = getPointerTy(DAG.getDataLayout());
12186 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12188 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12190 // With PIC, the address is actually $g + Offset.
12193 DAG.getNode(ISD::ADD, DL, PtrVT,
12194 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12200 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12201 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12203 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12204 // global base reg.
12205 unsigned char OpFlag = 0;
12206 unsigned WrapperKind = X86ISD::Wrapper;
12207 CodeModel::Model M = DAG.getTarget().getCodeModel();
12209 if (Subtarget->isPICStyleRIPRel() &&
12210 (M == CodeModel::Small || M == CodeModel::Kernel)) {
12211 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12212 OpFlag = X86II::MO_GOTPCREL;
12213 WrapperKind = X86ISD::WrapperRIP;
12214 } else if (Subtarget->isPICStyleGOT()) {
12215 OpFlag = X86II::MO_GOT;
12216 } else if (Subtarget->isPICStyleStubPIC()) {
12217 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12218 } else if (Subtarget->isPICStyleStubNoDynamic()) {
12219 OpFlag = X86II::MO_DARWIN_NONLAZY;
12222 auto PtrVT = getPointerTy(DAG.getDataLayout());
12223 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12226 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12228 // With PIC, the address is actually $g + Offset.
12229 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12230 !Subtarget->is64Bit()) {
12232 DAG.getNode(ISD::ADD, DL, PtrVT,
12233 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12236 // For symbols that require a load from a stub to get the address, emit the
12238 if (isGlobalStubReference(OpFlag))
12239 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12240 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12241 false, false, false, 0);
12247 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12248 // Create the TargetBlockAddressAddress node.
12249 unsigned char OpFlags =
12250 Subtarget->ClassifyBlockAddressReference();
12251 CodeModel::Model M = DAG.getTarget().getCodeModel();
12252 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12253 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12255 auto PtrVT = getPointerTy(DAG.getDataLayout());
12256 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12258 if (Subtarget->isPICStyleRIPRel() &&
12259 (M == CodeModel::Small || M == CodeModel::Kernel))
12260 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12262 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12264 // With PIC, the address is actually $g + Offset.
12265 if (isGlobalRelativeToPICBase(OpFlags)) {
12266 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12267 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12274 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12275 int64_t Offset, SelectionDAG &DAG) const {
12276 // Create the TargetGlobalAddress node, folding in the constant
12277 // offset if it is legal.
12278 unsigned char OpFlags =
12279 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12280 CodeModel::Model M = DAG.getTarget().getCodeModel();
12281 auto PtrVT = getPointerTy(DAG.getDataLayout());
12283 if (OpFlags == X86II::MO_NO_FLAG &&
12284 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12285 // A direct static reference to a global.
12286 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12289 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12292 if (Subtarget->isPICStyleRIPRel() &&
12293 (M == CodeModel::Small || M == CodeModel::Kernel))
12294 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12296 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12298 // With PIC, the address is actually $g + Offset.
12299 if (isGlobalRelativeToPICBase(OpFlags)) {
12300 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12301 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12304 // For globals that require a load from a stub to get the address, emit the
12306 if (isGlobalStubReference(OpFlags))
12307 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12308 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12309 false, false, false, 0);
12311 // If there was a non-zero offset that we didn't fold, create an explicit
12312 // addition for it.
12314 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12315 DAG.getConstant(Offset, dl, PtrVT));
12321 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12322 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12323 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12324 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12328 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12329 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12330 unsigned char OperandFlags, bool LocalDynamic = false) {
12331 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12332 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12334 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12335 GA->getValueType(0),
12339 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12343 SDValue Ops[] = { Chain, TGA, *InFlag };
12344 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12346 SDValue Ops[] = { Chain, TGA };
12347 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12350 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12351 MFI->setAdjustsStack(true);
12352 MFI->setHasCalls(true);
12354 SDValue Flag = Chain.getValue(1);
12355 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12358 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12360 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12363 SDLoc dl(GA); // ? function entry point might be better
12364 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12365 DAG.getNode(X86ISD::GlobalBaseReg,
12366 SDLoc(), PtrVT), InFlag);
12367 InFlag = Chain.getValue(1);
12369 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12372 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12374 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12376 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12377 X86::RAX, X86II::MO_TLSGD);
12380 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12386 // Get the start address of the TLS block for this module.
12387 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12388 .getInfo<X86MachineFunctionInfo>();
12389 MFI->incNumLocalDynamicTLSAccesses();
12393 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12394 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12397 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12398 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12399 InFlag = Chain.getValue(1);
12400 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12401 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12404 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12408 unsigned char OperandFlags = X86II::MO_DTPOFF;
12409 unsigned WrapperKind = X86ISD::Wrapper;
12410 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12411 GA->getValueType(0),
12412 GA->getOffset(), OperandFlags);
12413 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12415 // Add x@dtpoff with the base.
12416 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12419 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12420 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12421 const EVT PtrVT, TLSModel::Model model,
12422 bool is64Bit, bool isPIC) {
12425 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12426 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12427 is64Bit ? 257 : 256));
12429 SDValue ThreadPointer =
12430 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12431 MachinePointerInfo(Ptr), false, false, false, 0);
12433 unsigned char OperandFlags = 0;
12434 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12436 unsigned WrapperKind = X86ISD::Wrapper;
12437 if (model == TLSModel::LocalExec) {
12438 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12439 } else if (model == TLSModel::InitialExec) {
12441 OperandFlags = X86II::MO_GOTTPOFF;
12442 WrapperKind = X86ISD::WrapperRIP;
12444 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12447 llvm_unreachable("Unexpected model");
12450 // emit "addl x@ntpoff,%eax" (local exec)
12451 // or "addl x@indntpoff,%eax" (initial exec)
12452 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12454 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12455 GA->getOffset(), OperandFlags);
12456 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12458 if (model == TLSModel::InitialExec) {
12459 if (isPIC && !is64Bit) {
12460 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12461 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12465 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12466 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12467 false, false, false, 0);
12470 // The address of the thread local variable is the add of the thread
12471 // pointer with the offset of the variable.
12472 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12476 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12478 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12480 // Cygwin uses emutls.
12481 // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12482 if (Subtarget->isTargetWindowsCygwin())
12483 return LowerToTLSEmulatedModel(GA, DAG);
12485 const GlobalValue *GV = GA->getGlobal();
12486 auto PtrVT = getPointerTy(DAG.getDataLayout());
12488 if (Subtarget->isTargetELF()) {
12489 if (DAG.getTarget().Options.EmulatedTLS)
12490 return LowerToTLSEmulatedModel(GA, DAG);
12491 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12493 case TLSModel::GeneralDynamic:
12494 if (Subtarget->is64Bit())
12495 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12496 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12497 case TLSModel::LocalDynamic:
12498 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12499 Subtarget->is64Bit());
12500 case TLSModel::InitialExec:
12501 case TLSModel::LocalExec:
12502 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12503 DAG.getTarget().getRelocationModel() ==
12506 llvm_unreachable("Unknown TLS model.");
12509 if (Subtarget->isTargetDarwin()) {
12510 // Darwin only has one model of TLS. Lower to that.
12511 unsigned char OpFlag = 0;
12512 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12513 X86ISD::WrapperRIP : X86ISD::Wrapper;
12515 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12516 // global base reg.
12517 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12518 !Subtarget->is64Bit();
12520 OpFlag = X86II::MO_TLVP_PIC_BASE;
12522 OpFlag = X86II::MO_TLVP;
12524 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12525 GA->getValueType(0),
12526 GA->getOffset(), OpFlag);
12527 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12529 // With PIC32, the address is actually $g + Offset.
12531 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12532 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12535 // Lowering the machine isd will make sure everything is in the right
12537 SDValue Chain = DAG.getEntryNode();
12538 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12539 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12540 SDValue Args[] = { Chain, Offset };
12541 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12543 DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12544 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12546 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12547 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12548 MFI->setAdjustsStack(true);
12550 // And our return value (tls address) is in the standard call return value
12552 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12553 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12556 if (Subtarget->isTargetKnownWindowsMSVC() ||
12557 Subtarget->isTargetWindowsGNU()) {
12558 // Just use the implicit TLS architecture
12559 // Need to generate someting similar to:
12560 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12562 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12563 // mov rcx, qword [rdx+rcx*8]
12564 // mov eax, .tls$:tlsvar
12565 // [rax+rcx] contains the address
12566 // Windows 64bit: gs:0x58
12567 // Windows 32bit: fs:__tls_array
12570 SDValue Chain = DAG.getEntryNode();
12572 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12573 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12574 // use its literal value of 0x2C.
12575 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12576 ? Type::getInt8PtrTy(*DAG.getContext(),
12578 : Type::getInt32PtrTy(*DAG.getContext(),
12581 SDValue TlsArray = Subtarget->is64Bit()
12582 ? DAG.getIntPtrConstant(0x58, dl)
12583 : (Subtarget->isTargetWindowsGNU()
12584 ? DAG.getIntPtrConstant(0x2C, dl)
12585 : DAG.getExternalSymbol("_tls_array", PtrVT));
12587 SDValue ThreadPointer =
12588 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12592 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12593 res = ThreadPointer;
12595 // Load the _tls_index variable
12596 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12597 if (Subtarget->is64Bit())
12598 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12599 MachinePointerInfo(), MVT::i32, false, false,
12602 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12605 auto &DL = DAG.getDataLayout();
12607 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12608 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12610 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12613 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12616 // Get the offset of start of .tls section
12617 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12618 GA->getValueType(0),
12619 GA->getOffset(), X86II::MO_SECREL);
12620 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12622 // The address of the thread local variable is the add of the thread
12623 // pointer with the offset of the variable.
12624 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12627 llvm_unreachable("TLS not implemented for this target.");
12630 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12631 /// and take a 2 x i32 value to shift plus a shift amount.
12632 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12633 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12634 MVT VT = Op.getSimpleValueType();
12635 unsigned VTBits = VT.getSizeInBits();
12637 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12638 SDValue ShOpLo = Op.getOperand(0);
12639 SDValue ShOpHi = Op.getOperand(1);
12640 SDValue ShAmt = Op.getOperand(2);
12641 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12642 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12644 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12645 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12646 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12647 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12648 : DAG.getConstant(0, dl, VT);
12650 SDValue Tmp2, Tmp3;
12651 if (Op.getOpcode() == ISD::SHL_PARTS) {
12652 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12653 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12655 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12656 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12659 // If the shift amount is larger or equal than the width of a part we can't
12660 // rely on the results of shld/shrd. Insert a test and select the appropriate
12661 // values for large shift amounts.
12662 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12663 DAG.getConstant(VTBits, dl, MVT::i8));
12664 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12665 AndNode, DAG.getConstant(0, dl, MVT::i8));
12668 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12669 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12670 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12672 if (Op.getOpcode() == ISD::SHL_PARTS) {
12673 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12674 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12676 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12677 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12680 SDValue Ops[2] = { Lo, Hi };
12681 return DAG.getMergeValues(Ops, dl);
12684 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12685 SelectionDAG &DAG) const {
12686 SDValue Src = Op.getOperand(0);
12687 MVT SrcVT = Src.getSimpleValueType();
12688 MVT VT = Op.getSimpleValueType();
12691 if (SrcVT.isVector()) {
12692 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12693 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12694 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12695 DAG.getUNDEF(SrcVT)));
12697 if (SrcVT.getVectorElementType() == MVT::i1) {
12698 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12699 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12700 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12705 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12706 "Unknown SINT_TO_FP to lower!");
12708 // These are really Legal; return the operand so the caller accepts it as
12710 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12712 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12713 Subtarget->is64Bit()) {
12717 SDValue ValueToStore = Op.getOperand(0);
12718 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12719 !Subtarget->is64Bit())
12720 // Bitcasting to f64 here allows us to do a single 64-bit store from
12721 // an SSE register, avoiding the store forwarding penalty that would come
12722 // with two 32-bit stores.
12723 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
12725 unsigned Size = SrcVT.getSizeInBits()/8;
12726 MachineFunction &MF = DAG.getMachineFunction();
12727 auto PtrVT = getPointerTy(MF.getDataLayout());
12728 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12729 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12730 SDValue Chain = DAG.getStore(
12731 DAG.getEntryNode(), dl, ValueToStore, StackSlot,
12732 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12734 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12737 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12739 SelectionDAG &DAG) const {
12743 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12745 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12747 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12749 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12751 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12752 MachineMemOperand *MMO;
12754 int SSFI = FI->getIndex();
12755 MMO = DAG.getMachineFunction().getMachineMemOperand(
12756 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12757 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12759 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12760 StackSlot = StackSlot.getOperand(1);
12762 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12763 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12765 Tys, Ops, SrcVT, MMO);
12768 Chain = Result.getValue(1);
12769 SDValue InFlag = Result.getValue(2);
12771 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12772 // shouldn't be necessary except that RFP cannot be live across
12773 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12774 MachineFunction &MF = DAG.getMachineFunction();
12775 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12776 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12777 auto PtrVT = getPointerTy(MF.getDataLayout());
12778 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12779 Tys = DAG.getVTList(MVT::Other);
12781 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12783 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12784 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12785 MachineMemOperand::MOStore, SSFISize, SSFISize);
12787 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12788 Ops, Op.getValueType(), MMO);
12789 Result = DAG.getLoad(
12790 Op.getValueType(), DL, Chain, StackSlot,
12791 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12792 false, false, false, 0);
12798 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12799 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12800 SelectionDAG &DAG) const {
12801 // This algorithm is not obvious. Here it is what we're trying to output:
12804 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12805 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12807 haddpd %xmm0, %xmm0
12809 pshufd $0x4e, %xmm0, %xmm1
12815 LLVMContext *Context = DAG.getContext();
12817 // Build some magic constants.
12818 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12819 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12820 auto PtrVT = getPointerTy(DAG.getDataLayout());
12821 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12823 SmallVector<Constant*,2> CV1;
12825 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12826 APInt(64, 0x4330000000000000ULL))));
12828 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12829 APInt(64, 0x4530000000000000ULL))));
12830 Constant *C1 = ConstantVector::get(CV1);
12831 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12833 // Load the 64-bit value into an XMM register.
12834 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12837 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12838 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12839 false, false, false, 16);
12841 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12844 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12845 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12846 false, false, false, 16);
12847 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12848 // TODO: Are there any fast-math-flags to propagate here?
12849 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12852 if (Subtarget->hasSSE3()) {
12853 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12854 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12856 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12857 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12859 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12860 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12863 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12864 DAG.getIntPtrConstant(0, dl));
12867 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12868 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12869 SelectionDAG &DAG) const {
12871 // FP constant to bias correct the final result.
12872 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12875 // Load the 32-bit value into an XMM register.
12876 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12879 // Zero out the upper parts of the register.
12880 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12882 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12883 DAG.getBitcast(MVT::v2f64, Load),
12884 DAG.getIntPtrConstant(0, dl));
12886 // Or the load with the bias.
12887 SDValue Or = DAG.getNode(
12888 ISD::OR, dl, MVT::v2i64,
12889 DAG.getBitcast(MVT::v2i64,
12890 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12891 DAG.getBitcast(MVT::v2i64,
12892 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12894 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12895 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12897 // Subtract the bias.
12898 // TODO: Are there any fast-math-flags to propagate here?
12899 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12901 // Handle final rounding.
12902 MVT DestVT = Op.getSimpleValueType();
12904 if (DestVT.bitsLT(MVT::f64))
12905 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12906 DAG.getIntPtrConstant(0, dl));
12907 if (DestVT.bitsGT(MVT::f64))
12908 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12910 // Handle final rounding.
12914 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12915 const X86Subtarget &Subtarget) {
12916 // The algorithm is the following:
12917 // #ifdef __SSE4_1__
12918 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12919 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12920 // (uint4) 0x53000000, 0xaa);
12922 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12923 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12925 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12926 // return (float4) lo + fhi;
12928 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12929 // reassociate the two FADDs, and if we do that, the algorithm fails
12930 // spectacularly (PR24512).
12931 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12932 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12933 // there's also the MachineCombiner reassociations happening on Machine IR.
12934 if (DAG.getTarget().Options.UnsafeFPMath)
12938 SDValue V = Op->getOperand(0);
12939 MVT VecIntVT = V.getSimpleValueType();
12940 bool Is128 = VecIntVT == MVT::v4i32;
12941 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12942 // If we convert to something else than the supported type, e.g., to v4f64,
12944 if (VecFloatVT != Op->getSimpleValueType(0))
12947 unsigned NumElts = VecIntVT.getVectorNumElements();
12948 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12949 "Unsupported custom type");
12950 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12952 // In the #idef/#else code, we have in common:
12953 // - The vector of constants:
12959 // Create the splat vector for 0x4b000000.
12960 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12961 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12962 CstLow, CstLow, CstLow, CstLow};
12963 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12964 makeArrayRef(&CstLowArray[0], NumElts));
12965 // Create the splat vector for 0x53000000.
12966 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12967 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12968 CstHigh, CstHigh, CstHigh, CstHigh};
12969 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12970 makeArrayRef(&CstHighArray[0], NumElts));
12972 // Create the right shift.
12973 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12974 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12975 CstShift, CstShift, CstShift, CstShift};
12976 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12977 makeArrayRef(&CstShiftArray[0], NumElts));
12978 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12981 if (Subtarget.hasSSE41()) {
12982 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12983 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12984 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12985 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12986 // Low will be bitcasted right away, so do not bother bitcasting back to its
12988 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12989 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12990 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12991 // (uint4) 0x53000000, 0xaa);
12992 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12993 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12994 // High will be bitcasted right away, so do not bother bitcasting back to
12995 // its original type.
12996 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12997 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12999 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
13000 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
13001 CstMask, CstMask, CstMask);
13002 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13003 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13004 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13006 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13007 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13010 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13011 SDValue CstFAdd = DAG.getConstantFP(
13012 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
13013 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
13014 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
13015 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
13016 makeArrayRef(&CstFAddArray[0], NumElts));
13018 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13019 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13020 // TODO: Are there any fast-math-flags to propagate here?
13022 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13023 // return (float4) lo + fhi;
13024 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13025 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13028 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13029 SelectionDAG &DAG) const {
13030 SDValue N0 = Op.getOperand(0);
13031 MVT SVT = N0.getSimpleValueType();
13034 switch (SVT.SimpleTy) {
13036 llvm_unreachable("Custom UINT_TO_FP is not supported!");
13041 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13042 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13043 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13047 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13050 assert(Subtarget->hasAVX512());
13051 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13052 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13056 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13057 SelectionDAG &DAG) const {
13058 SDValue N0 = Op.getOperand(0);
13060 auto PtrVT = getPointerTy(DAG.getDataLayout());
13062 if (Op.getSimpleValueType().isVector())
13063 return lowerUINT_TO_FP_vec(Op, DAG);
13065 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13066 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13067 // the optimization here.
13068 if (DAG.SignBitIsZero(N0))
13069 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13071 MVT SrcVT = N0.getSimpleValueType();
13072 MVT DstVT = Op.getSimpleValueType();
13074 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13075 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13076 // Conversions from unsigned i32 to f32/f64 are legal,
13077 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13081 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13082 return LowerUINT_TO_FP_i64(Op, DAG);
13083 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13084 return LowerUINT_TO_FP_i32(Op, DAG);
13085 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13088 // Make a 64-bit buffer, and use it to build an FILD.
13089 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13090 if (SrcVT == MVT::i32) {
13091 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13092 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13093 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13094 StackSlot, MachinePointerInfo(),
13096 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13097 OffsetSlot, MachinePointerInfo(),
13099 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13103 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13104 SDValue ValueToStore = Op.getOperand(0);
13105 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget->is64Bit())
13106 // Bitcasting to f64 here allows us to do a single 64-bit store from
13107 // an SSE register, avoiding the store forwarding penalty that would come
13108 // with two 32-bit stores.
13109 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13110 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore,
13111 StackSlot, MachinePointerInfo(),
13113 // For i64 source, we need to add the appropriate power of 2 if the input
13114 // was negative. This is the same as the optimization in
13115 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13116 // we must be careful to do the computation in x87 extended precision, not
13117 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13118 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13119 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13120 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13121 MachineMemOperand::MOLoad, 8, 8);
13123 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13124 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13125 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13128 APInt FF(32, 0x5F800000ULL);
13130 // Check whether the sign bit is set.
13131 SDValue SignSet = DAG.getSetCC(
13132 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13133 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13135 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13136 SDValue FudgePtr = DAG.getConstantPool(
13137 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13139 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13140 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13141 SDValue Four = DAG.getIntPtrConstant(4, dl);
13142 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13144 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13146 // Load the value out, extending it from f32 to f80.
13147 // FIXME: Avoid the extend by constructing the right constant pool?
13148 SDValue Fudge = DAG.getExtLoad(
13149 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13150 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13151 false, false, false, 4);
13152 // Extend everything to 80 bits to force it to be done on x87.
13153 // TODO: Are there any fast-math-flags to propagate here?
13154 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13155 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13156 DAG.getIntPtrConstant(0, dl));
13159 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13160 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13161 // just return an <SDValue(), SDValue()> pair.
13162 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13163 // to i16, i32 or i64, and we lower it to a legal sequence.
13164 // If lowered to the final integer result we return a <result, SDValue()> pair.
13165 // Otherwise we lower it to a sequence ending with a FIST, return a
13166 // <FIST, StackSlot> pair, and the caller is responsible for loading
13167 // the final integer result from StackSlot.
13168 std::pair<SDValue,SDValue>
13169 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13170 bool IsSigned, bool IsReplace) const {
13173 EVT DstTy = Op.getValueType();
13174 EVT TheVT = Op.getOperand(0).getValueType();
13175 auto PtrVT = getPointerTy(DAG.getDataLayout());
13177 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13178 // f16 must be promoted before using the lowering in this routine.
13179 // fp128 does not use this lowering.
13180 return std::make_pair(SDValue(), SDValue());
13183 // If using FIST to compute an unsigned i64, we'll need some fixup
13184 // to handle values above the maximum signed i64. A FIST is always
13185 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13186 bool UnsignedFixup = !IsSigned &&
13187 DstTy == MVT::i64 &&
13188 (!Subtarget->is64Bit() ||
13189 !isScalarFPTypeInSSEReg(TheVT));
13191 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13192 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13193 // The low 32 bits of the fist result will have the correct uint32 result.
13194 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13198 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13199 DstTy.getSimpleVT() >= MVT::i16 &&
13200 "Unknown FP_TO_INT to lower!");
13202 // These are really Legal.
13203 if (DstTy == MVT::i32 &&
13204 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13205 return std::make_pair(SDValue(), SDValue());
13206 if (Subtarget->is64Bit() &&
13207 DstTy == MVT::i64 &&
13208 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13209 return std::make_pair(SDValue(), SDValue());
13211 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13213 MachineFunction &MF = DAG.getMachineFunction();
13214 unsigned MemSize = DstTy.getSizeInBits()/8;
13215 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13216 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13219 switch (DstTy.getSimpleVT().SimpleTy) {
13220 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13221 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13222 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13223 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13226 SDValue Chain = DAG.getEntryNode();
13227 SDValue Value = Op.getOperand(0);
13228 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13230 if (UnsignedFixup) {
13232 // Conversion to unsigned i64 is implemented with a select,
13233 // depending on whether the source value fits in the range
13234 // of a signed i64. Let Thresh be the FP equivalent of
13235 // 0x8000000000000000ULL.
13237 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13238 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13239 // Fist-to-mem64 FistSrc
13240 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13241 // to XOR'ing the high 32 bits with Adjust.
13243 // Being a power of 2, Thresh is exactly representable in all FP formats.
13244 // For X87 we'd like to use the smallest FP type for this constant, but
13245 // for DAG type consistency we have to match the FP operand type.
13247 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13248 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13249 bool LosesInfo = false;
13250 if (TheVT == MVT::f64)
13251 // The rounding mode is irrelevant as the conversion should be exact.
13252 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13254 else if (TheVT == MVT::f80)
13255 Status = Thresh.convert(APFloat::x87DoubleExtended,
13256 APFloat::rmNearestTiesToEven, &LosesInfo);
13258 assert(Status == APFloat::opOK && !LosesInfo &&
13259 "FP conversion should have been exact");
13261 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13263 SDValue Cmp = DAG.getSetCC(DL,
13264 getSetCCResultType(DAG.getDataLayout(),
13265 *DAG.getContext(), TheVT),
13266 Value, ThreshVal, ISD::SETLT);
13267 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13268 DAG.getConstant(0, DL, MVT::i32),
13269 DAG.getConstant(0x80000000, DL, MVT::i32));
13270 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13271 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13272 *DAG.getContext(), TheVT),
13273 Value, ThreshVal, ISD::SETLT);
13274 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13277 // FIXME This causes a redundant load/store if the SSE-class value is already
13278 // in memory, such as if it is on the callstack.
13279 if (isScalarFPTypeInSSEReg(TheVT)) {
13280 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13281 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13282 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13284 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13286 Chain, StackSlot, DAG.getValueType(TheVT)
13289 MachineMemOperand *MMO =
13290 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13291 MachineMemOperand::MOLoad, MemSize, MemSize);
13292 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13293 Chain = Value.getValue(1);
13294 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13295 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13298 MachineMemOperand *MMO =
13299 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13300 MachineMemOperand::MOStore, MemSize, MemSize);
13302 if (UnsignedFixup) {
13304 // Insert the FIST, load its result as two i32's,
13305 // and XOR the high i32 with Adjust.
13307 SDValue FistOps[] = { Chain, Value, StackSlot };
13308 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13309 FistOps, DstTy, MMO);
13311 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13312 MachinePointerInfo(),
13313 false, false, false, 0);
13314 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13315 DAG.getConstant(4, DL, PtrVT));
13317 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13318 MachinePointerInfo(),
13319 false, false, false, 0);
13320 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13322 if (Subtarget->is64Bit()) {
13323 // Join High32 and Low32 into a 64-bit result.
13324 // (High32 << 32) | Low32
13325 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13326 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13327 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13328 DAG.getConstant(32, DL, MVT::i8));
13329 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13330 return std::make_pair(Result, SDValue());
13333 SDValue ResultOps[] = { Low32, High32 };
13335 SDValue pair = IsReplace
13336 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13337 : DAG.getMergeValues(ResultOps, DL);
13338 return std::make_pair(pair, SDValue());
13340 // Build the FP_TO_INT*_IN_MEM
13341 SDValue Ops[] = { Chain, Value, StackSlot };
13342 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13344 return std::make_pair(FIST, StackSlot);
13348 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13349 const X86Subtarget *Subtarget) {
13350 MVT VT = Op->getSimpleValueType(0);
13351 SDValue In = Op->getOperand(0);
13352 MVT InVT = In.getSimpleValueType();
13355 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13356 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13358 // Optimize vectors in AVX mode:
13361 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13362 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13363 // Concat upper and lower parts.
13366 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13367 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13368 // Concat upper and lower parts.
13371 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13372 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13373 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13376 if (Subtarget->hasInt256())
13377 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13379 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13380 SDValue Undef = DAG.getUNDEF(InVT);
13381 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13382 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13383 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13385 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13386 VT.getVectorNumElements()/2);
13388 OpLo = DAG.getBitcast(HVT, OpLo);
13389 OpHi = DAG.getBitcast(HVT, OpHi);
13391 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13394 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13395 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13396 MVT VT = Op->getSimpleValueType(0);
13397 SDValue In = Op->getOperand(0);
13398 MVT InVT = In.getSimpleValueType();
13400 unsigned int NumElts = VT.getVectorNumElements();
13401 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13404 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13405 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13407 assert(InVT.getVectorElementType() == MVT::i1);
13408 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13410 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13412 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13414 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13415 if (VT.is512BitVector())
13417 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13420 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13421 SelectionDAG &DAG) {
13422 if (Subtarget->hasFp256())
13423 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13429 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13430 SelectionDAG &DAG) {
13432 MVT VT = Op.getSimpleValueType();
13433 SDValue In = Op.getOperand(0);
13434 MVT SVT = In.getSimpleValueType();
13436 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13437 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13439 if (Subtarget->hasFp256())
13440 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13443 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13444 VT.getVectorNumElements() != SVT.getVectorNumElements());
13448 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13449 const X86Subtarget *Subtarget) {
13452 MVT VT = Op.getSimpleValueType();
13453 SDValue In = Op.getOperand(0);
13454 MVT InVT = In.getSimpleValueType();
13456 assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13458 // Shift LSB to MSB and use VPMOVB2M - SKX.
13459 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13460 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13461 Subtarget->hasBWI()) || // legal, will go to VPMOVB2M, VPMOVW2M
13462 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13463 InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13464 Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13465 // Shift packed bytes not supported natively, bitcast to dword
13466 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13467 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13468 DAG.getBitcast(ExtVT, In),
13469 DAG.getConstant(ShiftInx, DL, ExtVT));
13470 ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13471 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13473 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13474 Subtarget->hasDQI()) || // legal, will go to VPMOVD2M, VPMOVQ2M
13475 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13476 InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13477 Subtarget->hasVLX())) { // legal, will go to VPMOVD2M, VPMOVQ2M
13479 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13480 DAG.getConstant(ShiftInx, DL, InVT));
13481 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13484 // Shift LSB to MSB, extend if necessary and use TESTM.
13485 unsigned NumElts = InVT.getVectorNumElements();
13486 if (InVT.getSizeInBits() < 512 &&
13487 (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13488 !Subtarget->hasVLX())) {
13489 assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13491 // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13492 // so vector should be extended to packed dword/qword.
13493 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13494 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13496 ShiftInx = InVT.getScalarSizeInBits() - 1;
13499 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13500 DAG.getConstant(ShiftInx, DL, InVT));
13501 return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13504 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13506 MVT VT = Op.getSimpleValueType();
13507 SDValue In = Op.getOperand(0);
13508 MVT InVT = In.getSimpleValueType();
13510 if (VT == MVT::i1) {
13511 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13512 "Invalid scalar TRUNCATE operation");
13513 if (InVT.getSizeInBits() >= 32)
13515 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13516 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13518 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13519 "Invalid TRUNCATE operation");
13521 if (VT.getVectorElementType() == MVT::i1)
13522 return LowerTruncateVecI1(Op, DAG, Subtarget);
13524 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13525 if (Subtarget->hasAVX512()) {
13526 // word to byte only under BWI
13527 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13528 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13529 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13530 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13532 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13533 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13534 if (Subtarget->hasInt256()) {
13535 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13536 In = DAG.getBitcast(MVT::v8i32, In);
13537 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13539 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13540 DAG.getIntPtrConstant(0, DL));
13543 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13544 DAG.getIntPtrConstant(0, DL));
13545 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13546 DAG.getIntPtrConstant(2, DL));
13547 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13548 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13549 static const int ShufMask[] = {0, 2, 4, 6};
13550 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13553 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13554 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13555 if (Subtarget->hasInt256()) {
13556 In = DAG.getBitcast(MVT::v32i8, In);
13558 SmallVector<SDValue,32> pshufbMask;
13559 for (unsigned i = 0; i < 2; ++i) {
13560 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13561 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13562 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13563 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13564 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13565 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13566 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13567 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13568 for (unsigned j = 0; j < 8; ++j)
13569 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13571 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13572 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13573 In = DAG.getBitcast(MVT::v4i64, In);
13575 static const int ShufMask[] = {0, 2, -1, -1};
13576 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13578 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13579 DAG.getIntPtrConstant(0, DL));
13580 return DAG.getBitcast(VT, In);
13583 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13584 DAG.getIntPtrConstant(0, DL));
13586 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13587 DAG.getIntPtrConstant(4, DL));
13589 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13590 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13592 // The PSHUFB mask:
13593 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13594 -1, -1, -1, -1, -1, -1, -1, -1};
13596 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13597 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13598 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13600 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13601 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13603 // The MOVLHPS Mask:
13604 static const int ShufMask2[] = {0, 1, 4, 5};
13605 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13606 return DAG.getBitcast(MVT::v8i16, res);
13609 // Handle truncation of V256 to V128 using shuffles.
13610 if (!VT.is128BitVector() || !InVT.is256BitVector())
13613 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13615 unsigned NumElems = VT.getVectorNumElements();
13616 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13618 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13619 // Prepare truncation shuffle mask
13620 for (unsigned i = 0; i != NumElems; ++i)
13621 MaskVec[i] = i * 2;
13622 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13623 DAG.getUNDEF(NVT), &MaskVec[0]);
13624 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13625 DAG.getIntPtrConstant(0, DL));
13628 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13629 SelectionDAG &DAG) const {
13630 assert(!Op.getSimpleValueType().isVector());
13632 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13633 /*IsSigned=*/ true, /*IsReplace=*/ false);
13634 SDValue FIST = Vals.first, StackSlot = Vals.second;
13635 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13636 if (!FIST.getNode())
13639 if (StackSlot.getNode())
13640 // Load the result.
13641 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13642 FIST, StackSlot, MachinePointerInfo(),
13643 false, false, false, 0);
13645 // The node is the result.
13649 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13650 SelectionDAG &DAG) const {
13651 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13652 /*IsSigned=*/ false, /*IsReplace=*/ false);
13653 SDValue FIST = Vals.first, StackSlot = Vals.second;
13654 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13655 if (!FIST.getNode())
13658 if (StackSlot.getNode())
13659 // Load the result.
13660 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13661 FIST, StackSlot, MachinePointerInfo(),
13662 false, false, false, 0);
13664 // The node is the result.
13668 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13670 MVT VT = Op.getSimpleValueType();
13671 SDValue In = Op.getOperand(0);
13672 MVT SVT = In.getSimpleValueType();
13674 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13676 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13677 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13678 In, DAG.getUNDEF(SVT)));
13681 /// The only differences between FABS and FNEG are the mask and the logic op.
13682 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13683 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13684 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13685 "Wrong opcode for lowering FABS or FNEG.");
13687 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13689 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13690 // into an FNABS. We'll lower the FABS after that if it is still in use.
13692 for (SDNode *User : Op->uses())
13693 if (User->getOpcode() == ISD::FNEG)
13697 MVT VT = Op.getSimpleValueType();
13699 bool IsF128 = (VT == MVT::f128);
13701 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13702 // decide if we should generate a 16-byte constant mask when we only need 4 or
13703 // 8 bytes for the scalar case.
13709 if (VT.isVector()) {
13711 EltVT = VT.getVectorElementType();
13712 NumElts = VT.getVectorNumElements();
13713 } else if (IsF128) {
13714 // SSE instructions are used for optimized f128 logical operations.
13715 LogicVT = MVT::f128;
13719 // There are no scalar bitwise logical SSE/AVX instructions, so we
13720 // generate a 16-byte vector constant and logic op even for the scalar case.
13721 // Using a 16-byte mask allows folding the load of the mask with
13722 // the logic op, so it can save (~4 bytes) on code size.
13723 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13725 NumElts = (VT == MVT::f64) ? 2 : 4;
13728 unsigned EltBits = EltVT.getSizeInBits();
13729 LLVMContext *Context = DAG.getContext();
13730 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13732 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13733 Constant *C = ConstantInt::get(*Context, MaskElt);
13734 C = ConstantVector::getSplat(NumElts, C);
13735 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13736 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13737 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13739 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13740 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13741 false, false, false, Alignment);
13743 SDValue Op0 = Op.getOperand(0);
13744 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13746 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13747 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13749 if (VT.isVector() || IsF128)
13750 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13752 // For the scalar case extend to a 128-bit vector, perform the logic op,
13753 // and extract the scalar result back out.
13754 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13755 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13756 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13757 DAG.getIntPtrConstant(0, dl));
13760 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13762 LLVMContext *Context = DAG.getContext();
13763 SDValue Op0 = Op.getOperand(0);
13764 SDValue Op1 = Op.getOperand(1);
13766 MVT VT = Op.getSimpleValueType();
13767 MVT SrcVT = Op1.getSimpleValueType();
13768 bool IsF128 = (VT == MVT::f128);
13770 // If second operand is smaller, extend it first.
13771 if (SrcVT.bitsLT(VT)) {
13772 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13775 // And if it is bigger, shrink it first.
13776 if (SrcVT.bitsGT(VT)) {
13777 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13781 // At this point the operands and the result should have the same
13782 // type, and that won't be f80 since that is not custom lowered.
13783 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13784 "Unexpected type in LowerFCOPYSIGN");
13786 const fltSemantics &Sem =
13787 VT == MVT::f64 ? APFloat::IEEEdouble :
13788 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13789 const unsigned SizeInBits = VT.getSizeInBits();
13791 SmallVector<Constant *, 4> CV(
13792 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13793 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13795 // First, clear all bits but the sign bit from the second operand (sign).
13796 CV[0] = ConstantFP::get(*Context,
13797 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13798 Constant *C = ConstantVector::get(CV);
13799 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13800 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13802 // Perform all logic operations as 16-byte vectors because there are no
13803 // scalar FP logic instructions in SSE. This allows load folding of the
13804 // constants into the logic instructions.
13805 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13807 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13808 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13809 false, false, false, 16);
13811 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13812 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13814 // Next, clear the sign bit from the first operand (magnitude).
13815 // If it's a constant, we can clear it here.
13816 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13817 APFloat APF = Op0CN->getValueAPF();
13818 // If the magnitude is a positive zero, the sign bit alone is enough.
13819 if (APF.isPosZero())
13820 return IsF128 ? SignBit :
13821 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13822 DAG.getIntPtrConstant(0, dl));
13824 CV[0] = ConstantFP::get(*Context, APF);
13826 CV[0] = ConstantFP::get(
13828 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13830 C = ConstantVector::get(CV);
13831 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13833 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13834 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13835 false, false, false, 16);
13836 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13837 if (!isa<ConstantFPSDNode>(Op0)) {
13839 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13840 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13842 // OR the magnitude value with the sign bit.
13843 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13844 return IsF128 ? Val :
13845 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13846 DAG.getIntPtrConstant(0, dl));
13849 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13850 SDValue N0 = Op.getOperand(0);
13852 MVT VT = Op.getSimpleValueType();
13854 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13855 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13856 DAG.getConstant(1, dl, VT));
13857 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13860 // Check whether an OR'd tree is PTEST-able.
13861 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13862 SelectionDAG &DAG) {
13863 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13865 if (!Subtarget->hasSSE41())
13868 if (!Op->hasOneUse())
13871 SDNode *N = Op.getNode();
13874 SmallVector<SDValue, 8> Opnds;
13875 DenseMap<SDValue, unsigned> VecInMap;
13876 SmallVector<SDValue, 8> VecIns;
13877 EVT VT = MVT::Other;
13879 // Recognize a special case where a vector is casted into wide integer to
13881 Opnds.push_back(N->getOperand(0));
13882 Opnds.push_back(N->getOperand(1));
13884 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13885 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13886 // BFS traverse all OR'd operands.
13887 if (I->getOpcode() == ISD::OR) {
13888 Opnds.push_back(I->getOperand(0));
13889 Opnds.push_back(I->getOperand(1));
13890 // Re-evaluate the number of nodes to be traversed.
13891 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13895 // Quit if a non-EXTRACT_VECTOR_ELT
13896 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13899 // Quit if without a constant index.
13900 SDValue Idx = I->getOperand(1);
13901 if (!isa<ConstantSDNode>(Idx))
13904 SDValue ExtractedFromVec = I->getOperand(0);
13905 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13906 if (M == VecInMap.end()) {
13907 VT = ExtractedFromVec.getValueType();
13908 // Quit if not 128/256-bit vector.
13909 if (!VT.is128BitVector() && !VT.is256BitVector())
13911 // Quit if not the same type.
13912 if (VecInMap.begin() != VecInMap.end() &&
13913 VT != VecInMap.begin()->first.getValueType())
13915 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13916 VecIns.push_back(ExtractedFromVec);
13918 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13921 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13922 "Not extracted from 128-/256-bit vector.");
13924 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13926 for (DenseMap<SDValue, unsigned>::const_iterator
13927 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13928 // Quit if not all elements are used.
13929 if (I->second != FullMask)
13933 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13935 // Cast all vectors into TestVT for PTEST.
13936 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13937 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13939 // If more than one full vectors are evaluated, OR them first before PTEST.
13940 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13941 // Each iteration will OR 2 nodes and append the result until there is only
13942 // 1 node left, i.e. the final OR'd value of all vectors.
13943 SDValue LHS = VecIns[Slot];
13944 SDValue RHS = VecIns[Slot + 1];
13945 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13948 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13949 VecIns.back(), VecIns.back());
13952 /// \brief return true if \c Op has a use that doesn't just read flags.
13953 static bool hasNonFlagsUse(SDValue Op) {
13954 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13956 SDNode *User = *UI;
13957 unsigned UOpNo = UI.getOperandNo();
13958 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13959 // Look pass truncate.
13960 UOpNo = User->use_begin().getOperandNo();
13961 User = *User->use_begin();
13964 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13965 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13971 /// Emit nodes that will be selected as "test Op0,Op0", or something
13973 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13974 SelectionDAG &DAG) const {
13975 if (Op.getValueType() == MVT::i1) {
13976 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13977 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13978 DAG.getConstant(0, dl, MVT::i8));
13980 // CF and OF aren't always set the way we want. Determine which
13981 // of these we need.
13982 bool NeedCF = false;
13983 bool NeedOF = false;
13986 case X86::COND_A: case X86::COND_AE:
13987 case X86::COND_B: case X86::COND_BE:
13990 case X86::COND_G: case X86::COND_GE:
13991 case X86::COND_L: case X86::COND_LE:
13992 case X86::COND_O: case X86::COND_NO: {
13993 // Check if we really need to set the
13994 // Overflow flag. If NoSignedWrap is present
13995 // that is not actually needed.
13996 switch (Op->getOpcode()) {
14001 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14002 if (BinNode->Flags.hasNoSignedWrap())
14012 // See if we can use the EFLAGS value from the operand instead of
14013 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14014 // we prove that the arithmetic won't overflow, we can't use OF or CF.
14015 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14016 // Emit a CMP with 0, which is the TEST pattern.
14017 //if (Op.getValueType() == MVT::i1)
14018 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
14019 // DAG.getConstant(0, MVT::i1));
14020 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14021 DAG.getConstant(0, dl, Op.getValueType()));
14023 unsigned Opcode = 0;
14024 unsigned NumOperands = 0;
14026 // Truncate operations may prevent the merge of the SETCC instruction
14027 // and the arithmetic instruction before it. Attempt to truncate the operands
14028 // of the arithmetic instruction and use a reduced bit-width instruction.
14029 bool NeedTruncation = false;
14030 SDValue ArithOp = Op;
14031 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14032 SDValue Arith = Op->getOperand(0);
14033 // Both the trunc and the arithmetic op need to have one user each.
14034 if (Arith->hasOneUse())
14035 switch (Arith.getOpcode()) {
14042 NeedTruncation = true;
14048 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14049 // which may be the result of a CAST. We use the variable 'Op', which is the
14050 // non-casted variable when we check for possible users.
14051 switch (ArithOp.getOpcode()) {
14053 // Due to an isel shortcoming, be conservative if this add is likely to be
14054 // selected as part of a load-modify-store instruction. When the root node
14055 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14056 // uses of other nodes in the match, such as the ADD in this case. This
14057 // leads to the ADD being left around and reselected, with the result being
14058 // two adds in the output. Alas, even if none our users are stores, that
14059 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14060 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14061 // climbing the DAG back to the root, and it doesn't seem to be worth the
14063 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14064 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14065 if (UI->getOpcode() != ISD::CopyToReg &&
14066 UI->getOpcode() != ISD::SETCC &&
14067 UI->getOpcode() != ISD::STORE)
14070 if (ConstantSDNode *C =
14071 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14072 // An add of one will be selected as an INC.
14073 if (C->isOne() && !Subtarget->slowIncDec()) {
14074 Opcode = X86ISD::INC;
14079 // An add of negative one (subtract of one) will be selected as a DEC.
14080 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14081 Opcode = X86ISD::DEC;
14087 // Otherwise use a regular EFLAGS-setting add.
14088 Opcode = X86ISD::ADD;
14093 // If we have a constant logical shift that's only used in a comparison
14094 // against zero turn it into an equivalent AND. This allows turning it into
14095 // a TEST instruction later.
14096 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14097 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14098 EVT VT = Op.getValueType();
14099 unsigned BitWidth = VT.getSizeInBits();
14100 unsigned ShAmt = Op->getConstantOperandVal(1);
14101 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14103 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14104 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14105 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14106 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14108 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14109 DAG.getConstant(Mask, dl, VT));
14110 DAG.ReplaceAllUsesWith(Op, New);
14116 // If the primary and result isn't used, don't bother using X86ISD::AND,
14117 // because a TEST instruction will be better.
14118 if (!hasNonFlagsUse(Op))
14124 // Due to the ISEL shortcoming noted above, be conservative if this op is
14125 // likely to be selected as part of a load-modify-store instruction.
14126 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14127 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14128 if (UI->getOpcode() == ISD::STORE)
14131 // Otherwise use a regular EFLAGS-setting instruction.
14132 switch (ArithOp.getOpcode()) {
14133 default: llvm_unreachable("unexpected operator!");
14134 case ISD::SUB: Opcode = X86ISD::SUB; break;
14135 case ISD::XOR: Opcode = X86ISD::XOR; break;
14136 case ISD::AND: Opcode = X86ISD::AND; break;
14138 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14139 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14140 if (EFLAGS.getNode())
14143 Opcode = X86ISD::OR;
14157 return SDValue(Op.getNode(), 1);
14163 // If we found that truncation is beneficial, perform the truncation and
14165 if (NeedTruncation) {
14166 EVT VT = Op.getValueType();
14167 SDValue WideVal = Op->getOperand(0);
14168 EVT WideVT = WideVal.getValueType();
14169 unsigned ConvertedOp = 0;
14170 // Use a target machine opcode to prevent further DAGCombine
14171 // optimizations that may separate the arithmetic operations
14172 // from the setcc node.
14173 switch (WideVal.getOpcode()) {
14175 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14176 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14177 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14178 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14179 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14183 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14184 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14185 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14186 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14187 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14193 // Emit a CMP with 0, which is the TEST pattern.
14194 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14195 DAG.getConstant(0, dl, Op.getValueType()));
14197 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14198 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14200 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14201 DAG.ReplaceAllUsesWith(Op, New);
14202 return SDValue(New.getNode(), 1);
14205 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14207 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14208 SDLoc dl, SelectionDAG &DAG) const {
14209 if (isNullConstant(Op1))
14210 return EmitTest(Op0, X86CC, dl, DAG);
14212 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14213 "Unexpected comparison operation for MVT::i1 operands");
14215 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14216 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14217 // Do the comparison at i32 if it's smaller, besides the Atom case.
14218 // This avoids subregister aliasing issues. Keep the smaller reference
14219 // if we're optimizing for size, however, as that'll allow better folding
14220 // of memory operations.
14221 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14222 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14223 !Subtarget->isAtom()) {
14224 unsigned ExtendOp =
14225 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14226 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14227 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14229 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14230 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14231 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14233 return SDValue(Sub.getNode(), 1);
14235 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14238 /// Convert a comparison if required by the subtarget.
14239 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14240 SelectionDAG &DAG) const {
14241 // If the subtarget does not support the FUCOMI instruction, floating-point
14242 // comparisons have to be converted.
14243 if (Subtarget->hasCMov() ||
14244 Cmp.getOpcode() != X86ISD::CMP ||
14245 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14246 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14249 // The instruction selector will select an FUCOM instruction instead of
14250 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14251 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14252 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14254 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14255 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14256 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14257 DAG.getConstant(8, dl, MVT::i8));
14258 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14260 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14261 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14262 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14265 /// The minimum architected relative accuracy is 2^-12. We need one
14266 /// Newton-Raphson step to have a good float result (24 bits of precision).
14267 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14268 DAGCombinerInfo &DCI,
14269 unsigned &RefinementSteps,
14270 bool &UseOneConstNR) const {
14271 EVT VT = Op.getValueType();
14272 const char *RecipOp;
14274 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14275 // TODO: Add support for AVX512 (v16f32).
14276 // It is likely not profitable to do this for f64 because a double-precision
14277 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14278 // instructions: convert to single, rsqrtss, convert back to double, refine
14279 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14280 // along with FMA, this could be a throughput win.
14281 if (VT == MVT::f32 && Subtarget->hasSSE1())
14283 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14284 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14285 RecipOp = "vec-sqrtf";
14289 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14290 if (!Recips.isEnabled(RecipOp))
14293 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14294 UseOneConstNR = false;
14295 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14298 /// The minimum architected relative accuracy is 2^-12. We need one
14299 /// Newton-Raphson step to have a good float result (24 bits of precision).
14300 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14301 DAGCombinerInfo &DCI,
14302 unsigned &RefinementSteps) const {
14303 EVT VT = Op.getValueType();
14304 const char *RecipOp;
14306 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14307 // TODO: Add support for AVX512 (v16f32).
14308 // It is likely not profitable to do this for f64 because a double-precision
14309 // reciprocal estimate with refinement on x86 prior to FMA requires
14310 // 15 instructions: convert to single, rcpss, convert back to double, refine
14311 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14312 // along with FMA, this could be a throughput win.
14313 if (VT == MVT::f32 && Subtarget->hasSSE1())
14315 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14316 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14317 RecipOp = "vec-divf";
14321 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14322 if (!Recips.isEnabled(RecipOp))
14325 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14326 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14329 /// If we have at least two divisions that use the same divisor, convert to
14330 /// multplication by a reciprocal. This may need to be adjusted for a given
14331 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14332 /// This is because we still need one division to calculate the reciprocal and
14333 /// then we need two multiplies by that reciprocal as replacements for the
14334 /// original divisions.
14335 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14339 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14340 /// if it's possible.
14341 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14342 SDLoc dl, SelectionDAG &DAG) const {
14343 SDValue Op0 = And.getOperand(0);
14344 SDValue Op1 = And.getOperand(1);
14345 if (Op0.getOpcode() == ISD::TRUNCATE)
14346 Op0 = Op0.getOperand(0);
14347 if (Op1.getOpcode() == ISD::TRUNCATE)
14348 Op1 = Op1.getOperand(0);
14351 if (Op1.getOpcode() == ISD::SHL)
14352 std::swap(Op0, Op1);
14353 if (Op0.getOpcode() == ISD::SHL) {
14354 if (isOneConstant(Op0.getOperand(0))) {
14355 // If we looked past a truncate, check that it's only truncating away
14357 unsigned BitWidth = Op0.getValueSizeInBits();
14358 unsigned AndBitWidth = And.getValueSizeInBits();
14359 if (BitWidth > AndBitWidth) {
14361 DAG.computeKnownBits(Op0, Zeros, Ones);
14362 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14366 RHS = Op0.getOperand(1);
14368 } else if (Op1.getOpcode() == ISD::Constant) {
14369 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14370 uint64_t AndRHSVal = AndRHS->getZExtValue();
14371 SDValue AndLHS = Op0;
14373 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14374 LHS = AndLHS.getOperand(0);
14375 RHS = AndLHS.getOperand(1);
14378 // Use BT if the immediate can't be encoded in a TEST instruction.
14379 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14381 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14385 if (LHS.getNode()) {
14386 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14387 // instruction. Since the shift amount is in-range-or-undefined, we know
14388 // that doing a bittest on the i32 value is ok. We extend to i32 because
14389 // the encoding for the i16 version is larger than the i32 version.
14390 // Also promote i16 to i32 for performance / code size reason.
14391 if (LHS.getValueType() == MVT::i8 ||
14392 LHS.getValueType() == MVT::i16)
14393 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14395 // If the operand types disagree, extend the shift amount to match. Since
14396 // BT ignores high bits (like shifts) we can use anyextend.
14397 if (LHS.getValueType() != RHS.getValueType())
14398 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14400 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14401 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14402 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14403 DAG.getConstant(Cond, dl, MVT::i8), BT);
14409 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14411 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14416 // SSE Condition code mapping:
14425 switch (SetCCOpcode) {
14426 default: llvm_unreachable("Unexpected SETCC condition");
14428 case ISD::SETEQ: SSECC = 0; break;
14430 case ISD::SETGT: Swap = true; // Fallthrough
14432 case ISD::SETOLT: SSECC = 1; break;
14434 case ISD::SETGE: Swap = true; // Fallthrough
14436 case ISD::SETOLE: SSECC = 2; break;
14437 case ISD::SETUO: SSECC = 3; break;
14439 case ISD::SETNE: SSECC = 4; break;
14440 case ISD::SETULE: Swap = true; // Fallthrough
14441 case ISD::SETUGE: SSECC = 5; break;
14442 case ISD::SETULT: Swap = true; // Fallthrough
14443 case ISD::SETUGT: SSECC = 6; break;
14444 case ISD::SETO: SSECC = 7; break;
14446 case ISD::SETONE: SSECC = 8; break;
14449 std::swap(Op0, Op1);
14454 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14455 // ones, and then concatenate the result back.
14456 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14457 MVT VT = Op.getSimpleValueType();
14459 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14460 "Unsupported value type for operation");
14462 unsigned NumElems = VT.getVectorNumElements();
14464 SDValue CC = Op.getOperand(2);
14466 // Extract the LHS vectors
14467 SDValue LHS = Op.getOperand(0);
14468 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14469 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14471 // Extract the RHS vectors
14472 SDValue RHS = Op.getOperand(1);
14473 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14474 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14476 // Issue the operation on the smaller types and concatenate the result back
14477 MVT EltVT = VT.getVectorElementType();
14478 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14479 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14480 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14481 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14484 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14485 SDValue Op0 = Op.getOperand(0);
14486 SDValue Op1 = Op.getOperand(1);
14487 SDValue CC = Op.getOperand(2);
14488 MVT VT = Op.getSimpleValueType();
14491 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14492 "Unexpected type for boolean compare operation");
14493 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14494 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14495 DAG.getConstant(-1, dl, VT));
14496 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14497 DAG.getConstant(-1, dl, VT));
14498 switch (SetCCOpcode) {
14499 default: llvm_unreachable("Unexpected SETCC condition");
14501 // (x == y) -> ~(x ^ y)
14502 return DAG.getNode(ISD::XOR, dl, VT,
14503 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14504 DAG.getConstant(-1, dl, VT));
14506 // (x != y) -> (x ^ y)
14507 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14510 // (x > y) -> (x & ~y)
14511 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14514 // (x < y) -> (~x & y)
14515 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14518 // (x <= y) -> (~x | y)
14519 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14522 // (x >=y) -> (x | ~y)
14523 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14527 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14528 const X86Subtarget *Subtarget) {
14529 SDValue Op0 = Op.getOperand(0);
14530 SDValue Op1 = Op.getOperand(1);
14531 SDValue CC = Op.getOperand(2);
14532 MVT VT = Op.getSimpleValueType();
14535 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14536 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14537 "Cannot set masked compare for this operation");
14539 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14541 bool Unsigned = false;
14544 switch (SetCCOpcode) {
14545 default: llvm_unreachable("Unexpected SETCC condition");
14546 case ISD::SETNE: SSECC = 4; break;
14547 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14548 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14549 case ISD::SETLT: Swap = true; //fall-through
14550 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14551 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14552 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14553 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14554 case ISD::SETULE: Unsigned = true; //fall-through
14555 case ISD::SETLE: SSECC = 2; break;
14559 std::swap(Op0, Op1);
14561 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14562 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14563 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14564 DAG.getConstant(SSECC, dl, MVT::i8));
14567 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14568 /// operand \p Op1. If non-trivial (for example because it's not constant)
14569 /// return an empty value.
14570 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14572 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14576 MVT VT = Op1.getSimpleValueType();
14577 MVT EVT = VT.getVectorElementType();
14578 unsigned n = VT.getVectorNumElements();
14579 SmallVector<SDValue, 8> ULTOp1;
14581 for (unsigned i = 0; i < n; ++i) {
14582 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14583 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14586 // Avoid underflow.
14587 APInt Val = Elt->getAPIntValue();
14591 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14594 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14597 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14598 SelectionDAG &DAG) {
14599 SDValue Op0 = Op.getOperand(0);
14600 SDValue Op1 = Op.getOperand(1);
14601 SDValue CC = Op.getOperand(2);
14602 MVT VT = Op.getSimpleValueType();
14603 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14604 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14609 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14610 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14613 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14614 unsigned Opc = X86ISD::CMPP;
14615 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14616 assert(VT.getVectorNumElements() <= 16);
14617 Opc = X86ISD::CMPM;
14619 // In the two special cases we can't handle, emit two comparisons.
14622 unsigned CombineOpc;
14623 if (SetCCOpcode == ISD::SETUEQ) {
14624 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14626 assert(SetCCOpcode == ISD::SETONE);
14627 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14630 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14631 DAG.getConstant(CC0, dl, MVT::i8));
14632 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14633 DAG.getConstant(CC1, dl, MVT::i8));
14634 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14636 // Handle all other FP comparisons here.
14637 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14638 DAG.getConstant(SSECC, dl, MVT::i8));
14641 MVT VTOp0 = Op0.getSimpleValueType();
14642 assert(VTOp0 == Op1.getSimpleValueType() &&
14643 "Expected operands with same type!");
14644 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14645 "Invalid number of packed elements for source and destination!");
14647 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14648 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14649 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14650 // legalizer firstly checks if the first operand in input to the setcc has
14651 // a legal type. If so, then it promotes the return type to that same type.
14652 // Otherwise, the return type is promoted to the 'next legal type' which,
14653 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14655 // We reach this code only if the following two conditions are met:
14656 // 1. Both return type and operand type have been promoted to wider types
14657 // by the type legalizer.
14658 // 2. The original operand type has been promoted to a 256-bit vector.
14660 // Note that condition 2. only applies for AVX targets.
14661 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14662 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14665 // The non-AVX512 code below works under the assumption that source and
14666 // destination types are the same.
14667 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14668 "Value types for source and destination must be the same!");
14670 // Break 256-bit integer vector compare into smaller ones.
14671 if (VT.is256BitVector() && !Subtarget->hasInt256())
14672 return Lower256IntVSETCC(Op, DAG);
14674 MVT OpVT = Op1.getSimpleValueType();
14675 if (OpVT.getVectorElementType() == MVT::i1)
14676 return LowerBoolVSETCC_AVX512(Op, DAG);
14678 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14679 if (Subtarget->hasAVX512()) {
14680 if (Op1.getSimpleValueType().is512BitVector() ||
14681 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14682 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14683 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14685 // In AVX-512 architecture setcc returns mask with i1 elements,
14686 // But there is no compare instruction for i8 and i16 elements in KNL.
14687 // We are not talking about 512-bit operands in this case, these
14688 // types are illegal.
14690 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14691 OpVT.getVectorElementType().getSizeInBits() >= 8))
14692 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14693 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14696 // Lower using XOP integer comparisons.
14697 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14698 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14699 // Translate compare code to XOP PCOM compare mode.
14700 unsigned CmpMode = 0;
14701 switch (SetCCOpcode) {
14702 default: llvm_unreachable("Unexpected SETCC condition");
14704 case ISD::SETLT: CmpMode = 0x00; break;
14706 case ISD::SETLE: CmpMode = 0x01; break;
14708 case ISD::SETGT: CmpMode = 0x02; break;
14710 case ISD::SETGE: CmpMode = 0x03; break;
14711 case ISD::SETEQ: CmpMode = 0x04; break;
14712 case ISD::SETNE: CmpMode = 0x05; break;
14715 // Are we comparing unsigned or signed integers?
14716 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14717 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14719 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14720 DAG.getConstant(CmpMode, dl, MVT::i8));
14723 // We are handling one of the integer comparisons here. Since SSE only has
14724 // GT and EQ comparisons for integer, swapping operands and multiple
14725 // operations may be required for some comparisons.
14727 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14728 bool Subus = false;
14730 switch (SetCCOpcode) {
14731 default: llvm_unreachable("Unexpected SETCC condition");
14732 case ISD::SETNE: Invert = true;
14733 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14734 case ISD::SETLT: Swap = true;
14735 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14736 case ISD::SETGE: Swap = true;
14737 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14738 Invert = true; break;
14739 case ISD::SETULT: Swap = true;
14740 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14741 FlipSigns = true; break;
14742 case ISD::SETUGE: Swap = true;
14743 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14744 FlipSigns = true; Invert = true; break;
14747 // Special case: Use min/max operations for SETULE/SETUGE
14748 MVT VET = VT.getVectorElementType();
14750 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14751 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14754 switch (SetCCOpcode) {
14756 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14757 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14760 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14763 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14764 if (!MinMax && hasSubus) {
14765 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14767 // t = psubus Op0, Op1
14768 // pcmpeq t, <0..0>
14769 switch (SetCCOpcode) {
14771 case ISD::SETULT: {
14772 // If the comparison is against a constant we can turn this into a
14773 // setule. With psubus, setule does not require a swap. This is
14774 // beneficial because the constant in the register is no longer
14775 // destructed as the destination so it can be hoisted out of a loop.
14776 // Only do this pre-AVX since vpcmp* is no longer destructive.
14777 if (Subtarget->hasAVX())
14779 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14780 if (ULEOp1.getNode()) {
14782 Subus = true; Invert = false; Swap = false;
14786 // Psubus is better than flip-sign because it requires no inversion.
14787 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14788 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14792 Opc = X86ISD::SUBUS;
14798 std::swap(Op0, Op1);
14800 // Check that the operation in question is available (most are plain SSE2,
14801 // but PCMPGTQ and PCMPEQQ have different requirements).
14802 if (VT == MVT::v2i64) {
14803 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14804 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14806 // First cast everything to the right type.
14807 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14808 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14810 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14811 // bits of the inputs before performing those operations. The lower
14812 // compare is always unsigned.
14815 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14817 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14818 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14819 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14820 Sign, Zero, Sign, Zero);
14822 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14823 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14825 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14826 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14827 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14829 // Create masks for only the low parts/high parts of the 64 bit integers.
14830 static const int MaskHi[] = { 1, 1, 3, 3 };
14831 static const int MaskLo[] = { 0, 0, 2, 2 };
14832 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14833 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14834 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14836 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14837 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14840 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14842 return DAG.getBitcast(VT, Result);
14845 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14846 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14847 // pcmpeqd + pshufd + pand.
14848 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14850 // First cast everything to the right type.
14851 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14852 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14855 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14857 // Make sure the lower and upper halves are both all-ones.
14858 static const int Mask[] = { 1, 0, 3, 2 };
14859 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14860 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14863 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14865 return DAG.getBitcast(VT, Result);
14869 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14870 // bits of the inputs before performing those operations.
14872 MVT EltVT = VT.getVectorElementType();
14873 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14875 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14876 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14879 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14881 // If the logical-not of the result is required, perform that now.
14883 Result = DAG.getNOT(dl, Result, VT);
14886 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14889 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14890 getZeroVector(VT, Subtarget, DAG, dl));
14895 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14897 MVT VT = Op.getSimpleValueType();
14899 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14901 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14902 && "SetCC type must be 8-bit or 1-bit integer");
14903 SDValue Op0 = Op.getOperand(0);
14904 SDValue Op1 = Op.getOperand(1);
14906 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14908 // Optimize to BT if possible.
14909 // Lower (X & (1 << N)) == 0 to BT(X, N).
14910 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14911 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14912 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14913 isNullConstant(Op1) &&
14914 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14915 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14917 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14922 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14924 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14925 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14927 // If the input is a setcc, then reuse the input setcc or use a new one with
14928 // the inverted condition.
14929 if (Op0.getOpcode() == X86ISD::SETCC) {
14930 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14931 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14935 CCode = X86::GetOppositeBranchCondition(CCode);
14936 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14937 DAG.getConstant(CCode, dl, MVT::i8),
14938 Op0.getOperand(1));
14940 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14944 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14945 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14947 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14948 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14951 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14952 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14953 if (X86CC == X86::COND_INVALID)
14956 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14957 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14958 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14959 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14961 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14965 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14966 SDValue LHS = Op.getOperand(0);
14967 SDValue RHS = Op.getOperand(1);
14968 SDValue Carry = Op.getOperand(2);
14969 SDValue Cond = Op.getOperand(3);
14972 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14973 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14975 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14976 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14977 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14978 return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14979 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14982 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14983 static bool isX86LogicalCmp(SDValue Op) {
14984 unsigned Opc = Op.getNode()->getOpcode();
14985 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14986 Opc == X86ISD::SAHF)
14988 if (Op.getResNo() == 1 &&
14989 (Opc == X86ISD::ADD ||
14990 Opc == X86ISD::SUB ||
14991 Opc == X86ISD::ADC ||
14992 Opc == X86ISD::SBB ||
14993 Opc == X86ISD::SMUL ||
14994 Opc == X86ISD::UMUL ||
14995 Opc == X86ISD::INC ||
14996 Opc == X86ISD::DEC ||
14997 Opc == X86ISD::OR ||
14998 Opc == X86ISD::XOR ||
14999 Opc == X86ISD::AND))
15002 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15008 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15009 if (V.getOpcode() != ISD::TRUNCATE)
15012 SDValue VOp0 = V.getOperand(0);
15013 unsigned InBits = VOp0.getValueSizeInBits();
15014 unsigned Bits = V.getValueSizeInBits();
15015 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
15018 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15019 bool addTest = true;
15020 SDValue Cond = Op.getOperand(0);
15021 SDValue Op1 = Op.getOperand(1);
15022 SDValue Op2 = Op.getOperand(2);
15024 MVT VT = Op1.getSimpleValueType();
15027 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15028 // are available or VBLENDV if AVX is available.
15029 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15030 if (Cond.getOpcode() == ISD::SETCC &&
15031 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15032 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
15033 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15034 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15035 int SSECC = translateX86FSETCC(
15036 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15039 if (Subtarget->hasAVX512()) {
15040 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15041 DAG.getConstant(SSECC, DL, MVT::i8));
15042 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15045 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15046 DAG.getConstant(SSECC, DL, MVT::i8));
15048 // If we have AVX, we can use a variable vector select (VBLENDV) instead
15049 // of 3 logic instructions for size savings and potentially speed.
15050 // Unfortunately, there is no scalar form of VBLENDV.
15052 // If either operand is a constant, don't try this. We can expect to
15053 // optimize away at least one of the logic instructions later in that
15054 // case, so that sequence would be faster than a variable blend.
15056 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15057 // uses XMM0 as the selection register. That may need just as many
15058 // instructions as the AND/ANDN/OR sequence due to register moves, so
15061 if (Subtarget->hasAVX() &&
15062 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15064 // Convert to vectors, do a VSELECT, and convert back to scalar.
15065 // All of the conversions should be optimized away.
15067 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15068 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15069 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15070 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15072 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15073 VCmp = DAG.getBitcast(VCmpVT, VCmp);
15075 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15077 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15078 VSel, DAG.getIntPtrConstant(0, DL));
15080 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15081 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15082 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15086 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15088 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15089 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15090 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15091 Op1Scalar = Op1.getOperand(0);
15093 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15094 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15095 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15096 Op2Scalar = Op2.getOperand(0);
15097 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15098 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15099 Op1Scalar.getValueType(),
15100 Cond, Op1Scalar, Op2Scalar);
15101 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15102 return DAG.getBitcast(VT, newSelect);
15103 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15104 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15105 DAG.getIntPtrConstant(0, DL));
15109 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15110 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15111 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15112 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15113 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15114 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15115 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15117 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15120 if (Cond.getOpcode() == ISD::SETCC) {
15121 SDValue NewCond = LowerSETCC(Cond, DAG);
15122 if (NewCond.getNode())
15126 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15127 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15128 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15129 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15130 if (Cond.getOpcode() == X86ISD::SETCC &&
15131 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15132 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15133 SDValue Cmp = Cond.getOperand(1);
15135 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15137 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15138 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15139 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15141 SDValue CmpOp0 = Cmp.getOperand(0);
15142 // Apply further optimizations for special cases
15143 // (select (x != 0), -1, 0) -> neg & sbb
15144 // (select (x == 0), 0, -1) -> neg & sbb
15145 if (isNullConstant(Y) &&
15146 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15147 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15148 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15149 DAG.getConstant(0, DL,
15150 CmpOp0.getValueType()),
15152 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15153 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15154 SDValue(Neg.getNode(), 1));
15158 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15159 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15160 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15162 SDValue Res = // Res = 0 or -1.
15163 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15164 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15166 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15167 Res = DAG.getNOT(DL, Res, Res.getValueType());
15169 if (!isNullConstant(Op2))
15170 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15175 // Look past (and (setcc_carry (cmp ...)), 1).
15176 if (Cond.getOpcode() == ISD::AND &&
15177 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15178 isOneConstant(Cond.getOperand(1)))
15179 Cond = Cond.getOperand(0);
15181 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15182 // setting operand in place of the X86ISD::SETCC.
15183 unsigned CondOpcode = Cond.getOpcode();
15184 if (CondOpcode == X86ISD::SETCC ||
15185 CondOpcode == X86ISD::SETCC_CARRY) {
15186 CC = Cond.getOperand(0);
15188 SDValue Cmp = Cond.getOperand(1);
15189 unsigned Opc = Cmp.getOpcode();
15190 MVT VT = Op.getSimpleValueType();
15192 bool IllegalFPCMov = false;
15193 if (VT.isFloatingPoint() && !VT.isVector() &&
15194 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15195 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15197 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15198 Opc == X86ISD::BT) { // FIXME
15202 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15203 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15204 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15205 Cond.getOperand(0).getValueType() != MVT::i8)) {
15206 SDValue LHS = Cond.getOperand(0);
15207 SDValue RHS = Cond.getOperand(1);
15208 unsigned X86Opcode;
15211 switch (CondOpcode) {
15212 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15213 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15214 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15215 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15216 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15217 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15218 default: llvm_unreachable("unexpected overflowing operator");
15220 if (CondOpcode == ISD::UMULO)
15221 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15224 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15226 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15228 if (CondOpcode == ISD::UMULO)
15229 Cond = X86Op.getValue(2);
15231 Cond = X86Op.getValue(1);
15233 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15238 // Look past the truncate if the high bits are known zero.
15239 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15240 Cond = Cond.getOperand(0);
15242 // We know the result of AND is compared against zero. Try to match
15244 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15245 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15246 CC = NewSetCC.getOperand(0);
15247 Cond = NewSetCC.getOperand(1);
15254 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15255 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15258 // a < b ? -1 : 0 -> RES = ~setcc_carry
15259 // a < b ? 0 : -1 -> RES = setcc_carry
15260 // a >= b ? -1 : 0 -> RES = setcc_carry
15261 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15262 if (Cond.getOpcode() == X86ISD::SUB) {
15263 Cond = ConvertCmpIfNecessary(Cond, DAG);
15264 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15266 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15267 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15268 (isNullConstant(Op1) || isNullConstant(Op2))) {
15269 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15270 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15272 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15273 return DAG.getNOT(DL, Res, Res.getValueType());
15278 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15279 // widen the cmov and push the truncate through. This avoids introducing a new
15280 // branch during isel and doesn't add any extensions.
15281 if (Op.getValueType() == MVT::i8 &&
15282 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15283 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15284 if (T1.getValueType() == T2.getValueType() &&
15285 // Blacklist CopyFromReg to avoid partial register stalls.
15286 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15287 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15288 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15289 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15293 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15294 // condition is true.
15295 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15296 SDValue Ops[] = { Op2, Op1, CC, Cond };
15297 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15300 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15301 const X86Subtarget *Subtarget,
15302 SelectionDAG &DAG) {
15303 MVT VT = Op->getSimpleValueType(0);
15304 SDValue In = Op->getOperand(0);
15305 MVT InVT = In.getSimpleValueType();
15306 MVT VTElt = VT.getVectorElementType();
15307 MVT InVTElt = InVT.getVectorElementType();
15311 if ((InVTElt == MVT::i1) &&
15312 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15313 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15315 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15316 VTElt.getSizeInBits() <= 16)) ||
15318 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15319 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15321 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15322 VTElt.getSizeInBits() >= 32))))
15323 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15325 unsigned int NumElts = VT.getVectorNumElements();
15327 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15330 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15331 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15332 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15333 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15336 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15337 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15339 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15342 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15344 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15345 if (VT.is512BitVector())
15347 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15350 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15351 const X86Subtarget *Subtarget,
15352 SelectionDAG &DAG) {
15353 SDValue In = Op->getOperand(0);
15354 MVT VT = Op->getSimpleValueType(0);
15355 MVT InVT = In.getSimpleValueType();
15356 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15358 MVT InSVT = InVT.getVectorElementType();
15359 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15361 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15363 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15368 // SSE41 targets can use the pmovsx* instructions directly.
15369 if (Subtarget->hasSSE41())
15370 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15372 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15376 // As SRAI is only available on i16/i32 types, we expand only up to i32
15377 // and handle i64 separately.
15378 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15379 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15380 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15381 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15382 Curr = DAG.getBitcast(CurrVT, Curr);
15385 SDValue SignExt = Curr;
15386 if (CurrVT != InVT) {
15387 unsigned SignExtShift =
15388 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15389 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15390 DAG.getConstant(SignExtShift, dl, MVT::i8));
15396 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15397 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15398 DAG.getConstant(31, dl, MVT::i8));
15399 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15400 return DAG.getBitcast(VT, Ext);
15406 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15407 SelectionDAG &DAG) {
15408 MVT VT = Op->getSimpleValueType(0);
15409 SDValue In = Op->getOperand(0);
15410 MVT InVT = In.getSimpleValueType();
15413 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15414 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15416 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15417 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15418 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15421 if (Subtarget->hasInt256())
15422 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15424 // Optimize vectors in AVX mode
15425 // Sign extend v8i16 to v8i32 and
15428 // Divide input vector into two parts
15429 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15430 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15431 // concat the vectors to original VT
15433 unsigned NumElems = InVT.getVectorNumElements();
15434 SDValue Undef = DAG.getUNDEF(InVT);
15436 SmallVector<int,8> ShufMask1(NumElems, -1);
15437 for (unsigned i = 0; i != NumElems/2; ++i)
15440 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15442 SmallVector<int,8> ShufMask2(NumElems, -1);
15443 for (unsigned i = 0; i != NumElems/2; ++i)
15444 ShufMask2[i] = i + NumElems/2;
15446 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15448 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15449 VT.getVectorNumElements()/2);
15451 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15452 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15454 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15457 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15458 // may emit an illegal shuffle but the expansion is still better than scalar
15459 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15460 // we'll emit a shuffle and a arithmetic shift.
15461 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15462 // TODO: It is possible to support ZExt by zeroing the undef values during
15463 // the shuffle phase or after the shuffle.
15464 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15465 SelectionDAG &DAG) {
15466 MVT RegVT = Op.getSimpleValueType();
15467 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15468 assert(RegVT.isInteger() &&
15469 "We only custom lower integer vector sext loads.");
15471 // Nothing useful we can do without SSE2 shuffles.
15472 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15474 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15476 EVT MemVT = Ld->getMemoryVT();
15477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15478 unsigned RegSz = RegVT.getSizeInBits();
15480 ISD::LoadExtType Ext = Ld->getExtensionType();
15482 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15483 && "Only anyext and sext are currently implemented.");
15484 assert(MemVT != RegVT && "Cannot extend to the same type");
15485 assert(MemVT.isVector() && "Must load a vector from memory");
15487 unsigned NumElems = RegVT.getVectorNumElements();
15488 unsigned MemSz = MemVT.getSizeInBits();
15489 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15491 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15492 // The only way in which we have a legal 256-bit vector result but not the
15493 // integer 256-bit operations needed to directly lower a sextload is if we
15494 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15495 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15496 // correctly legalized. We do this late to allow the canonical form of
15497 // sextload to persist throughout the rest of the DAG combiner -- it wants
15498 // to fold together any extensions it can, and so will fuse a sign_extend
15499 // of an sextload into a sextload targeting a wider value.
15501 if (MemSz == 128) {
15502 // Just switch this to a normal load.
15503 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15504 "it must be a legal 128-bit vector "
15506 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15507 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15508 Ld->isInvariant(), Ld->getAlignment());
15510 assert(MemSz < 128 &&
15511 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15512 // Do an sext load to a 128-bit vector type. We want to use the same
15513 // number of elements, but elements half as wide. This will end up being
15514 // recursively lowered by this routine, but will succeed as we definitely
15515 // have all the necessary features if we're using AVX1.
15517 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15518 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15520 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15521 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15522 Ld->isNonTemporal(), Ld->isInvariant(),
15523 Ld->getAlignment());
15526 // Replace chain users with the new chain.
15527 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15528 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15530 // Finally, do a normal sign-extend to the desired register.
15531 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15534 // All sizes must be a power of two.
15535 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15536 "Non-power-of-two elements are not custom lowered!");
15538 // Attempt to load the original value using scalar loads.
15539 // Find the largest scalar type that divides the total loaded size.
15540 MVT SclrLoadTy = MVT::i8;
15541 for (MVT Tp : MVT::integer_valuetypes()) {
15542 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15547 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15548 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15550 SclrLoadTy = MVT::f64;
15552 // Calculate the number of scalar loads that we need to perform
15553 // in order to load our vector from memory.
15554 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15556 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15557 "Can only lower sext loads with a single scalar load!");
15559 unsigned loadRegZize = RegSz;
15560 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15563 // Represent our vector as a sequence of elements which are the
15564 // largest scalar that we can load.
15565 EVT LoadUnitVecVT = EVT::getVectorVT(
15566 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15568 // Represent the data using the same element type that is stored in
15569 // memory. In practice, we ''widen'' MemVT.
15571 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15572 loadRegZize / MemVT.getScalarSizeInBits());
15574 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15575 "Invalid vector type");
15577 // We can't shuffle using an illegal type.
15578 assert(TLI.isTypeLegal(WideVecVT) &&
15579 "We only lower types that form legal widened vector types");
15581 SmallVector<SDValue, 8> Chains;
15582 SDValue Ptr = Ld->getBasePtr();
15583 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15584 TLI.getPointerTy(DAG.getDataLayout()));
15585 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15587 for (unsigned i = 0; i < NumLoads; ++i) {
15588 // Perform a single load.
15589 SDValue ScalarLoad =
15590 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15591 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15592 Ld->getAlignment());
15593 Chains.push_back(ScalarLoad.getValue(1));
15594 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15595 // another round of DAGCombining.
15597 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15599 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15600 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15602 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15605 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15607 // Bitcast the loaded value to a vector of the original element type, in
15608 // the size of the target vector type.
15609 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15610 unsigned SizeRatio = RegSz / MemSz;
15612 if (Ext == ISD::SEXTLOAD) {
15613 // If we have SSE4.1, we can directly emit a VSEXT node.
15614 if (Subtarget->hasSSE41()) {
15615 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15616 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15620 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15622 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15623 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15625 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15626 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15630 // Redistribute the loaded elements into the different locations.
15631 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15632 for (unsigned i = 0; i != NumElems; ++i)
15633 ShuffleVec[i * SizeRatio] = i;
15635 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15636 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15638 // Bitcast to the requested type.
15639 Shuff = DAG.getBitcast(RegVT, Shuff);
15640 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15644 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15645 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15646 // from the AND / OR.
15647 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15648 Opc = Op.getOpcode();
15649 if (Opc != ISD::OR && Opc != ISD::AND)
15651 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15652 Op.getOperand(0).hasOneUse() &&
15653 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15654 Op.getOperand(1).hasOneUse());
15657 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15658 // 1 and that the SETCC node has a single use.
15659 static bool isXor1OfSetCC(SDValue Op) {
15660 if (Op.getOpcode() != ISD::XOR)
15662 if (isOneConstant(Op.getOperand(1)))
15663 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15664 Op.getOperand(0).hasOneUse();
15668 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15669 bool addTest = true;
15670 SDValue Chain = Op.getOperand(0);
15671 SDValue Cond = Op.getOperand(1);
15672 SDValue Dest = Op.getOperand(2);
15675 bool Inverted = false;
15677 if (Cond.getOpcode() == ISD::SETCC) {
15678 // Check for setcc([su]{add,sub,mul}o == 0).
15679 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15680 isNullConstant(Cond.getOperand(1)) &&
15681 Cond.getOperand(0).getResNo() == 1 &&
15682 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15683 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15684 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15685 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15686 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15687 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15689 Cond = Cond.getOperand(0);
15691 SDValue NewCond = LowerSETCC(Cond, DAG);
15692 if (NewCond.getNode())
15697 // FIXME: LowerXALUO doesn't handle these!!
15698 else if (Cond.getOpcode() == X86ISD::ADD ||
15699 Cond.getOpcode() == X86ISD::SUB ||
15700 Cond.getOpcode() == X86ISD::SMUL ||
15701 Cond.getOpcode() == X86ISD::UMUL)
15702 Cond = LowerXALUO(Cond, DAG);
15705 // Look pass (and (setcc_carry (cmp ...)), 1).
15706 if (Cond.getOpcode() == ISD::AND &&
15707 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15708 isOneConstant(Cond.getOperand(1)))
15709 Cond = Cond.getOperand(0);
15711 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15712 // setting operand in place of the X86ISD::SETCC.
15713 unsigned CondOpcode = Cond.getOpcode();
15714 if (CondOpcode == X86ISD::SETCC ||
15715 CondOpcode == X86ISD::SETCC_CARRY) {
15716 CC = Cond.getOperand(0);
15718 SDValue Cmp = Cond.getOperand(1);
15719 unsigned Opc = Cmp.getOpcode();
15720 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15721 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15725 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15729 // These can only come from an arithmetic instruction with overflow,
15730 // e.g. SADDO, UADDO.
15731 Cond = Cond.getNode()->getOperand(1);
15737 CondOpcode = Cond.getOpcode();
15738 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15739 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15740 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15741 Cond.getOperand(0).getValueType() != MVT::i8)) {
15742 SDValue LHS = Cond.getOperand(0);
15743 SDValue RHS = Cond.getOperand(1);
15744 unsigned X86Opcode;
15747 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15748 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15750 switch (CondOpcode) {
15751 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15753 if (isOneConstant(RHS)) {
15754 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15757 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15758 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15760 if (isOneConstant(RHS)) {
15761 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15764 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15765 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15766 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15767 default: llvm_unreachable("unexpected overflowing operator");
15770 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15771 if (CondOpcode == ISD::UMULO)
15772 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15775 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15777 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15779 if (CondOpcode == ISD::UMULO)
15780 Cond = X86Op.getValue(2);
15782 Cond = X86Op.getValue(1);
15784 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15788 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15789 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15790 if (CondOpc == ISD::OR) {
15791 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15792 // two branches instead of an explicit OR instruction with a
15794 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15795 isX86LogicalCmp(Cmp)) {
15796 CC = Cond.getOperand(0).getOperand(0);
15797 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15798 Chain, Dest, CC, Cmp);
15799 CC = Cond.getOperand(1).getOperand(0);
15803 } else { // ISD::AND
15804 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15805 // two branches instead of an explicit AND instruction with a
15806 // separate test. However, we only do this if this block doesn't
15807 // have a fall-through edge, because this requires an explicit
15808 // jmp when the condition is false.
15809 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15810 isX86LogicalCmp(Cmp) &&
15811 Op.getNode()->hasOneUse()) {
15812 X86::CondCode CCode =
15813 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15814 CCode = X86::GetOppositeBranchCondition(CCode);
15815 CC = DAG.getConstant(CCode, dl, MVT::i8);
15816 SDNode *User = *Op.getNode()->use_begin();
15817 // Look for an unconditional branch following this conditional branch.
15818 // We need this because we need to reverse the successors in order
15819 // to implement FCMP_OEQ.
15820 if (User->getOpcode() == ISD::BR) {
15821 SDValue FalseBB = User->getOperand(1);
15823 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15824 assert(NewBR == User);
15828 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15829 Chain, Dest, CC, Cmp);
15830 X86::CondCode CCode =
15831 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15832 CCode = X86::GetOppositeBranchCondition(CCode);
15833 CC = DAG.getConstant(CCode, dl, MVT::i8);
15839 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15840 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15841 // It should be transformed during dag combiner except when the condition
15842 // is set by a arithmetics with overflow node.
15843 X86::CondCode CCode =
15844 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15845 CCode = X86::GetOppositeBranchCondition(CCode);
15846 CC = DAG.getConstant(CCode, dl, MVT::i8);
15847 Cond = Cond.getOperand(0).getOperand(1);
15849 } else if (Cond.getOpcode() == ISD::SETCC &&
15850 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15851 // For FCMP_OEQ, we can emit
15852 // two branches instead of an explicit AND instruction with a
15853 // separate test. However, we only do this if this block doesn't
15854 // have a fall-through edge, because this requires an explicit
15855 // jmp when the condition is false.
15856 if (Op.getNode()->hasOneUse()) {
15857 SDNode *User = *Op.getNode()->use_begin();
15858 // Look for an unconditional branch following this conditional branch.
15859 // We need this because we need to reverse the successors in order
15860 // to implement FCMP_OEQ.
15861 if (User->getOpcode() == ISD::BR) {
15862 SDValue FalseBB = User->getOperand(1);
15864 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15865 assert(NewBR == User);
15869 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15870 Cond.getOperand(0), Cond.getOperand(1));
15871 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15872 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15873 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15874 Chain, Dest, CC, Cmp);
15875 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15880 } else if (Cond.getOpcode() == ISD::SETCC &&
15881 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15882 // For FCMP_UNE, we can emit
15883 // two branches instead of an explicit AND instruction with a
15884 // separate test. However, we only do this if this block doesn't
15885 // have a fall-through edge, because this requires an explicit
15886 // jmp when the condition is false.
15887 if (Op.getNode()->hasOneUse()) {
15888 SDNode *User = *Op.getNode()->use_begin();
15889 // Look for an unconditional branch following this conditional branch.
15890 // We need this because we need to reverse the successors in order
15891 // to implement FCMP_UNE.
15892 if (User->getOpcode() == ISD::BR) {
15893 SDValue FalseBB = User->getOperand(1);
15895 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15896 assert(NewBR == User);
15899 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15900 Cond.getOperand(0), Cond.getOperand(1));
15901 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15902 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15903 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15904 Chain, Dest, CC, Cmp);
15905 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15915 // Look pass the truncate if the high bits are known zero.
15916 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15917 Cond = Cond.getOperand(0);
15919 // We know the result of AND is compared against zero. Try to match
15921 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15922 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15923 CC = NewSetCC.getOperand(0);
15924 Cond = NewSetCC.getOperand(1);
15931 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15932 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15933 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15935 Cond = ConvertCmpIfNecessary(Cond, DAG);
15936 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15937 Chain, Dest, CC, Cond);
15940 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15941 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15942 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15943 // that the guard pages used by the OS virtual memory manager are allocated in
15944 // correct sequence.
15946 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15947 SelectionDAG &DAG) const {
15948 MachineFunction &MF = DAG.getMachineFunction();
15949 bool SplitStack = MF.shouldSplitStack();
15950 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15955 SDNode *Node = Op.getNode();
15956 SDValue Chain = Op.getOperand(0);
15957 SDValue Size = Op.getOperand(1);
15958 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15959 EVT VT = Node->getValueType(0);
15961 // Chain the dynamic stack allocation so that it doesn't modify the stack
15962 // pointer when other instructions are using the stack.
15963 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15965 bool Is64Bit = Subtarget->is64Bit();
15966 MVT SPTy = getPointerTy(DAG.getDataLayout());
15970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15971 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15972 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15973 " not tell us which reg is the stack pointer!");
15974 EVT VT = Node->getValueType(0);
15975 SDValue Tmp3 = Node->getOperand(2);
15977 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15978 Chain = SP.getValue(1);
15979 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15980 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15981 unsigned StackAlign = TFI.getStackAlignment();
15982 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15983 if (Align > StackAlign)
15984 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15985 DAG.getConstant(-(uint64_t)Align, dl, VT));
15986 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15987 } else if (SplitStack) {
15988 MachineRegisterInfo &MRI = MF.getRegInfo();
15991 // The 64 bit implementation of segmented stacks needs to clobber both r10
15992 // r11. This makes it impossible to use it along with nested parameters.
15993 const Function *F = MF.getFunction();
15995 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15997 if (I->hasNestAttr())
15998 report_fatal_error("Cannot use segmented stacks with functions that "
15999 "have nested arguments.");
16002 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16003 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16004 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16005 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16006 DAG.getRegister(Vreg, SPTy));
16009 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
16011 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
16012 Flag = Chain.getValue(1);
16013 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16015 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
16017 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16018 unsigned SPReg = RegInfo->getStackRegister();
16019 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16020 Chain = SP.getValue(1);
16023 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16024 DAG.getConstant(-(uint64_t)Align, dl, VT));
16025 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16031 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16032 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16034 SDValue Ops[2] = {Result, Chain};
16035 return DAG.getMergeValues(Ops, dl);
16038 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16039 MachineFunction &MF = DAG.getMachineFunction();
16040 auto PtrVT = getPointerTy(MF.getDataLayout());
16041 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16043 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16046 if (!Subtarget->is64Bit() ||
16047 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16048 // vastart just stores the address of the VarArgsFrameIndex slot into the
16049 // memory location argument.
16050 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16051 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16052 MachinePointerInfo(SV), false, false, 0);
16056 // gp_offset (0 - 6 * 8)
16057 // fp_offset (48 - 48 + 8 * 16)
16058 // overflow_arg_area (point to parameters coming in memory).
16060 SmallVector<SDValue, 8> MemOps;
16061 SDValue FIN = Op.getOperand(1);
16063 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16064 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16066 FIN, MachinePointerInfo(SV), false, false, 0);
16067 MemOps.push_back(Store);
16070 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16071 Store = DAG.getStore(Op.getOperand(0), DL,
16072 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16074 FIN, MachinePointerInfo(SV, 4), false, false, 0);
16075 MemOps.push_back(Store);
16077 // Store ptr to overflow_arg_area
16078 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16079 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16080 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16081 MachinePointerInfo(SV, 8),
16083 MemOps.push_back(Store);
16085 // Store ptr to reg_save_area.
16086 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16087 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16088 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16089 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16090 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16091 MemOps.push_back(Store);
16092 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16095 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16096 assert(Subtarget->is64Bit() &&
16097 "LowerVAARG only handles 64-bit va_arg!");
16098 assert(Op.getNode()->getNumOperands() == 4);
16100 MachineFunction &MF = DAG.getMachineFunction();
16101 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16102 // The Win64 ABI uses char* instead of a structure.
16103 return DAG.expandVAArg(Op.getNode());
16105 SDValue Chain = Op.getOperand(0);
16106 SDValue SrcPtr = Op.getOperand(1);
16107 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16108 unsigned Align = Op.getConstantOperandVal(3);
16111 EVT ArgVT = Op.getNode()->getValueType(0);
16112 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16113 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16116 // Decide which area this value should be read from.
16117 // TODO: Implement the AMD64 ABI in its entirety. This simple
16118 // selection mechanism works only for the basic types.
16119 if (ArgVT == MVT::f80) {
16120 llvm_unreachable("va_arg for f80 not yet implemented");
16121 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16122 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16123 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16124 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16126 llvm_unreachable("Unhandled argument type in LowerVAARG");
16129 if (ArgMode == 2) {
16130 // Sanity Check: Make sure using fp_offset makes sense.
16131 assert(!Subtarget->useSoftFloat() &&
16132 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16133 Subtarget->hasSSE1());
16136 // Insert VAARG_64 node into the DAG
16137 // VAARG_64 returns two values: Variable Argument Address, Chain
16138 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16139 DAG.getConstant(ArgMode, dl, MVT::i8),
16140 DAG.getConstant(Align, dl, MVT::i32)};
16141 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16142 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16143 VTs, InstOps, MVT::i64,
16144 MachinePointerInfo(SV),
16146 /*Volatile=*/false,
16148 /*WriteMem=*/true);
16149 Chain = VAARG.getValue(1);
16151 // Load the next argument and return it
16152 return DAG.getLoad(ArgVT, dl,
16155 MachinePointerInfo(),
16156 false, false, false, 0);
16159 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16160 SelectionDAG &DAG) {
16161 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16162 // where a va_list is still an i8*.
16163 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16164 if (Subtarget->isCallingConvWin64(
16165 DAG.getMachineFunction().getFunction()->getCallingConv()))
16166 // Probably a Win64 va_copy.
16167 return DAG.expandVACopy(Op.getNode());
16169 SDValue Chain = Op.getOperand(0);
16170 SDValue DstPtr = Op.getOperand(1);
16171 SDValue SrcPtr = Op.getOperand(2);
16172 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16173 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16176 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16177 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16179 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16182 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16183 // amount is a constant. Takes immediate version of shift as input.
16184 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16185 SDValue SrcOp, uint64_t ShiftAmt,
16186 SelectionDAG &DAG) {
16187 MVT ElementType = VT.getVectorElementType();
16189 // Fold this packed shift into its first operand if ShiftAmt is 0.
16193 // Check for ShiftAmt >= element width
16194 if (ShiftAmt >= ElementType.getSizeInBits()) {
16195 if (Opc == X86ISD::VSRAI)
16196 ShiftAmt = ElementType.getSizeInBits() - 1;
16198 return DAG.getConstant(0, dl, VT);
16201 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16202 && "Unknown target vector shift-by-constant node");
16204 // Fold this packed vector shift into a build vector if SrcOp is a
16205 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16206 if (VT == SrcOp.getSimpleValueType() &&
16207 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16208 SmallVector<SDValue, 8> Elts;
16209 unsigned NumElts = SrcOp->getNumOperands();
16210 ConstantSDNode *ND;
16213 default: llvm_unreachable(nullptr);
16214 case X86ISD::VSHLI:
16215 for (unsigned i=0; i!=NumElts; ++i) {
16216 SDValue CurrentOp = SrcOp->getOperand(i);
16217 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16218 Elts.push_back(CurrentOp);
16221 ND = cast<ConstantSDNode>(CurrentOp);
16222 const APInt &C = ND->getAPIntValue();
16223 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16226 case X86ISD::VSRLI:
16227 for (unsigned i=0; i!=NumElts; ++i) {
16228 SDValue CurrentOp = SrcOp->getOperand(i);
16229 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16230 Elts.push_back(CurrentOp);
16233 ND = cast<ConstantSDNode>(CurrentOp);
16234 const APInt &C = ND->getAPIntValue();
16235 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16238 case X86ISD::VSRAI:
16239 for (unsigned i=0; i!=NumElts; ++i) {
16240 SDValue CurrentOp = SrcOp->getOperand(i);
16241 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16242 Elts.push_back(CurrentOp);
16245 ND = cast<ConstantSDNode>(CurrentOp);
16246 const APInt &C = ND->getAPIntValue();
16247 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16252 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16255 return DAG.getNode(Opc, dl, VT, SrcOp,
16256 DAG.getConstant(ShiftAmt, dl, MVT::i8));
16259 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16260 // may or may not be a constant. Takes immediate version of shift as input.
16261 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16262 SDValue SrcOp, SDValue ShAmt,
16263 SelectionDAG &DAG) {
16264 MVT SVT = ShAmt.getSimpleValueType();
16265 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16267 // Catch shift-by-constant.
16268 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16269 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16270 CShAmt->getZExtValue(), DAG);
16272 // Change opcode to non-immediate version
16274 default: llvm_unreachable("Unknown target vector shift node");
16275 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16276 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16277 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16280 const X86Subtarget &Subtarget =
16281 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16282 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16283 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16284 // Let the shuffle legalizer expand this shift amount node.
16285 SDValue Op0 = ShAmt.getOperand(0);
16286 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16287 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16289 // Need to build a vector containing shift amount.
16290 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16291 SmallVector<SDValue, 4> ShOps;
16292 ShOps.push_back(ShAmt);
16293 if (SVT == MVT::i32) {
16294 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16295 ShOps.push_back(DAG.getUNDEF(SVT));
16297 ShOps.push_back(DAG.getUNDEF(SVT));
16299 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16300 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16303 // The return type has to be a 128-bit type with the same element
16304 // type as the input type.
16305 MVT EltVT = VT.getVectorElementType();
16306 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16308 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16309 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16312 /// \brief Return Mask with the necessary casting or extending
16313 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16314 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16315 const X86Subtarget *Subtarget,
16316 SelectionDAG &DAG, SDLoc dl) {
16318 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16319 // Mask should be extended
16320 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16321 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16324 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16325 if (MaskVT == MVT::v64i1) {
16326 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16327 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16329 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16330 DAG.getConstant(0, dl, MVT::i32));
16331 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16332 DAG.getConstant(1, dl, MVT::i32));
16334 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16335 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16337 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16339 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16341 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16342 return DAG.getBitcast(MaskVT,
16343 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16347 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16348 Mask.getSimpleValueType().getSizeInBits());
16349 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16350 // are extracted by EXTRACT_SUBVECTOR.
16351 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16352 DAG.getBitcast(BitcastVT, Mask),
16353 DAG.getIntPtrConstant(0, dl));
16357 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16358 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16359 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16360 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16361 SDValue PreservedSrc,
16362 const X86Subtarget *Subtarget,
16363 SelectionDAG &DAG) {
16364 MVT VT = Op.getSimpleValueType();
16365 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16366 unsigned OpcodeSelect = ISD::VSELECT;
16369 if (isAllOnesConstant(Mask))
16372 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16374 switch (Op.getOpcode()) {
16376 case X86ISD::PCMPEQM:
16377 case X86ISD::PCMPGTM:
16379 case X86ISD::CMPMU:
16380 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16381 case X86ISD::VFPCLASS:
16382 case X86ISD::VFPCLASSS:
16383 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16384 case X86ISD::VTRUNC:
16385 case X86ISD::VTRUNCS:
16386 case X86ISD::VTRUNCUS:
16387 // We can't use ISD::VSELECT here because it is not always "Legal"
16388 // for the destination type. For example vpmovqb require only AVX512
16389 // and vselect that can operate on byte element type require BWI
16390 OpcodeSelect = X86ISD::SELECT;
16393 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16394 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16395 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16398 /// \brief Creates an SDNode for a predicated scalar operation.
16399 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16400 /// The mask is coming as MVT::i8 and it should be truncated
16401 /// to MVT::i1 while lowering masking intrinsics.
16402 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16403 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16404 /// for a scalar instruction.
16405 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16406 SDValue PreservedSrc,
16407 const X86Subtarget *Subtarget,
16408 SelectionDAG &DAG) {
16409 if (isAllOnesConstant(Mask))
16412 MVT VT = Op.getSimpleValueType();
16414 // The mask should be of type MVT::i1
16415 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16417 if (Op.getOpcode() == X86ISD::FSETCC)
16418 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16419 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16420 Op.getOpcode() == X86ISD::VFPCLASSS)
16421 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16423 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16424 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16425 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16428 static int getSEHRegistrationNodeSize(const Function *Fn) {
16429 if (!Fn->hasPersonalityFn())
16430 report_fatal_error(
16431 "querying registration node size for function without personality");
16432 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16433 // WinEHStatePass for the full struct definition.
16434 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16435 case EHPersonality::MSVC_X86SEH: return 24;
16436 case EHPersonality::MSVC_CXX: return 16;
16439 report_fatal_error(
16440 "can only recover FP for 32-bit MSVC EH personality functions");
16443 /// When the MSVC runtime transfers control to us, either to an outlined
16444 /// function or when returning to a parent frame after catching an exception, we
16445 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16446 /// Here's the math:
16447 /// RegNodeBase = EntryEBP - RegNodeSize
16448 /// ParentFP = RegNodeBase - ParentFrameOffset
16449 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16450 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16451 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16452 SDValue EntryEBP) {
16453 MachineFunction &MF = DAG.getMachineFunction();
16456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16457 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16459 // It's possible that the parent function no longer has a personality function
16460 // if the exceptional code was optimized away, in which case we just return
16461 // the incoming EBP.
16462 if (!Fn->hasPersonalityFn())
16465 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16466 // registration, or the .set_setframe offset.
16467 MCSymbol *OffsetSym =
16468 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16469 GlobalValue::getRealLinkageName(Fn->getName()));
16470 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16471 SDValue ParentFrameOffset =
16472 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16474 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16475 // prologue to RBP in the parent function.
16476 const X86Subtarget &Subtarget =
16477 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16478 if (Subtarget.is64Bit())
16479 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16481 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16482 // RegNodeBase = EntryEBP - RegNodeSize
16483 // ParentFP = RegNodeBase - ParentFrameOffset
16484 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16485 DAG.getConstant(RegNodeSize, dl, PtrVT));
16486 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16489 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16490 SelectionDAG &DAG) {
16492 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16493 MVT VT = Op.getSimpleValueType();
16494 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16496 switch(IntrData->Type) {
16497 case INTR_TYPE_1OP:
16498 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16499 case INTR_TYPE_2OP:
16500 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16502 case INTR_TYPE_2OP_IMM8:
16503 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16504 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16505 case INTR_TYPE_3OP:
16506 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16507 Op.getOperand(2), Op.getOperand(3));
16508 case INTR_TYPE_4OP:
16509 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16510 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16511 case INTR_TYPE_1OP_MASK_RM: {
16512 SDValue Src = Op.getOperand(1);
16513 SDValue PassThru = Op.getOperand(2);
16514 SDValue Mask = Op.getOperand(3);
16515 SDValue RoundingMode;
16516 // We allways add rounding mode to the Node.
16517 // If the rounding mode is not specified, we add the
16518 // "current direction" mode.
16519 if (Op.getNumOperands() == 4)
16521 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16523 RoundingMode = Op.getOperand(4);
16524 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16525 if (IntrWithRoundingModeOpcode != 0)
16526 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16527 X86::STATIC_ROUNDING::CUR_DIRECTION)
16528 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16529 dl, Op.getValueType(), Src, RoundingMode),
16530 Mask, PassThru, Subtarget, DAG);
16531 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16533 Mask, PassThru, Subtarget, DAG);
16535 case INTR_TYPE_1OP_MASK: {
16536 SDValue Src = Op.getOperand(1);
16537 SDValue PassThru = Op.getOperand(2);
16538 SDValue Mask = Op.getOperand(3);
16539 // We add rounding mode to the Node when
16540 // - RM Opcode is specified and
16541 // - RM is not "current direction".
16542 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16543 if (IntrWithRoundingModeOpcode != 0) {
16544 SDValue Rnd = Op.getOperand(4);
16545 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16546 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16547 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16548 dl, Op.getValueType(),
16550 Mask, PassThru, Subtarget, DAG);
16553 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16554 Mask, PassThru, Subtarget, DAG);
16556 case INTR_TYPE_SCALAR_MASK: {
16557 SDValue Src1 = Op.getOperand(1);
16558 SDValue Src2 = Op.getOperand(2);
16559 SDValue passThru = Op.getOperand(3);
16560 SDValue Mask = Op.getOperand(4);
16561 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16562 Mask, passThru, Subtarget, DAG);
16564 case INTR_TYPE_SCALAR_MASK_RM: {
16565 SDValue Src1 = Op.getOperand(1);
16566 SDValue Src2 = Op.getOperand(2);
16567 SDValue Src0 = Op.getOperand(3);
16568 SDValue Mask = Op.getOperand(4);
16569 // There are 2 kinds of intrinsics in this group:
16570 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16571 // (2) With rounding mode and sae - 7 operands.
16572 if (Op.getNumOperands() == 6) {
16573 SDValue Sae = Op.getOperand(5);
16574 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16575 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16577 Mask, Src0, Subtarget, DAG);
16579 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16580 SDValue RoundingMode = Op.getOperand(5);
16581 SDValue Sae = Op.getOperand(6);
16582 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16583 RoundingMode, Sae),
16584 Mask, Src0, Subtarget, DAG);
16586 case INTR_TYPE_2OP_MASK:
16587 case INTR_TYPE_2OP_IMM8_MASK: {
16588 SDValue Src1 = Op.getOperand(1);
16589 SDValue Src2 = Op.getOperand(2);
16590 SDValue PassThru = Op.getOperand(3);
16591 SDValue Mask = Op.getOperand(4);
16593 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16594 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16596 // We specify 2 possible opcodes for intrinsics with rounding modes.
16597 // First, we check if the intrinsic may have non-default rounding mode,
16598 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16599 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16600 if (IntrWithRoundingModeOpcode != 0) {
16601 SDValue Rnd = Op.getOperand(5);
16602 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16603 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16604 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16605 dl, Op.getValueType(),
16607 Mask, PassThru, Subtarget, DAG);
16610 // TODO: Intrinsics should have fast-math-flags to propagate.
16611 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16612 Mask, PassThru, Subtarget, DAG);
16614 case INTR_TYPE_2OP_MASK_RM: {
16615 SDValue Src1 = Op.getOperand(1);
16616 SDValue Src2 = Op.getOperand(2);
16617 SDValue PassThru = Op.getOperand(3);
16618 SDValue Mask = Op.getOperand(4);
16619 // We specify 2 possible modes for intrinsics, with/without rounding
16621 // First, we check if the intrinsic have rounding mode (6 operands),
16622 // if not, we set rounding mode to "current".
16624 if (Op.getNumOperands() == 6)
16625 Rnd = Op.getOperand(5);
16627 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16628 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16630 Mask, PassThru, Subtarget, DAG);
16632 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16633 SDValue Src1 = Op.getOperand(1);
16634 SDValue Src2 = Op.getOperand(2);
16635 SDValue Src3 = Op.getOperand(3);
16636 SDValue PassThru = Op.getOperand(4);
16637 SDValue Mask = Op.getOperand(5);
16638 SDValue Sae = Op.getOperand(6);
16640 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16642 Mask, PassThru, Subtarget, DAG);
16644 case INTR_TYPE_3OP_MASK_RM: {
16645 SDValue Src1 = Op.getOperand(1);
16646 SDValue Src2 = Op.getOperand(2);
16647 SDValue Imm = Op.getOperand(3);
16648 SDValue PassThru = Op.getOperand(4);
16649 SDValue Mask = Op.getOperand(5);
16650 // We specify 2 possible modes for intrinsics, with/without rounding
16652 // First, we check if the intrinsic have rounding mode (7 operands),
16653 // if not, we set rounding mode to "current".
16655 if (Op.getNumOperands() == 7)
16656 Rnd = Op.getOperand(6);
16658 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16659 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16660 Src1, Src2, Imm, Rnd),
16661 Mask, PassThru, Subtarget, DAG);
16663 case INTR_TYPE_3OP_IMM8_MASK:
16664 case INTR_TYPE_3OP_MASK:
16665 case INSERT_SUBVEC: {
16666 SDValue Src1 = Op.getOperand(1);
16667 SDValue Src2 = Op.getOperand(2);
16668 SDValue Src3 = Op.getOperand(3);
16669 SDValue PassThru = Op.getOperand(4);
16670 SDValue Mask = Op.getOperand(5);
16672 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16673 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16674 else if (IntrData->Type == INSERT_SUBVEC) {
16675 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16676 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16677 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16678 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16679 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16682 // We specify 2 possible opcodes for intrinsics with rounding modes.
16683 // First, we check if the intrinsic may have non-default rounding mode,
16684 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16685 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16686 if (IntrWithRoundingModeOpcode != 0) {
16687 SDValue Rnd = Op.getOperand(6);
16688 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16689 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16690 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16691 dl, Op.getValueType(),
16692 Src1, Src2, Src3, Rnd),
16693 Mask, PassThru, Subtarget, DAG);
16696 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16698 Mask, PassThru, Subtarget, DAG);
16700 case VPERM_3OP_MASKZ:
16701 case VPERM_3OP_MASK:{
16702 // Src2 is the PassThru
16703 SDValue Src1 = Op.getOperand(1);
16704 SDValue Src2 = Op.getOperand(2);
16705 SDValue Src3 = Op.getOperand(3);
16706 SDValue Mask = Op.getOperand(4);
16707 MVT VT = Op.getSimpleValueType();
16708 SDValue PassThru = SDValue();
16710 // set PassThru element
16711 if (IntrData->Type == VPERM_3OP_MASKZ)
16712 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16714 PassThru = DAG.getBitcast(VT, Src2);
16716 // Swap Src1 and Src2 in the node creation
16717 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16718 dl, Op.getValueType(),
16720 Mask, PassThru, Subtarget, DAG);
16724 case FMA_OP_MASK: {
16725 SDValue Src1 = Op.getOperand(1);
16726 SDValue Src2 = Op.getOperand(2);
16727 SDValue Src3 = Op.getOperand(3);
16728 SDValue Mask = Op.getOperand(4);
16729 MVT VT = Op.getSimpleValueType();
16730 SDValue PassThru = SDValue();
16732 // set PassThru element
16733 if (IntrData->Type == FMA_OP_MASKZ)
16734 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16735 else if (IntrData->Type == FMA_OP_MASK3)
16740 // We specify 2 possible opcodes for intrinsics with rounding modes.
16741 // First, we check if the intrinsic may have non-default rounding mode,
16742 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16743 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16744 if (IntrWithRoundingModeOpcode != 0) {
16745 SDValue Rnd = Op.getOperand(5);
16746 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16747 X86::STATIC_ROUNDING::CUR_DIRECTION)
16748 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16749 dl, Op.getValueType(),
16750 Src1, Src2, Src3, Rnd),
16751 Mask, PassThru, Subtarget, DAG);
16753 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16754 dl, Op.getValueType(),
16756 Mask, PassThru, Subtarget, DAG);
16758 case TERLOG_OP_MASK:
16759 case TERLOG_OP_MASKZ: {
16760 SDValue Src1 = Op.getOperand(1);
16761 SDValue Src2 = Op.getOperand(2);
16762 SDValue Src3 = Op.getOperand(3);
16763 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16764 SDValue Mask = Op.getOperand(5);
16765 MVT VT = Op.getSimpleValueType();
16766 SDValue PassThru = Src1;
16767 // Set PassThru element.
16768 if (IntrData->Type == TERLOG_OP_MASKZ)
16769 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16771 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16772 Src1, Src2, Src3, Src4),
16773 Mask, PassThru, Subtarget, DAG);
16776 // FPclass intrinsics with mask
16777 SDValue Src1 = Op.getOperand(1);
16778 MVT VT = Src1.getSimpleValueType();
16779 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16780 SDValue Imm = Op.getOperand(2);
16781 SDValue Mask = Op.getOperand(3);
16782 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16783 Mask.getSimpleValueType().getSizeInBits());
16784 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16785 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16786 DAG.getTargetConstant(0, dl, MaskVT),
16788 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16789 DAG.getUNDEF(BitcastVT), FPclassMask,
16790 DAG.getIntPtrConstant(0, dl));
16791 return DAG.getBitcast(Op.getValueType(), Res);
16794 SDValue Src1 = Op.getOperand(1);
16795 SDValue Imm = Op.getOperand(2);
16796 SDValue Mask = Op.getOperand(3);
16797 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16798 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16799 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16800 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16803 case CMP_MASK_CC: {
16804 // Comparison intrinsics with masks.
16805 // Example of transformation:
16806 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16807 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16809 // (v8i1 (insert_subvector undef,
16810 // (v2i1 (and (PCMPEQM %a, %b),
16811 // (extract_subvector
16812 // (v8i1 (bitcast %mask)), 0))), 0))))
16813 MVT VT = Op.getOperand(1).getSimpleValueType();
16814 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16815 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16816 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16817 Mask.getSimpleValueType().getSizeInBits());
16819 if (IntrData->Type == CMP_MASK_CC) {
16820 SDValue CC = Op.getOperand(3);
16821 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16822 // We specify 2 possible opcodes for intrinsics with rounding modes.
16823 // First, we check if the intrinsic may have non-default rounding mode,
16824 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16825 if (IntrData->Opc1 != 0) {
16826 SDValue Rnd = Op.getOperand(5);
16827 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16828 X86::STATIC_ROUNDING::CUR_DIRECTION)
16829 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16830 Op.getOperand(2), CC, Rnd);
16832 //default rounding mode
16834 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16835 Op.getOperand(2), CC);
16838 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16839 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16842 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16843 DAG.getTargetConstant(0, dl,
16846 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16847 DAG.getUNDEF(BitcastVT), CmpMask,
16848 DAG.getIntPtrConstant(0, dl));
16849 return DAG.getBitcast(Op.getValueType(), Res);
16851 case CMP_MASK_SCALAR_CC: {
16852 SDValue Src1 = Op.getOperand(1);
16853 SDValue Src2 = Op.getOperand(2);
16854 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16855 SDValue Mask = Op.getOperand(4);
16858 if (IntrData->Opc1 != 0) {
16859 SDValue Rnd = Op.getOperand(5);
16860 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16861 X86::STATIC_ROUNDING::CUR_DIRECTION)
16862 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16864 //default rounding mode
16866 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16868 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16869 DAG.getTargetConstant(0, dl,
16873 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16874 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16875 DAG.getValueType(MVT::i1));
16877 case COMI: { // Comparison intrinsics
16878 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16879 SDValue LHS = Op.getOperand(1);
16880 SDValue RHS = Op.getOperand(2);
16881 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16882 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16883 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16884 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16885 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16886 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16888 case COMI_RM: { // Comparison intrinsics with Sae
16889 SDValue LHS = Op.getOperand(1);
16890 SDValue RHS = Op.getOperand(2);
16891 SDValue CC = Op.getOperand(3);
16892 SDValue Sae = Op.getOperand(4);
16893 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16894 // choose between ordered and unordered (comi/ucomi)
16895 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16897 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16898 X86::STATIC_ROUNDING::CUR_DIRECTION)
16899 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16901 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16902 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16903 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16904 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16907 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16908 Op.getOperand(1), Op.getOperand(2), DAG);
16910 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16911 Op.getSimpleValueType(),
16913 Op.getOperand(2), DAG),
16914 Op.getOperand(4), Op.getOperand(3), Subtarget,
16916 case COMPRESS_EXPAND_IN_REG: {
16917 SDValue Mask = Op.getOperand(3);
16918 SDValue DataToCompress = Op.getOperand(1);
16919 SDValue PassThru = Op.getOperand(2);
16920 if (isAllOnesConstant(Mask)) // return data as is
16921 return Op.getOperand(1);
16923 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16925 Mask, PassThru, Subtarget, DAG);
16928 SDValue Mask = Op.getOperand(1);
16929 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16930 Mask.getSimpleValueType().getSizeInBits());
16931 Mask = DAG.getBitcast(MaskVT, Mask);
16932 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16935 SDValue Mask = Op.getOperand(3);
16936 MVT VT = Op.getSimpleValueType();
16937 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16938 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16939 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16943 MVT VT = Op.getSimpleValueType();
16944 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16946 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16947 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16948 // Arguments should be swapped.
16949 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16950 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16952 return DAG.getBitcast(VT, Res);
16954 case CONVERT_TO_MASK: {
16955 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16956 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16957 MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16959 SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16961 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16962 DAG.getUNDEF(BitcastVT), CvtMask,
16963 DAG.getIntPtrConstant(0, dl));
16964 return DAG.getBitcast(Op.getValueType(), Res);
16966 case CONVERT_MASK_TO_VEC: {
16967 SDValue Mask = Op.getOperand(1);
16968 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16969 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16970 return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16972 case BRCST_SUBVEC_TO_VEC: {
16973 SDValue Src = Op.getOperand(1);
16974 SDValue Passthru = Op.getOperand(2);
16975 SDValue Mask = Op.getOperand(3);
16976 EVT resVT = Passthru.getValueType();
16977 SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16978 DAG.getUNDEF(resVT), Src,
16979 DAG.getIntPtrConstant(0, dl));
16981 if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16982 immVal = DAG.getConstant(0x44, dl, MVT::i8);
16984 immVal = DAG.getConstant(0, dl, MVT::i8);
16985 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16986 subVec, subVec, immVal),
16987 Mask, Passthru, Subtarget, DAG);
16995 default: return SDValue(); // Don't custom lower most intrinsics.
16997 case Intrinsic::x86_avx2_permd:
16998 case Intrinsic::x86_avx2_permps:
16999 // Operands intentionally swapped. Mask is last operand to intrinsic,
17000 // but second operand for node/instruction.
17001 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
17002 Op.getOperand(2), Op.getOperand(1));
17004 // ptest and testp intrinsics. The intrinsic these come from are designed to
17005 // return an integer value, not just an instruction so lower it to the ptest
17006 // or testp pattern and a setcc for the result.
17007 case Intrinsic::x86_sse41_ptestz:
17008 case Intrinsic::x86_sse41_ptestc:
17009 case Intrinsic::x86_sse41_ptestnzc:
17010 case Intrinsic::x86_avx_ptestz_256:
17011 case Intrinsic::x86_avx_ptestc_256:
17012 case Intrinsic::x86_avx_ptestnzc_256:
17013 case Intrinsic::x86_avx_vtestz_ps:
17014 case Intrinsic::x86_avx_vtestc_ps:
17015 case Intrinsic::x86_avx_vtestnzc_ps:
17016 case Intrinsic::x86_avx_vtestz_pd:
17017 case Intrinsic::x86_avx_vtestc_pd:
17018 case Intrinsic::x86_avx_vtestnzc_pd:
17019 case Intrinsic::x86_avx_vtestz_ps_256:
17020 case Intrinsic::x86_avx_vtestc_ps_256:
17021 case Intrinsic::x86_avx_vtestnzc_ps_256:
17022 case Intrinsic::x86_avx_vtestz_pd_256:
17023 case Intrinsic::x86_avx_vtestc_pd_256:
17024 case Intrinsic::x86_avx_vtestnzc_pd_256: {
17025 bool IsTestPacked = false;
17028 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
17029 case Intrinsic::x86_avx_vtestz_ps:
17030 case Intrinsic::x86_avx_vtestz_pd:
17031 case Intrinsic::x86_avx_vtestz_ps_256:
17032 case Intrinsic::x86_avx_vtestz_pd_256:
17033 IsTestPacked = true; // Fallthrough
17034 case Intrinsic::x86_sse41_ptestz:
17035 case Intrinsic::x86_avx_ptestz_256:
17037 X86CC = X86::COND_E;
17039 case Intrinsic::x86_avx_vtestc_ps:
17040 case Intrinsic::x86_avx_vtestc_pd:
17041 case Intrinsic::x86_avx_vtestc_ps_256:
17042 case Intrinsic::x86_avx_vtestc_pd_256:
17043 IsTestPacked = true; // Fallthrough
17044 case Intrinsic::x86_sse41_ptestc:
17045 case Intrinsic::x86_avx_ptestc_256:
17047 X86CC = X86::COND_B;
17049 case Intrinsic::x86_avx_vtestnzc_ps:
17050 case Intrinsic::x86_avx_vtestnzc_pd:
17051 case Intrinsic::x86_avx_vtestnzc_ps_256:
17052 case Intrinsic::x86_avx_vtestnzc_pd_256:
17053 IsTestPacked = true; // Fallthrough
17054 case Intrinsic::x86_sse41_ptestnzc:
17055 case Intrinsic::x86_avx_ptestnzc_256:
17057 X86CC = X86::COND_A;
17061 SDValue LHS = Op.getOperand(1);
17062 SDValue RHS = Op.getOperand(2);
17063 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17064 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17065 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17066 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17067 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17069 case Intrinsic::x86_avx512_kortestz_w:
17070 case Intrinsic::x86_avx512_kortestc_w: {
17071 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17072 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17073 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17074 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17075 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17076 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17077 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17080 case Intrinsic::x86_sse42_pcmpistria128:
17081 case Intrinsic::x86_sse42_pcmpestria128:
17082 case Intrinsic::x86_sse42_pcmpistric128:
17083 case Intrinsic::x86_sse42_pcmpestric128:
17084 case Intrinsic::x86_sse42_pcmpistrio128:
17085 case Intrinsic::x86_sse42_pcmpestrio128:
17086 case Intrinsic::x86_sse42_pcmpistris128:
17087 case Intrinsic::x86_sse42_pcmpestris128:
17088 case Intrinsic::x86_sse42_pcmpistriz128:
17089 case Intrinsic::x86_sse42_pcmpestriz128: {
17093 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17094 case Intrinsic::x86_sse42_pcmpistria128:
17095 Opcode = X86ISD::PCMPISTRI;
17096 X86CC = X86::COND_A;
17098 case Intrinsic::x86_sse42_pcmpestria128:
17099 Opcode = X86ISD::PCMPESTRI;
17100 X86CC = X86::COND_A;
17102 case Intrinsic::x86_sse42_pcmpistric128:
17103 Opcode = X86ISD::PCMPISTRI;
17104 X86CC = X86::COND_B;
17106 case Intrinsic::x86_sse42_pcmpestric128:
17107 Opcode = X86ISD::PCMPESTRI;
17108 X86CC = X86::COND_B;
17110 case Intrinsic::x86_sse42_pcmpistrio128:
17111 Opcode = X86ISD::PCMPISTRI;
17112 X86CC = X86::COND_O;
17114 case Intrinsic::x86_sse42_pcmpestrio128:
17115 Opcode = X86ISD::PCMPESTRI;
17116 X86CC = X86::COND_O;
17118 case Intrinsic::x86_sse42_pcmpistris128:
17119 Opcode = X86ISD::PCMPISTRI;
17120 X86CC = X86::COND_S;
17122 case Intrinsic::x86_sse42_pcmpestris128:
17123 Opcode = X86ISD::PCMPESTRI;
17124 X86CC = X86::COND_S;
17126 case Intrinsic::x86_sse42_pcmpistriz128:
17127 Opcode = X86ISD::PCMPISTRI;
17128 X86CC = X86::COND_E;
17130 case Intrinsic::x86_sse42_pcmpestriz128:
17131 Opcode = X86ISD::PCMPESTRI;
17132 X86CC = X86::COND_E;
17135 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17136 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17137 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17138 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17139 DAG.getConstant(X86CC, dl, MVT::i8),
17140 SDValue(PCMP.getNode(), 1));
17141 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17144 case Intrinsic::x86_sse42_pcmpistri128:
17145 case Intrinsic::x86_sse42_pcmpestri128: {
17147 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17148 Opcode = X86ISD::PCMPISTRI;
17150 Opcode = X86ISD::PCMPESTRI;
17152 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17153 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17154 return DAG.getNode(Opcode, dl, VTs, NewOps);
17157 case Intrinsic::x86_seh_lsda: {
17158 // Compute the symbol for the LSDA. We know it'll get emitted later.
17159 MachineFunction &MF = DAG.getMachineFunction();
17160 SDValue Op1 = Op.getOperand(1);
17161 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17162 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17163 GlobalValue::getRealLinkageName(Fn->getName()));
17165 // Generate a simple absolute symbol reference. This intrinsic is only
17166 // supported on 32-bit Windows, which isn't PIC.
17167 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17168 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17171 case Intrinsic::x86_seh_recoverfp: {
17172 SDValue FnOp = Op.getOperand(1);
17173 SDValue IncomingFPOp = Op.getOperand(2);
17174 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17175 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17177 report_fatal_error(
17178 "llvm.x86.seh.recoverfp must take a function as the first argument");
17179 return recoverFramePointer(DAG, Fn, IncomingFPOp);
17182 case Intrinsic::localaddress: {
17183 // Returns one of the stack, base, or frame pointer registers, depending on
17184 // which is used to reference local variables.
17185 MachineFunction &MF = DAG.getMachineFunction();
17186 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17188 if (RegInfo->hasBasePointer(MF))
17189 Reg = RegInfo->getBaseRegister();
17190 else // This function handles the SP or FP case.
17191 Reg = RegInfo->getPtrSizedFrameRegister(MF);
17192 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17197 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17198 SDValue Src, SDValue Mask, SDValue Base,
17199 SDValue Index, SDValue ScaleOp, SDValue Chain,
17200 const X86Subtarget * Subtarget) {
17202 auto *C = cast<ConstantSDNode>(ScaleOp);
17203 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17204 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17205 Index.getSimpleValueType().getVectorNumElements());
17207 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17209 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17211 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17212 Mask.getSimpleValueType().getSizeInBits());
17214 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17215 // are extracted by EXTRACT_SUBVECTOR.
17216 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17217 DAG.getBitcast(BitcastVT, Mask),
17218 DAG.getIntPtrConstant(0, dl));
17220 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17221 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17222 SDValue Segment = DAG.getRegister(0, MVT::i32);
17223 if (Src.getOpcode() == ISD::UNDEF)
17224 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17225 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17226 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17227 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17228 return DAG.getMergeValues(RetOps, dl);
17231 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17232 SDValue Src, SDValue Mask, SDValue Base,
17233 SDValue Index, SDValue ScaleOp, SDValue Chain) {
17235 auto *C = cast<ConstantSDNode>(ScaleOp);
17236 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17237 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17238 SDValue Segment = DAG.getRegister(0, MVT::i32);
17239 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17240 Index.getSimpleValueType().getVectorNumElements());
17242 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17244 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17246 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17247 Mask.getSimpleValueType().getSizeInBits());
17249 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17250 // are extracted by EXTRACT_SUBVECTOR.
17251 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17252 DAG.getBitcast(BitcastVT, Mask),
17253 DAG.getIntPtrConstant(0, dl));
17255 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17256 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17257 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17258 return SDValue(Res, 1);
17261 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17262 SDValue Mask, SDValue Base, SDValue Index,
17263 SDValue ScaleOp, SDValue Chain) {
17265 auto *C = cast<ConstantSDNode>(ScaleOp);
17266 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17267 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17268 SDValue Segment = DAG.getRegister(0, MVT::i32);
17270 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17272 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17274 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17276 MaskInReg = DAG.getBitcast(MaskVT, Mask);
17277 //SDVTList VTs = DAG.getVTList(MVT::Other);
17278 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17279 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17280 return SDValue(Res, 0);
17283 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17284 // read performance monitor counters (x86_rdpmc).
17285 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17286 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17287 SmallVectorImpl<SDValue> &Results) {
17288 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17289 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17292 // The ECX register is used to select the index of the performance counter
17294 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17296 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17298 // Reads the content of a 64-bit performance counter and returns it in the
17299 // registers EDX:EAX.
17300 if (Subtarget->is64Bit()) {
17301 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17302 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17305 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17306 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17309 Chain = HI.getValue(1);
17311 if (Subtarget->is64Bit()) {
17312 // The EAX register is loaded with the low-order 32 bits. The EDX register
17313 // is loaded with the supported high-order bits of the counter.
17314 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17315 DAG.getConstant(32, DL, MVT::i8));
17316 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17317 Results.push_back(Chain);
17321 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17322 SDValue Ops[] = { LO, HI };
17323 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17324 Results.push_back(Pair);
17325 Results.push_back(Chain);
17328 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17329 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17330 // also used to custom lower READCYCLECOUNTER nodes.
17331 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17332 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17333 SmallVectorImpl<SDValue> &Results) {
17334 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17335 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17338 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17339 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17340 // and the EAX register is loaded with the low-order 32 bits.
17341 if (Subtarget->is64Bit()) {
17342 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17343 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17346 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17347 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17350 SDValue Chain = HI.getValue(1);
17352 if (Opcode == X86ISD::RDTSCP_DAG) {
17353 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17355 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17356 // the ECX register. Add 'ecx' explicitly to the chain.
17357 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17359 // Explicitly store the content of ECX at the location passed in input
17360 // to the 'rdtscp' intrinsic.
17361 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17362 MachinePointerInfo(), false, false, 0);
17365 if (Subtarget->is64Bit()) {
17366 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17367 // the EAX register is loaded with the low-order 32 bits.
17368 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17369 DAG.getConstant(32, DL, MVT::i8));
17370 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17371 Results.push_back(Chain);
17375 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17376 SDValue Ops[] = { LO, HI };
17377 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17378 Results.push_back(Pair);
17379 Results.push_back(Chain);
17382 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17383 SelectionDAG &DAG) {
17384 SmallVector<SDValue, 2> Results;
17386 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17388 return DAG.getMergeValues(Results, DL);
17391 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17392 MachineFunction &MF = DAG.getMachineFunction();
17393 SDValue Chain = Op.getOperand(0);
17394 SDValue RegNode = Op.getOperand(2);
17395 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17397 report_fatal_error("EH registrations only live in functions using WinEH");
17399 // Cast the operand to an alloca, and remember the frame index.
17400 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17402 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17403 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17405 // Return the chain operand without making any DAG nodes.
17409 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17410 /// return truncate Store/MaskedStore Node
17411 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17415 SDValue Mask = Op.getOperand(4);
17416 SDValue DataToTruncate = Op.getOperand(3);
17417 SDValue Addr = Op.getOperand(2);
17418 SDValue Chain = Op.getOperand(0);
17420 MVT VT = DataToTruncate.getSimpleValueType();
17421 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17423 if (isAllOnesConstant(Mask)) // return just a truncate store
17424 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17425 MachinePointerInfo(), SVT, false, false,
17426 SVT.getScalarSizeInBits()/8);
17428 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17429 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17430 Mask.getSimpleValueType().getSizeInBits());
17431 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17432 // are extracted by EXTRACT_SUBVECTOR.
17433 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17434 DAG.getBitcast(BitcastVT, Mask),
17435 DAG.getIntPtrConstant(0, dl));
17437 MachineMemOperand *MMO = DAG.getMachineFunction().
17438 getMachineMemOperand(MachinePointerInfo(),
17439 MachineMemOperand::MOStore, SVT.getStoreSize(),
17440 SVT.getScalarSizeInBits()/8);
17442 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17443 VMask, SVT, MMO, true);
17446 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17447 SelectionDAG &DAG) {
17448 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17450 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17452 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17453 return MarkEHRegistrationNode(Op, DAG);
17454 if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17455 IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17456 IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17457 IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17458 // We need a frame pointer because this will get lowered to a PUSH/POP
17460 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17461 MFI->setHasOpaqueSPAdjustment(true);
17462 // Don't do anything here, we will expand these intrinsics out later
17463 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17470 switch(IntrData->Type) {
17471 default: llvm_unreachable("Unknown Intrinsic Type");
17474 // Emit the node with the right value type.
17475 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17476 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17478 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17479 // Otherwise return the value from Rand, which is always 0, casted to i32.
17480 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17481 DAG.getConstant(1, dl, Op->getValueType(1)),
17482 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17483 SDValue(Result.getNode(), 1) };
17484 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17485 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17488 // Return { result, isValid, chain }.
17489 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17490 SDValue(Result.getNode(), 2));
17493 //gather(v1, mask, index, base, scale);
17494 SDValue Chain = Op.getOperand(0);
17495 SDValue Src = Op.getOperand(2);
17496 SDValue Base = Op.getOperand(3);
17497 SDValue Index = Op.getOperand(4);
17498 SDValue Mask = Op.getOperand(5);
17499 SDValue Scale = Op.getOperand(6);
17500 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17504 //scatter(base, mask, index, v1, scale);
17505 SDValue Chain = Op.getOperand(0);
17506 SDValue Base = Op.getOperand(2);
17507 SDValue Mask = Op.getOperand(3);
17508 SDValue Index = Op.getOperand(4);
17509 SDValue Src = Op.getOperand(5);
17510 SDValue Scale = Op.getOperand(6);
17511 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17515 SDValue Hint = Op.getOperand(6);
17516 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17517 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17518 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17519 SDValue Chain = Op.getOperand(0);
17520 SDValue Mask = Op.getOperand(2);
17521 SDValue Index = Op.getOperand(3);
17522 SDValue Base = Op.getOperand(4);
17523 SDValue Scale = Op.getOperand(5);
17524 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17526 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17528 SmallVector<SDValue, 2> Results;
17529 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17531 return DAG.getMergeValues(Results, dl);
17533 // Read Performance Monitoring Counters.
17535 SmallVector<SDValue, 2> Results;
17536 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17537 return DAG.getMergeValues(Results, dl);
17539 // XTEST intrinsics.
17541 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17542 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17543 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17544 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17546 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17547 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17548 Ret, SDValue(InTrans.getNode(), 1));
17552 SmallVector<SDValue, 2> Results;
17553 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17554 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17555 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17556 DAG.getConstant(-1, dl, MVT::i8));
17557 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17558 Op.getOperand(4), GenCF.getValue(1));
17559 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17560 Op.getOperand(5), MachinePointerInfo(),
17562 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17563 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17565 Results.push_back(SetCC);
17566 Results.push_back(Store);
17567 return DAG.getMergeValues(Results, dl);
17569 case COMPRESS_TO_MEM: {
17570 SDValue Mask = Op.getOperand(4);
17571 SDValue DataToCompress = Op.getOperand(3);
17572 SDValue Addr = Op.getOperand(2);
17573 SDValue Chain = Op.getOperand(0);
17575 MVT VT = DataToCompress.getSimpleValueType();
17576 if (isAllOnesConstant(Mask)) // return just a store
17577 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17578 MachinePointerInfo(), false, false,
17579 VT.getScalarSizeInBits()/8);
17581 SDValue Compressed =
17582 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17583 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17584 return DAG.getStore(Chain, dl, Compressed, Addr,
17585 MachinePointerInfo(), false, false,
17586 VT.getScalarSizeInBits()/8);
17588 case TRUNCATE_TO_MEM_VI8:
17589 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17590 case TRUNCATE_TO_MEM_VI16:
17591 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17592 case TRUNCATE_TO_MEM_VI32:
17593 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17594 case EXPAND_FROM_MEM: {
17595 SDValue Mask = Op.getOperand(4);
17596 SDValue PassThru = Op.getOperand(3);
17597 SDValue Addr = Op.getOperand(2);
17598 SDValue Chain = Op.getOperand(0);
17599 MVT VT = Op.getSimpleValueType();
17601 if (isAllOnesConstant(Mask)) // return just a load
17602 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17603 false, VT.getScalarSizeInBits()/8);
17605 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17606 false, false, false,
17607 VT.getScalarSizeInBits()/8);
17609 SDValue Results[] = {
17610 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17611 Mask, PassThru, Subtarget, DAG), Chain};
17612 return DAG.getMergeValues(Results, dl);
17616 SDValue Mask = Op.getOperand(4);
17617 SDValue PassThru = Op.getOperand(3);
17618 SDValue Addr = Op.getOperand(2);
17619 SDValue Chain = Op.getOperand(0);
17620 MVT VT = Op.getSimpleValueType();
17622 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
17623 assert(MemIntr && "Expected MemIntrinsicSDNode!");
17625 if (isAllOnesConstant(Mask)) // return just a load
17626 return DAG.getLoad(VT, dl, Chain, Addr, MemIntr->getMemOperand());
17628 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17629 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17630 return DAG.getMaskedLoad(VT, dl, Chain, Addr, VMask, PassThru, VT,
17631 MemIntr->getMemOperand(), ISD::NON_EXTLOAD);
17636 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17637 SelectionDAG &DAG) const {
17638 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17639 MFI->setReturnAddressIsTaken(true);
17641 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17644 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17646 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17649 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17650 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17651 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17652 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17653 DAG.getNode(ISD::ADD, dl, PtrVT,
17654 FrameAddr, Offset),
17655 MachinePointerInfo(), false, false, false, 0);
17658 // Just load the return address.
17659 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17660 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17661 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17664 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17665 MachineFunction &MF = DAG.getMachineFunction();
17666 MachineFrameInfo *MFI = MF.getFrameInfo();
17667 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17668 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17669 EVT VT = Op.getValueType();
17671 MFI->setFrameAddressIsTaken(true);
17673 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17674 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17675 // is not possible to crawl up the stack without looking at the unwind codes
17677 int FrameAddrIndex = FuncInfo->getFAIndex();
17678 if (!FrameAddrIndex) {
17679 // Set up a frame object for the return address.
17680 unsigned SlotSize = RegInfo->getSlotSize();
17681 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17682 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17683 FuncInfo->setFAIndex(FrameAddrIndex);
17685 return DAG.getFrameIndex(FrameAddrIndex, VT);
17688 unsigned FrameReg =
17689 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17690 SDLoc dl(Op); // FIXME probably not meaningful
17691 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17692 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17693 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17694 "Invalid Frame Register!");
17695 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17697 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17698 MachinePointerInfo(),
17699 false, false, false, 0);
17703 // FIXME? Maybe this could be a TableGen attribute on some registers and
17704 // this table could be generated automatically from RegInfo.
17705 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17706 SelectionDAG &DAG) const {
17707 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17708 const MachineFunction &MF = DAG.getMachineFunction();
17710 unsigned Reg = StringSwitch<unsigned>(RegName)
17711 .Case("esp", X86::ESP)
17712 .Case("rsp", X86::RSP)
17713 .Case("ebp", X86::EBP)
17714 .Case("rbp", X86::RBP)
17717 if (Reg == X86::EBP || Reg == X86::RBP) {
17718 if (!TFI.hasFP(MF))
17719 report_fatal_error("register " + StringRef(RegName) +
17720 " is allocatable: function has no frame pointer");
17723 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17724 unsigned FrameReg =
17725 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17726 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17727 "Invalid Frame Register!");
17735 report_fatal_error("Invalid register name global variable");
17738 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17739 SelectionDAG &DAG) const {
17740 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17741 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17744 unsigned X86TargetLowering::getExceptionPointerRegister(
17745 const Constant *PersonalityFn) const {
17746 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17747 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17749 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17752 unsigned X86TargetLowering::getExceptionSelectorRegister(
17753 const Constant *PersonalityFn) const {
17754 // Funclet personalities don't use selectors (the runtime does the selection).
17755 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17756 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17759 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17760 SDValue Chain = Op.getOperand(0);
17761 SDValue Offset = Op.getOperand(1);
17762 SDValue Handler = Op.getOperand(2);
17765 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17766 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17767 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17768 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17769 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17770 "Invalid Frame Register!");
17771 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17772 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17774 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17775 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17777 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17778 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17780 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17782 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17783 DAG.getRegister(StoreAddrReg, PtrVT));
17786 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17787 SelectionDAG &DAG) const {
17789 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17790 DAG.getVTList(MVT::i32, MVT::Other),
17791 Op.getOperand(0), Op.getOperand(1));
17794 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17795 SelectionDAG &DAG) const {
17797 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17798 Op.getOperand(0), Op.getOperand(1));
17801 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17802 return Op.getOperand(0);
17805 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17806 SelectionDAG &DAG) const {
17807 SDValue Root = Op.getOperand(0);
17808 SDValue Trmp = Op.getOperand(1); // trampoline
17809 SDValue FPtr = Op.getOperand(2); // nested function
17810 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17813 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17814 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17816 if (Subtarget->is64Bit()) {
17817 SDValue OutChains[6];
17819 // Large code-model.
17820 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17821 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17823 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17824 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17826 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17828 // Load the pointer to the nested function into R11.
17829 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17830 SDValue Addr = Trmp;
17831 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17832 Addr, MachinePointerInfo(TrmpAddr),
17835 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17836 DAG.getConstant(2, dl, MVT::i64));
17837 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17838 MachinePointerInfo(TrmpAddr, 2),
17841 // Load the 'nest' parameter value into R10.
17842 // R10 is specified in X86CallingConv.td
17843 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17844 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17845 DAG.getConstant(10, dl, MVT::i64));
17846 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17847 Addr, MachinePointerInfo(TrmpAddr, 10),
17850 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17851 DAG.getConstant(12, dl, MVT::i64));
17852 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17853 MachinePointerInfo(TrmpAddr, 12),
17856 // Jump to the nested function.
17857 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17858 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17859 DAG.getConstant(20, dl, MVT::i64));
17860 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17861 Addr, MachinePointerInfo(TrmpAddr, 20),
17864 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17865 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17866 DAG.getConstant(22, dl, MVT::i64));
17867 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17868 Addr, MachinePointerInfo(TrmpAddr, 22),
17871 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17873 const Function *Func =
17874 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17875 CallingConv::ID CC = Func->getCallingConv();
17880 llvm_unreachable("Unsupported calling convention");
17881 case CallingConv::C:
17882 case CallingConv::X86_StdCall: {
17883 // Pass 'nest' parameter in ECX.
17884 // Must be kept in sync with X86CallingConv.td
17885 NestReg = X86::ECX;
17887 // Check that ECX wasn't needed by an 'inreg' parameter.
17888 FunctionType *FTy = Func->getFunctionType();
17889 const AttributeSet &Attrs = Func->getAttributes();
17891 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17892 unsigned InRegCount = 0;
17895 for (FunctionType::param_iterator I = FTy->param_begin(),
17896 E = FTy->param_end(); I != E; ++I, ++Idx)
17897 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17898 auto &DL = DAG.getDataLayout();
17899 // FIXME: should only count parameters that are lowered to integers.
17900 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17903 if (InRegCount > 2) {
17904 report_fatal_error("Nest register in use - reduce number of inreg"
17910 case CallingConv::X86_FastCall:
17911 case CallingConv::X86_ThisCall:
17912 case CallingConv::Fast:
17913 // Pass 'nest' parameter in EAX.
17914 // Must be kept in sync with X86CallingConv.td
17915 NestReg = X86::EAX;
17919 SDValue OutChains[4];
17920 SDValue Addr, Disp;
17922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17923 DAG.getConstant(10, dl, MVT::i32));
17924 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17926 // This is storing the opcode for MOV32ri.
17927 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17928 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17929 OutChains[0] = DAG.getStore(Root, dl,
17930 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17931 Trmp, MachinePointerInfo(TrmpAddr),
17934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17935 DAG.getConstant(1, dl, MVT::i32));
17936 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17937 MachinePointerInfo(TrmpAddr, 1),
17940 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17941 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17942 DAG.getConstant(5, dl, MVT::i32));
17943 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17944 Addr, MachinePointerInfo(TrmpAddr, 5),
17947 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17948 DAG.getConstant(6, dl, MVT::i32));
17949 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17950 MachinePointerInfo(TrmpAddr, 6),
17953 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17957 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17958 SelectionDAG &DAG) const {
17960 The rounding mode is in bits 11:10 of FPSR, and has the following
17962 00 Round to nearest
17967 FLT_ROUNDS, on the other hand, expects the following:
17974 To perform the conversion, we do:
17975 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17978 MachineFunction &MF = DAG.getMachineFunction();
17979 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17980 unsigned StackAlignment = TFI.getStackAlignment();
17981 MVT VT = Op.getSimpleValueType();
17984 // Save FP Control Word to stack slot
17985 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17986 SDValue StackSlot =
17987 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17989 MachineMemOperand *MMO =
17990 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17991 MachineMemOperand::MOStore, 2, 2);
17993 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17994 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17995 DAG.getVTList(MVT::Other),
17996 Ops, MVT::i16, MMO);
17998 // Load FP Control Word from stack slot
17999 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
18000 MachinePointerInfo(), false, false, false, 0);
18002 // Transform as necessary
18004 DAG.getNode(ISD::SRL, DL, MVT::i16,
18005 DAG.getNode(ISD::AND, DL, MVT::i16,
18006 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
18007 DAG.getConstant(11, DL, MVT::i8));
18009 DAG.getNode(ISD::SRL, DL, MVT::i16,
18010 DAG.getNode(ISD::AND, DL, MVT::i16,
18011 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
18012 DAG.getConstant(9, DL, MVT::i8));
18015 DAG.getNode(ISD::AND, DL, MVT::i16,
18016 DAG.getNode(ISD::ADD, DL, MVT::i16,
18017 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
18018 DAG.getConstant(1, DL, MVT::i16)),
18019 DAG.getConstant(3, DL, MVT::i16));
18021 return DAG.getNode((VT.getSizeInBits() < 16 ?
18022 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
18025 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
18027 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
18028 // to 512-bit vector.
18029 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
18030 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
18031 // split the vector, perform operation on it's Lo a Hi part and
18032 // concatenate the results.
18033 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
18035 MVT VT = Op.getSimpleValueType();
18036 MVT EltVT = VT.getVectorElementType();
18037 unsigned NumElems = VT.getVectorNumElements();
18039 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
18040 // Extend to 512 bit vector.
18041 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18042 "Unsupported value type for operation");
18044 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
18045 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
18046 DAG.getUNDEF(NewVT),
18048 DAG.getIntPtrConstant(0, dl));
18049 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
18051 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
18052 DAG.getIntPtrConstant(0, dl));
18055 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
18056 "Unsupported element type");
18058 if (16 < NumElems) {
18059 // Split vector, it's Lo and Hi parts will be handled in next iteration.
18061 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
18062 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
18064 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
18065 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
18067 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
18070 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
18072 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18073 "Unsupported value type for operation");
18075 // Use native supported vector instruction vplzcntd.
18076 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18077 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18078 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18079 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18081 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18084 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18085 SelectionDAG &DAG) {
18086 MVT VT = Op.getSimpleValueType();
18088 unsigned NumBits = VT.getSizeInBits();
18091 if (VT.isVector() && Subtarget->hasAVX512())
18092 return LowerVectorCTLZ_AVX512(Op, DAG);
18094 Op = Op.getOperand(0);
18095 if (VT == MVT::i8) {
18096 // Zero extend to i32 since there is not an i8 bsr.
18098 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18101 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18102 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18103 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18105 // If src is zero (i.e. bsr sets ZF), returns NumBits.
18108 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18109 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18112 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18114 // Finally xor with NumBits-1.
18115 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18116 DAG.getConstant(NumBits - 1, dl, OpVT));
18119 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18123 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18124 SelectionDAG &DAG) {
18125 MVT VT = Op.getSimpleValueType();
18127 unsigned NumBits = VT.getSizeInBits();
18130 Op = Op.getOperand(0);
18131 if (VT == MVT::i8) {
18132 // Zero extend to i32 since there is not an i8 bsr.
18134 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18137 // Issue a bsr (scan bits in reverse).
18138 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18139 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18141 // And xor with NumBits-1.
18142 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18143 DAG.getConstant(NumBits - 1, dl, OpVT));
18146 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18150 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18151 MVT VT = Op.getSimpleValueType();
18152 unsigned NumBits = VT.getScalarSizeInBits();
18155 if (VT.isVector()) {
18156 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18158 SDValue N0 = Op.getOperand(0);
18159 SDValue Zero = DAG.getConstant(0, dl, VT);
18161 // lsb(x) = (x & -x)
18162 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18163 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18165 // cttz_undef(x) = (width - 1) - ctlz(lsb)
18166 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18167 TLI.isOperationLegal(ISD::CTLZ, VT)) {
18168 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18169 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18170 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18173 // cttz(x) = ctpop(lsb - 1)
18174 SDValue One = DAG.getConstant(1, dl, VT);
18175 return DAG.getNode(ISD::CTPOP, dl, VT,
18176 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18179 assert(Op.getOpcode() == ISD::CTTZ &&
18180 "Only scalar CTTZ requires custom lowering");
18182 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18183 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18184 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18186 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18189 DAG.getConstant(NumBits, dl, VT),
18190 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18193 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18196 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18197 // ones, and then concatenate the result back.
18198 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18199 MVT VT = Op.getSimpleValueType();
18201 assert(VT.is256BitVector() && VT.isInteger() &&
18202 "Unsupported value type for operation");
18204 unsigned NumElems = VT.getVectorNumElements();
18207 // Extract the LHS vectors
18208 SDValue LHS = Op.getOperand(0);
18209 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18210 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18212 // Extract the RHS vectors
18213 SDValue RHS = Op.getOperand(1);
18214 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18215 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18217 MVT EltVT = VT.getVectorElementType();
18218 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18220 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18221 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18222 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18225 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18226 if (Op.getValueType() == MVT::i1)
18227 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18228 Op.getOperand(0), Op.getOperand(1));
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 LowerSUB(SDValue Op, SelectionDAG &DAG) {
18236 if (Op.getValueType() == MVT::i1)
18237 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18238 Op.getOperand(0), Op.getOperand(1));
18239 assert(Op.getSimpleValueType().is256BitVector() &&
18240 Op.getSimpleValueType().isInteger() &&
18241 "Only handle AVX 256-bit vector integer operation");
18242 return Lower256IntArith(Op, DAG);
18245 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18246 assert(Op.getSimpleValueType().is256BitVector() &&
18247 Op.getSimpleValueType().isInteger() &&
18248 "Only handle AVX 256-bit vector integer operation");
18249 return Lower256IntArith(Op, DAG);
18252 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18253 SelectionDAG &DAG) {
18255 MVT VT = Op.getSimpleValueType();
18258 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18260 // Decompose 256-bit ops into smaller 128-bit ops.
18261 if (VT.is256BitVector() && !Subtarget->hasInt256())
18262 return Lower256IntArith(Op, DAG);
18264 SDValue A = Op.getOperand(0);
18265 SDValue B = Op.getOperand(1);
18267 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18268 // pairs, multiply and truncate.
18269 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18270 if (Subtarget->hasInt256()) {
18271 if (VT == MVT::v32i8) {
18272 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18273 SDValue Lo = DAG.getIntPtrConstant(0, dl);
18274 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18275 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18276 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18277 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18278 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18279 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18280 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18281 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18284 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18285 return DAG.getNode(
18286 ISD::TRUNCATE, dl, VT,
18287 DAG.getNode(ISD::MUL, dl, ExVT,
18288 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18289 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18292 assert(VT == MVT::v16i8 &&
18293 "Pre-AVX2 support only supports v16i8 multiplication");
18294 MVT ExVT = MVT::v8i16;
18296 // Extract the lo parts and sign extend to i16
18298 if (Subtarget->hasSSE41()) {
18299 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18300 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18302 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18303 -1, 4, -1, 5, -1, 6, -1, 7};
18304 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18305 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18306 ALo = DAG.getBitcast(ExVT, ALo);
18307 BLo = DAG.getBitcast(ExVT, BLo);
18308 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18309 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18312 // Extract the hi parts and sign extend to i16
18314 if (Subtarget->hasSSE41()) {
18315 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18316 -1, -1, -1, -1, -1, -1, -1, -1};
18317 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18318 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18319 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18320 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18322 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18323 -1, 12, -1, 13, -1, 14, -1, 15};
18324 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18325 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18326 AHi = DAG.getBitcast(ExVT, AHi);
18327 BHi = DAG.getBitcast(ExVT, BHi);
18328 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18329 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18332 // Multiply, mask the lower 8bits of the lo/hi results and pack
18333 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18334 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18335 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18336 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18337 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18340 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18341 if (VT == MVT::v4i32) {
18342 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18343 "Should not custom lower when pmuldq is available!");
18345 // Extract the odd parts.
18346 static const int UnpackMask[] = { 1, -1, 3, -1 };
18347 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18348 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18350 // Multiply the even parts.
18351 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18352 // Now multiply odd parts.
18353 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18355 Evens = DAG.getBitcast(VT, Evens);
18356 Odds = DAG.getBitcast(VT, Odds);
18358 // Merge the two vectors back together with a shuffle. This expands into 2
18360 static const int ShufMask[] = { 0, 4, 2, 6 };
18361 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18364 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18365 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18367 // Ahi = psrlqi(a, 32);
18368 // Bhi = psrlqi(b, 32);
18370 // AloBlo = pmuludq(a, b);
18371 // AloBhi = pmuludq(a, Bhi);
18372 // AhiBlo = pmuludq(Ahi, b);
18374 // AloBhi = psllqi(AloBhi, 32);
18375 // AhiBlo = psllqi(AhiBlo, 32);
18376 // return AloBlo + AloBhi + AhiBlo;
18378 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18379 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18381 SDValue AhiBlo = Ahi;
18382 SDValue AloBhi = Bhi;
18383 // Bit cast to 32-bit vectors for MULUDQ
18384 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18385 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18386 A = DAG.getBitcast(MulVT, A);
18387 B = DAG.getBitcast(MulVT, B);
18388 Ahi = DAG.getBitcast(MulVT, Ahi);
18389 Bhi = DAG.getBitcast(MulVT, Bhi);
18391 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18392 // After shifting right const values the result may be all-zero.
18393 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18394 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18395 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18397 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18398 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18399 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18402 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18403 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18406 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18407 assert(Subtarget->isTargetWin64() && "Unexpected target");
18408 EVT VT = Op.getValueType();
18409 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18410 "Unexpected return type for lowering");
18414 switch (Op->getOpcode()) {
18415 default: llvm_unreachable("Unexpected request for libcall!");
18416 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18417 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18418 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18419 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18420 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18421 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18425 SDValue InChain = DAG.getEntryNode();
18427 TargetLowering::ArgListTy Args;
18428 TargetLowering::ArgListEntry Entry;
18429 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18430 EVT ArgVT = Op->getOperand(i).getValueType();
18431 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18432 "Unexpected argument type for lowering");
18433 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18434 Entry.Node = StackPtr;
18435 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18437 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18438 Entry.Ty = PointerType::get(ArgTy,0);
18439 Entry.isSExt = false;
18440 Entry.isZExt = false;
18441 Args.push_back(Entry);
18444 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18445 getPointerTy(DAG.getDataLayout()));
18447 TargetLowering::CallLoweringInfo CLI(DAG);
18448 CLI.setDebugLoc(dl).setChain(InChain)
18449 .setCallee(getLibcallCallingConv(LC),
18450 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18451 Callee, std::move(Args), 0)
18452 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18454 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18455 return DAG.getBitcast(VT, CallInfo.first);
18458 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18459 SelectionDAG &DAG) {
18460 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18461 MVT VT = Op0.getSimpleValueType();
18464 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18465 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18467 // PMULxD operations multiply each even value (starting at 0) of LHS with
18468 // the related value of RHS and produce a widen result.
18469 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18470 // => <2 x i64> <ae|cg>
18472 // In other word, to have all the results, we need to perform two PMULxD:
18473 // 1. one with the even values.
18474 // 2. one with the odd values.
18475 // To achieve #2, with need to place the odd values at an even position.
18477 // Place the odd value at an even position (basically, shift all values 1
18478 // step to the left):
18479 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18480 // <a|b|c|d> => <b|undef|d|undef>
18481 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18482 // <e|f|g|h> => <f|undef|h|undef>
18483 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18485 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18487 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18488 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18490 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18491 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18492 // => <2 x i64> <ae|cg>
18493 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18494 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18495 // => <2 x i64> <bf|dh>
18496 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18498 // Shuffle it back into the right order.
18499 SDValue Highs, Lows;
18500 if (VT == MVT::v8i32) {
18501 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18502 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18503 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18504 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18506 const int HighMask[] = {1, 5, 3, 7};
18507 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18508 const int LowMask[] = {0, 4, 2, 6};
18509 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18512 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18513 // unsigned multiply.
18514 if (IsSigned && !Subtarget->hasSSE41()) {
18515 SDValue ShAmt = DAG.getConstant(
18517 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18518 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18519 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18520 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18521 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18523 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18524 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18527 // The first result of MUL_LOHI is actually the low value, followed by the
18529 SDValue Ops[] = {Lows, Highs};
18530 return DAG.getMergeValues(Ops, dl);
18533 // Return true if the required (according to Opcode) shift-imm form is natively
18534 // supported by the Subtarget
18535 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18537 if (VT.getScalarSizeInBits() < 16)
18540 if (VT.is512BitVector() &&
18541 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18544 bool LShift = VT.is128BitVector() ||
18545 (VT.is256BitVector() && Subtarget->hasInt256());
18547 bool AShift = LShift && (Subtarget->hasVLX() ||
18548 (VT != MVT::v2i64 && VT != MVT::v4i64));
18549 return (Opcode == ISD::SRA) ? AShift : LShift;
18552 // The shift amount is a variable, but it is the same for all vector lanes.
18553 // These instructions are defined together with shift-immediate.
18555 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18557 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18560 // Return true if the required (according to Opcode) variable-shift form is
18561 // natively supported by the Subtarget
18562 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18565 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18568 // vXi16 supported only on AVX-512, BWI
18569 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18572 if (VT.is512BitVector() || Subtarget->hasVLX())
18575 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18576 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18577 return (Opcode == ISD::SRA) ? AShift : LShift;
18580 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18581 const X86Subtarget *Subtarget) {
18582 MVT VT = Op.getSimpleValueType();
18584 SDValue R = Op.getOperand(0);
18585 SDValue Amt = Op.getOperand(1);
18587 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18588 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18590 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18591 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18592 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18593 SDValue Ex = DAG.getBitcast(ExVT, R);
18595 if (ShiftAmt >= 32) {
18596 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18598 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18599 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18600 ShiftAmt - 32, DAG);
18601 if (VT == MVT::v2i64)
18602 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18603 if (VT == MVT::v4i64)
18604 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18605 {9, 1, 11, 3, 13, 5, 15, 7});
18607 // SRA upper i32, SHL whole i64 and select lower i32.
18608 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18611 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18612 Lower = DAG.getBitcast(ExVT, Lower);
18613 if (VT == MVT::v2i64)
18614 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18615 if (VT == MVT::v4i64)
18616 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18617 {8, 1, 10, 3, 12, 5, 14, 7});
18619 return DAG.getBitcast(VT, Ex);
18622 // Optimize shl/srl/sra with constant shift amount.
18623 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18624 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18625 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18627 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18628 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18630 // i64 SRA needs to be performed as partial shifts.
18631 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18632 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18633 return ArithmeticShiftRight64(ShiftAmt);
18635 if (VT == MVT::v16i8 ||
18636 (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18637 VT == MVT::v64i8) {
18638 unsigned NumElts = VT.getVectorNumElements();
18639 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18641 // Simple i8 add case
18642 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18643 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18645 // ashr(R, 7) === cmp_slt(R, 0)
18646 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18647 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18648 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18651 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18652 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18655 if (Op.getOpcode() == ISD::SHL) {
18656 // Make a large shift.
18657 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18659 SHL = DAG.getBitcast(VT, SHL);
18660 // Zero out the rightmost bits.
18661 return DAG.getNode(ISD::AND, dl, VT, SHL,
18662 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18664 if (Op.getOpcode() == ISD::SRL) {
18665 // Make a large shift.
18666 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18668 SRL = DAG.getBitcast(VT, SRL);
18669 // Zero out the leftmost bits.
18670 return DAG.getNode(ISD::AND, dl, VT, SRL,
18671 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18673 if (Op.getOpcode() == ISD::SRA) {
18674 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18675 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18677 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18678 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18679 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18682 llvm_unreachable("Unknown shift opcode.");
18687 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18688 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18689 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18691 // Peek through any splat that was introduced for i64 shift vectorization.
18692 int SplatIndex = -1;
18693 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18694 if (SVN->isSplat()) {
18695 SplatIndex = SVN->getSplatIndex();
18696 Amt = Amt.getOperand(0);
18697 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18698 "Splat shuffle referencing second operand");
18701 if (Amt.getOpcode() != ISD::BITCAST ||
18702 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18705 Amt = Amt.getOperand(0);
18706 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18707 VT.getVectorNumElements();
18708 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18709 uint64_t ShiftAmt = 0;
18710 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18711 for (unsigned i = 0; i != Ratio; ++i) {
18712 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18716 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18719 // Check remaining shift amounts (if not a splat).
18720 if (SplatIndex < 0) {
18721 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18722 uint64_t ShAmt = 0;
18723 for (unsigned j = 0; j != Ratio; ++j) {
18724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18728 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18730 if (ShAmt != ShiftAmt)
18735 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18736 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18738 if (Op.getOpcode() == ISD::SRA)
18739 return ArithmeticShiftRight64(ShiftAmt);
18745 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18746 const X86Subtarget* Subtarget) {
18747 MVT VT = Op.getSimpleValueType();
18749 SDValue R = Op.getOperand(0);
18750 SDValue Amt = Op.getOperand(1);
18752 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18753 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18755 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18756 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18758 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18760 MVT EltVT = VT.getVectorElementType();
18762 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18763 // Check if this build_vector node is doing a splat.
18764 // If so, then set BaseShAmt equal to the splat value.
18765 BaseShAmt = BV->getSplatValue();
18766 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18767 BaseShAmt = SDValue();
18769 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18770 Amt = Amt.getOperand(0);
18772 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18773 if (SVN && SVN->isSplat()) {
18774 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18775 SDValue InVec = Amt.getOperand(0);
18776 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18777 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18778 "Unexpected shuffle index found!");
18779 BaseShAmt = InVec.getOperand(SplatIdx);
18780 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18781 if (ConstantSDNode *C =
18782 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18783 if (C->getZExtValue() == SplatIdx)
18784 BaseShAmt = InVec.getOperand(1);
18789 // Avoid introducing an extract element from a shuffle.
18790 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18791 DAG.getIntPtrConstant(SplatIdx, dl));
18795 if (BaseShAmt.getNode()) {
18796 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18797 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18798 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18799 else if (EltVT.bitsLT(MVT::i32))
18800 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18802 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18806 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18807 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18808 Amt.getOpcode() == ISD::BITCAST &&
18809 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18810 Amt = Amt.getOperand(0);
18811 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18812 VT.getVectorNumElements();
18813 std::vector<SDValue> Vals(Ratio);
18814 for (unsigned i = 0; i != Ratio; ++i)
18815 Vals[i] = Amt.getOperand(i);
18816 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18817 for (unsigned j = 0; j != Ratio; ++j)
18818 if (Vals[j] != Amt.getOperand(i + j))
18822 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18823 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18828 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18829 SelectionDAG &DAG) {
18830 MVT VT = Op.getSimpleValueType();
18832 SDValue R = Op.getOperand(0);
18833 SDValue Amt = Op.getOperand(1);
18835 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18836 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18838 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18841 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18844 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18847 // XOP has 128-bit variable logical/arithmetic shifts.
18848 // +ve/-ve Amt = shift left/right.
18849 if (Subtarget->hasXOP() &&
18850 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18851 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18852 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18853 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18854 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18856 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18857 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18858 if (Op.getOpcode() == ISD::SRA)
18859 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18862 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18863 // shifts per-lane and then shuffle the partial results back together.
18864 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18865 // Splat the shift amounts so the scalar shifts above will catch it.
18866 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18867 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18868 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18869 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18870 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18873 // i64 vector arithmetic shift can be emulated with the transform:
18874 // M = lshr(SIGN_BIT, Amt)
18875 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18876 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18877 Op.getOpcode() == ISD::SRA) {
18878 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18879 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18880 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18881 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18882 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18886 // If possible, lower this packed shift into a vector multiply instead of
18887 // expanding it into a sequence of scalar shifts.
18888 // Do this only if the vector shift count is a constant build_vector.
18889 if (Op.getOpcode() == ISD::SHL &&
18890 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18891 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18892 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18893 SmallVector<SDValue, 8> Elts;
18894 MVT SVT = VT.getVectorElementType();
18895 unsigned SVTBits = SVT.getSizeInBits();
18896 APInt One(SVTBits, 1);
18897 unsigned NumElems = VT.getVectorNumElements();
18899 for (unsigned i=0; i !=NumElems; ++i) {
18900 SDValue Op = Amt->getOperand(i);
18901 if (Op->getOpcode() == ISD::UNDEF) {
18902 Elts.push_back(Op);
18906 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18907 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18908 uint64_t ShAmt = C.getZExtValue();
18909 if (ShAmt >= SVTBits) {
18910 Elts.push_back(DAG.getUNDEF(SVT));
18913 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18915 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18916 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18919 // Lower SHL with variable shift amount.
18920 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18921 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18923 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18924 DAG.getConstant(0x3f800000U, dl, VT));
18925 Op = DAG.getBitcast(MVT::v4f32, Op);
18926 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18927 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18930 // If possible, lower this shift as a sequence of two shifts by
18931 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18933 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18935 // Could be rewritten as:
18936 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18938 // The advantage is that the two shifts from the example would be
18939 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18940 // the vector shift into four scalar shifts plus four pairs of vector
18942 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18943 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18944 unsigned TargetOpcode = X86ISD::MOVSS;
18945 bool CanBeSimplified;
18946 // The splat value for the first packed shift (the 'X' from the example).
18947 SDValue Amt1 = Amt->getOperand(0);
18948 // The splat value for the second packed shift (the 'Y' from the example).
18949 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18950 Amt->getOperand(2);
18952 // See if it is possible to replace this node with a sequence of
18953 // two shifts followed by a MOVSS/MOVSD
18954 if (VT == MVT::v4i32) {
18955 // Check if it is legal to use a MOVSS.
18956 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18957 Amt2 == Amt->getOperand(3);
18958 if (!CanBeSimplified) {
18959 // Otherwise, check if we can still simplify this node using a MOVSD.
18960 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18961 Amt->getOperand(2) == Amt->getOperand(3);
18962 TargetOpcode = X86ISD::MOVSD;
18963 Amt2 = Amt->getOperand(2);
18966 // Do similar checks for the case where the machine value type
18968 CanBeSimplified = Amt1 == Amt->getOperand(1);
18969 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18970 CanBeSimplified = Amt2 == Amt->getOperand(i);
18972 if (!CanBeSimplified) {
18973 TargetOpcode = X86ISD::MOVSD;
18974 CanBeSimplified = true;
18975 Amt2 = Amt->getOperand(4);
18976 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18977 CanBeSimplified = Amt1 == Amt->getOperand(i);
18978 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18979 CanBeSimplified = Amt2 == Amt->getOperand(j);
18983 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18984 isa<ConstantSDNode>(Amt2)) {
18985 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18986 MVT CastVT = MVT::v4i32;
18988 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18989 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18991 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18992 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18993 if (TargetOpcode == X86ISD::MOVSD)
18994 CastVT = MVT::v2i64;
18995 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18996 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18997 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18999 return DAG.getBitcast(VT, Result);
19003 // v4i32 Non Uniform Shifts.
19004 // If the shift amount is constant we can shift each lane using the SSE2
19005 // immediate shifts, else we need to zero-extend each lane to the lower i64
19006 // and shift using the SSE2 variable shifts.
19007 // The separate results can then be blended together.
19008 if (VT == MVT::v4i32) {
19009 unsigned Opc = Op.getOpcode();
19010 SDValue Amt0, Amt1, Amt2, Amt3;
19011 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
19012 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
19013 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
19014 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
19015 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
19017 // ISD::SHL is handled above but we include it here for completeness.
19020 llvm_unreachable("Unknown target vector shift node");
19022 Opc = X86ISD::VSHL;
19025 Opc = X86ISD::VSRL;
19028 Opc = X86ISD::VSRA;
19031 // The SSE2 shifts use the lower i64 as the same shift amount for
19032 // all lanes and the upper i64 is ignored. These shuffle masks
19033 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
19034 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19035 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
19036 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
19037 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
19038 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
19041 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
19042 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
19043 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
19044 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
19045 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
19046 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
19047 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
19050 if (VT == MVT::v16i8 ||
19051 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
19052 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
19053 unsigned ShiftOpcode = Op->getOpcode();
19055 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
19056 // On SSE41 targets we make use of the fact that VSELECT lowers
19057 // to PBLENDVB which selects bytes based just on the sign bit.
19058 if (Subtarget->hasSSE41()) {
19059 V0 = DAG.getBitcast(VT, V0);
19060 V1 = DAG.getBitcast(VT, V1);
19061 Sel = DAG.getBitcast(VT, Sel);
19062 return DAG.getBitcast(SelVT,
19063 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
19065 // On pre-SSE41 targets we test for the sign bit by comparing to
19066 // zero - a negative value will set all bits of the lanes to true
19067 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
19068 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
19069 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
19070 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19073 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19074 // We can safely do this using i16 shifts as we're only interested in
19075 // the 3 lower bits of each byte.
19076 Amt = DAG.getBitcast(ExtVT, Amt);
19077 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19078 Amt = DAG.getBitcast(VT, Amt);
19080 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19081 // r = VSELECT(r, shift(r, 4), a);
19083 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19084 R = SignBitSelect(VT, Amt, M, R);
19087 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19089 // r = VSELECT(r, shift(r, 2), a);
19090 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19091 R = SignBitSelect(VT, Amt, M, R);
19094 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19096 // return VSELECT(r, shift(r, 1), a);
19097 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19098 R = SignBitSelect(VT, Amt, M, R);
19102 if (Op->getOpcode() == ISD::SRA) {
19103 // For SRA we need to unpack each byte to the higher byte of a i16 vector
19104 // so we can correctly sign extend. We don't care what happens to the
19106 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19107 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19108 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19109 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19110 ALo = DAG.getBitcast(ExtVT, ALo);
19111 AHi = DAG.getBitcast(ExtVT, AHi);
19112 RLo = DAG.getBitcast(ExtVT, RLo);
19113 RHi = DAG.getBitcast(ExtVT, RHi);
19115 // r = VSELECT(r, shift(r, 4), a);
19116 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19117 DAG.getConstant(4, dl, ExtVT));
19118 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19119 DAG.getConstant(4, dl, ExtVT));
19120 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19121 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19124 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19125 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19127 // r = VSELECT(r, shift(r, 2), a);
19128 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19129 DAG.getConstant(2, dl, ExtVT));
19130 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19131 DAG.getConstant(2, dl, ExtVT));
19132 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19133 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19136 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19137 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19139 // r = VSELECT(r, shift(r, 1), a);
19140 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19141 DAG.getConstant(1, dl, ExtVT));
19142 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19143 DAG.getConstant(1, dl, ExtVT));
19144 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19145 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19147 // Logical shift the result back to the lower byte, leaving a zero upper
19149 // meaning that we can safely pack with PACKUSWB.
19151 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19153 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19154 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19158 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19159 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19160 // solution better.
19161 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19162 MVT ExtVT = MVT::v8i32;
19164 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19165 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19166 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19167 return DAG.getNode(ISD::TRUNCATE, dl, VT,
19168 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19171 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19172 MVT ExtVT = MVT::v8i32;
19173 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19174 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19175 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19176 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19177 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19178 ALo = DAG.getBitcast(ExtVT, ALo);
19179 AHi = DAG.getBitcast(ExtVT, AHi);
19180 RLo = DAG.getBitcast(ExtVT, RLo);
19181 RHi = DAG.getBitcast(ExtVT, RHi);
19182 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19183 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19184 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19185 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19186 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19189 if (VT == MVT::v8i16) {
19190 unsigned ShiftOpcode = Op->getOpcode();
19192 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19193 // On SSE41 targets we make use of the fact that VSELECT lowers
19194 // to PBLENDVB which selects bytes based just on the sign bit.
19195 if (Subtarget->hasSSE41()) {
19196 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19197 V0 = DAG.getBitcast(ExtVT, V0);
19198 V1 = DAG.getBitcast(ExtVT, V1);
19199 Sel = DAG.getBitcast(ExtVT, Sel);
19200 return DAG.getBitcast(
19201 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19203 // On pre-SSE41 targets we splat the sign bit - a negative value will
19204 // set all bits of the lanes to true and VSELECT uses that in
19205 // its OR(AND(V0,C),AND(V1,~C)) lowering.
19207 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19208 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19211 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19212 if (Subtarget->hasSSE41()) {
19213 // On SSE41 targets we need to replicate the shift mask in both
19214 // bytes for PBLENDVB.
19217 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19218 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19220 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19223 // r = VSELECT(r, shift(r, 8), a);
19224 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19225 R = SignBitSelect(Amt, M, R);
19228 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19230 // r = VSELECT(r, shift(r, 4), a);
19231 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19232 R = SignBitSelect(Amt, M, R);
19235 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19237 // r = VSELECT(r, shift(r, 2), a);
19238 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19239 R = SignBitSelect(Amt, M, R);
19242 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19244 // return VSELECT(r, shift(r, 1), a);
19245 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19246 R = SignBitSelect(Amt, M, R);
19250 // Decompose 256-bit shifts into smaller 128-bit shifts.
19251 if (VT.is256BitVector()) {
19252 unsigned NumElems = VT.getVectorNumElements();
19253 MVT EltVT = VT.getVectorElementType();
19254 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19256 // Extract the two vectors
19257 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19258 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19260 // Recreate the shift amount vectors
19261 SDValue Amt1, Amt2;
19262 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19263 // Constant shift amount
19264 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19265 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19266 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19268 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19269 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19271 // Variable shift amount
19272 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19273 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19276 // Issue new vector shifts for the smaller types
19277 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19278 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19280 // Concatenate the result back
19281 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19287 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19288 SelectionDAG &DAG) {
19289 MVT VT = Op.getSimpleValueType();
19291 SDValue R = Op.getOperand(0);
19292 SDValue Amt = Op.getOperand(1);
19294 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19295 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19296 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19298 // XOP has 128-bit vector variable + immediate rotates.
19299 // +ve/-ve Amt = rotate left/right.
19301 // Split 256-bit integers.
19302 if (VT.is256BitVector())
19303 return Lower256IntArith(Op, DAG);
19305 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19307 // Attempt to rotate by immediate.
19308 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19309 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19310 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19311 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19312 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19313 DAG.getConstant(RotateAmt, DL, MVT::i8));
19317 // Use general rotate by variable (per-element).
19318 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19321 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19322 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19323 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19324 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19325 // has only one use.
19326 SDNode *N = Op.getNode();
19327 SDValue LHS = N->getOperand(0);
19328 SDValue RHS = N->getOperand(1);
19329 unsigned BaseOp = 0;
19332 switch (Op.getOpcode()) {
19333 default: llvm_unreachable("Unknown ovf instruction!");
19335 // A subtract of one will be selected as a INC. Note that INC doesn't
19336 // set CF, so we can't do this for UADDO.
19337 if (isOneConstant(RHS)) {
19338 BaseOp = X86ISD::INC;
19339 Cond = X86::COND_O;
19342 BaseOp = X86ISD::ADD;
19343 Cond = X86::COND_O;
19346 BaseOp = X86ISD::ADD;
19347 Cond = X86::COND_B;
19350 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19351 // set CF, so we can't do this for USUBO.
19352 if (isOneConstant(RHS)) {
19353 BaseOp = X86ISD::DEC;
19354 Cond = X86::COND_O;
19357 BaseOp = X86ISD::SUB;
19358 Cond = X86::COND_O;
19361 BaseOp = X86ISD::SUB;
19362 Cond = X86::COND_B;
19365 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19366 Cond = X86::COND_O;
19368 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19369 if (N->getValueType(0) == MVT::i8) {
19370 BaseOp = X86ISD::UMUL8;
19371 Cond = X86::COND_O;
19374 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19376 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19379 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19380 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19381 SDValue(Sum.getNode(), 2));
19383 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19387 // Also sets EFLAGS.
19388 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19389 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19392 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19393 DAG.getConstant(Cond, DL, MVT::i32),
19394 SDValue(Sum.getNode(), 1));
19396 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19399 /// Returns true if the operand type is exactly twice the native width, and
19400 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19401 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19402 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19403 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19404 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19407 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19408 else if (OpWidth == 128)
19409 return Subtarget->hasCmpxchg16b();
19414 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19415 return needsCmpXchgNb(SI->getValueOperand()->getType());
19418 // Note: this turns large loads into lock cmpxchg8b/16b.
19419 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19420 TargetLowering::AtomicExpansionKind
19421 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19422 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19423 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19424 : AtomicExpansionKind::None;
19427 TargetLowering::AtomicExpansionKind
19428 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19429 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19430 Type *MemType = AI->getType();
19432 // If the operand is too big, we must see if cmpxchg8/16b is available
19433 // and default to library calls otherwise.
19434 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19435 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19436 : AtomicExpansionKind::None;
19439 AtomicRMWInst::BinOp Op = AI->getOperation();
19442 llvm_unreachable("Unknown atomic operation");
19443 case AtomicRMWInst::Xchg:
19444 case AtomicRMWInst::Add:
19445 case AtomicRMWInst::Sub:
19446 // It's better to use xadd, xsub or xchg for these in all cases.
19447 return AtomicExpansionKind::None;
19448 case AtomicRMWInst::Or:
19449 case AtomicRMWInst::And:
19450 case AtomicRMWInst::Xor:
19451 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19452 // prefix to a normal instruction for these operations.
19453 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19454 : AtomicExpansionKind::None;
19455 case AtomicRMWInst::Nand:
19456 case AtomicRMWInst::Max:
19457 case AtomicRMWInst::Min:
19458 case AtomicRMWInst::UMax:
19459 case AtomicRMWInst::UMin:
19460 // These always require a non-trivial set of data operations on x86. We must
19461 // use a cmpxchg loop.
19462 return AtomicExpansionKind::CmpXChg;
19466 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19467 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19468 // no-sse2). There isn't any reason to disable it if the target processor
19470 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19474 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19475 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19476 Type *MemType = AI->getType();
19477 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19478 // there is no benefit in turning such RMWs into loads, and it is actually
19479 // harmful as it introduces a mfence.
19480 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19483 auto Builder = IRBuilder<>(AI);
19484 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19485 auto SynchScope = AI->getSynchScope();
19486 // We must restrict the ordering to avoid generating loads with Release or
19487 // ReleaseAcquire orderings.
19488 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19489 auto Ptr = AI->getPointerOperand();
19491 // Before the load we need a fence. Here is an example lifted from
19492 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19495 // x.store(1, relaxed);
19496 // r1 = y.fetch_add(0, release);
19498 // y.fetch_add(42, acquire);
19499 // r2 = x.load(relaxed);
19500 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19501 // lowered to just a load without a fence. A mfence flushes the store buffer,
19502 // making the optimization clearly correct.
19503 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19504 // otherwise, we might be able to be more aggressive on relaxed idempotent
19505 // rmw. In practice, they do not look useful, so we don't try to be
19506 // especially clever.
19507 if (SynchScope == SingleThread)
19508 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19509 // the IR level, so we must wrap it in an intrinsic.
19512 if (!hasMFENCE(*Subtarget))
19513 // FIXME: it might make sense to use a locked operation here but on a
19514 // different cache-line to prevent cache-line bouncing. In practice it
19515 // is probably a small win, and x86 processors without mfence are rare
19516 // enough that we do not bother.
19520 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19521 Builder.CreateCall(MFence, {});
19523 // Finally we can emit the atomic load.
19524 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19525 AI->getType()->getPrimitiveSizeInBits());
19526 Loaded->setAtomic(Order, SynchScope);
19527 AI->replaceAllUsesWith(Loaded);
19528 AI->eraseFromParent();
19532 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19533 SelectionDAG &DAG) {
19535 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19536 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19537 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19538 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19540 // The only fence that needs an instruction is a sequentially-consistent
19541 // cross-thread fence.
19542 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19543 if (hasMFENCE(*Subtarget))
19544 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19546 SDValue Chain = Op.getOperand(0);
19547 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19549 DAG.getRegister(X86::ESP, MVT::i32), // Base
19550 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19551 DAG.getRegister(0, MVT::i32), // Index
19552 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19553 DAG.getRegister(0, MVT::i32), // Segment.
19557 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19558 return SDValue(Res, 0);
19561 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19562 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19565 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19566 SelectionDAG &DAG) {
19567 MVT T = Op.getSimpleValueType();
19571 switch(T.SimpleTy) {
19572 default: llvm_unreachable("Invalid value type!");
19573 case MVT::i8: Reg = X86::AL; size = 1; break;
19574 case MVT::i16: Reg = X86::AX; size = 2; break;
19575 case MVT::i32: Reg = X86::EAX; size = 4; break;
19577 assert(Subtarget->is64Bit() && "Node not type legal!");
19578 Reg = X86::RAX; size = 8;
19581 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19582 Op.getOperand(2), SDValue());
19583 SDValue Ops[] = { cpIn.getValue(0),
19586 DAG.getTargetConstant(size, DL, MVT::i8),
19587 cpIn.getValue(1) };
19588 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19589 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19590 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19594 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19595 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19596 MVT::i32, cpOut.getValue(2));
19597 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19598 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19601 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19602 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19603 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19607 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19608 SelectionDAG &DAG) {
19609 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19610 MVT DstVT = Op.getSimpleValueType();
19612 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
19613 SrcVT == MVT::i64) {
19614 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19615 if (DstVT != MVT::f64)
19616 // This conversion needs to be expanded.
19619 SDValue Op0 = Op->getOperand(0);
19620 SmallVector<SDValue, 16> Elts;
19624 if (SrcVT.isVector()) {
19625 NumElts = SrcVT.getVectorNumElements();
19626 SVT = SrcVT.getVectorElementType();
19628 // Widen the vector in input in the case of MVT::v2i32.
19629 // Example: from MVT::v2i32 to MVT::v4i32.
19630 for (unsigned i = 0, e = NumElts; i != e; ++i)
19631 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
19632 DAG.getIntPtrConstant(i, dl)));
19634 assert(SrcVT == MVT::i64 && !Subtarget->is64Bit() &&
19635 "Unexpected source type in LowerBITCAST");
19636 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19637 DAG.getIntPtrConstant(0, dl)));
19638 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
19639 DAG.getIntPtrConstant(1, dl)));
19643 // Explicitly mark the extra elements as Undef.
19644 Elts.append(NumElts, DAG.getUNDEF(SVT));
19646 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19647 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19648 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19649 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19650 DAG.getIntPtrConstant(0, dl));
19653 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19654 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19655 assert((DstVT == MVT::i64 ||
19656 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19657 "Unexpected custom BITCAST");
19658 // i64 <=> MMX conversions are Legal.
19659 if (SrcVT==MVT::i64 && DstVT.isVector())
19661 if (DstVT==MVT::i64 && SrcVT.isVector())
19663 // MMX <=> MMX conversions are Legal.
19664 if (SrcVT.isVector() && DstVT.isVector())
19666 // All other conversions need to be expanded.
19670 /// Compute the horizontal sum of bytes in V for the elements of VT.
19672 /// Requires V to be a byte vector and VT to be an integer vector type with
19673 /// wider elements than V's type. The width of the elements of VT determines
19674 /// how many bytes of V are summed horizontally to produce each element of the
19676 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19677 const X86Subtarget *Subtarget,
19678 SelectionDAG &DAG) {
19680 MVT ByteVecVT = V.getSimpleValueType();
19681 MVT EltVT = VT.getVectorElementType();
19682 int NumElts = VT.getVectorNumElements();
19683 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19684 "Expected value to have byte element type.");
19685 assert(EltVT != MVT::i8 &&
19686 "Horizontal byte sum only makes sense for wider elements!");
19687 unsigned VecSize = VT.getSizeInBits();
19688 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19690 // PSADBW instruction horizontally add all bytes and leave the result in i64
19691 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19692 if (EltVT == MVT::i64) {
19693 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19694 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19695 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19696 return DAG.getBitcast(VT, V);
19699 if (EltVT == MVT::i32) {
19700 // We unpack the low half and high half into i32s interleaved with zeros so
19701 // that we can use PSADBW to horizontally sum them. The most useful part of
19702 // this is that it lines up the results of two PSADBW instructions to be
19703 // two v2i64 vectors which concatenated are the 4 population counts. We can
19704 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19705 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19706 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19707 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19709 // Do the horizontal sums into two v2i64s.
19710 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19711 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19712 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19713 DAG.getBitcast(ByteVecVT, Low), Zeros);
19714 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19715 DAG.getBitcast(ByteVecVT, High), Zeros);
19717 // Merge them together.
19718 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19719 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19720 DAG.getBitcast(ShortVecVT, Low),
19721 DAG.getBitcast(ShortVecVT, High));
19723 return DAG.getBitcast(VT, V);
19726 // The only element type left is i16.
19727 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19729 // To obtain pop count for each i16 element starting from the pop count for
19730 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19731 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19732 // directly supported.
19733 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19734 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19735 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19736 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19737 DAG.getBitcast(ByteVecVT, V));
19738 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19741 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19742 const X86Subtarget *Subtarget,
19743 SelectionDAG &DAG) {
19744 MVT VT = Op.getSimpleValueType();
19745 MVT EltVT = VT.getVectorElementType();
19746 unsigned VecSize = VT.getSizeInBits();
19748 // Implement a lookup table in register by using an algorithm based on:
19749 // http://wm.ite.pl/articles/sse-popcount.html
19751 // The general idea is that every lower byte nibble in the input vector is an
19752 // index into a in-register pre-computed pop count table. We then split up the
19753 // input vector in two new ones: (1) a vector with only the shifted-right
19754 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19755 // masked out higher ones) for each byte. PSHUB is used separately with both
19756 // to index the in-register table. Next, both are added and the result is a
19757 // i8 vector where each element contains the pop count for input byte.
19759 // To obtain the pop count for elements != i8, we follow up with the same
19760 // approach and use additional tricks as described below.
19762 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19763 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19764 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19765 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19767 int NumByteElts = VecSize / 8;
19768 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19769 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19770 SmallVector<SDValue, 16> LUTVec;
19771 for (int i = 0; i < NumByteElts; ++i)
19772 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19773 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19774 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19775 DAG.getConstant(0x0F, DL, MVT::i8));
19776 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19779 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19780 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19781 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19784 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19786 // The input vector is used as the shuffle mask that index elements into the
19787 // LUT. After counting low and high nibbles, add the vector to obtain the
19788 // final pop count per i8 element.
19789 SDValue HighPopCnt =
19790 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19791 SDValue LowPopCnt =
19792 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19793 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19795 if (EltVT == MVT::i8)
19798 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19801 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19802 const X86Subtarget *Subtarget,
19803 SelectionDAG &DAG) {
19804 MVT VT = Op.getSimpleValueType();
19805 assert(VT.is128BitVector() &&
19806 "Only 128-bit vector bitmath lowering supported.");
19808 int VecSize = VT.getSizeInBits();
19809 MVT EltVT = VT.getVectorElementType();
19810 int Len = EltVT.getSizeInBits();
19812 // This is the vectorized version of the "best" algorithm from
19813 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19814 // with a minor tweak to use a series of adds + shifts instead of vector
19815 // multiplications. Implemented for all integer vector types. We only use
19816 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19817 // much faster, even faster than using native popcnt instructions.
19819 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19820 MVT VT = V.getSimpleValueType();
19821 SmallVector<SDValue, 32> Shifters(
19822 VT.getVectorNumElements(),
19823 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19824 return DAG.getNode(OpCode, DL, VT, V,
19825 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19827 auto GetMask = [&](SDValue V, APInt Mask) {
19828 MVT VT = V.getSimpleValueType();
19829 SmallVector<SDValue, 32> Masks(
19830 VT.getVectorNumElements(),
19831 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19832 return DAG.getNode(ISD::AND, DL, VT, V,
19833 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19836 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19837 // x86, so set the SRL type to have elements at least i16 wide. This is
19838 // correct because all of our SRLs are followed immediately by a mask anyways
19839 // that handles any bits that sneak into the high bits of the byte elements.
19840 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19844 // v = v - ((v >> 1) & 0x55555555...)
19846 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19847 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19848 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19850 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19851 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19852 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19853 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19854 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19856 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19857 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19858 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19859 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19861 // At this point, V contains the byte-wise population count, and we are
19862 // merely doing a horizontal sum if necessary to get the wider element
19864 if (EltVT == MVT::i8)
19867 return LowerHorizontalByteSum(
19868 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19872 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19873 SelectionDAG &DAG) {
19874 MVT VT = Op.getSimpleValueType();
19875 // FIXME: Need to add AVX-512 support here!
19876 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19877 "Unknown CTPOP type to handle");
19878 SDLoc DL(Op.getNode());
19879 SDValue Op0 = Op.getOperand(0);
19881 if (!Subtarget->hasSSSE3()) {
19882 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19883 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19884 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19887 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19888 unsigned NumElems = VT.getVectorNumElements();
19890 // Extract each 128-bit vector, compute pop count and concat the result.
19891 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19892 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19894 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19895 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19896 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19899 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19902 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19903 SelectionDAG &DAG) {
19904 assert(Op.getSimpleValueType().isVector() &&
19905 "We only do custom lowering for vector population count.");
19906 return LowerVectorCTPOP(Op, Subtarget, DAG);
19909 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19910 SDNode *Node = Op.getNode();
19912 EVT T = Node->getValueType(0);
19913 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19914 DAG.getConstant(0, dl, T), Node->getOperand(2));
19915 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19916 cast<AtomicSDNode>(Node)->getMemoryVT(),
19917 Node->getOperand(0),
19918 Node->getOperand(1), negOp,
19919 cast<AtomicSDNode>(Node)->getMemOperand(),
19920 cast<AtomicSDNode>(Node)->getOrdering(),
19921 cast<AtomicSDNode>(Node)->getSynchScope());
19924 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19925 SDNode *Node = Op.getNode();
19927 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19929 // Convert seq_cst store -> xchg
19930 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19931 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19932 // (The only way to get a 16-byte store is cmpxchg16b)
19933 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19934 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19935 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19936 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19937 cast<AtomicSDNode>(Node)->getMemoryVT(),
19938 Node->getOperand(0),
19939 Node->getOperand(1), Node->getOperand(2),
19940 cast<AtomicSDNode>(Node)->getMemOperand(),
19941 cast<AtomicSDNode>(Node)->getOrdering(),
19942 cast<AtomicSDNode>(Node)->getSynchScope());
19943 return Swap.getValue(1);
19945 // Other atomic stores have a simple pattern.
19949 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19950 MVT VT = Op.getNode()->getSimpleValueType(0);
19952 // Let legalize expand this if it isn't a legal type yet.
19953 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19956 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19959 bool ExtraOp = false;
19960 switch (Op.getOpcode()) {
19961 default: llvm_unreachable("Invalid code");
19962 case ISD::ADDC: Opc = X86ISD::ADD; break;
19963 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19964 case ISD::SUBC: Opc = X86ISD::SUB; break;
19965 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19969 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19971 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19972 Op.getOperand(1), Op.getOperand(2));
19975 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19976 SelectionDAG &DAG) {
19977 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19979 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19980 // which returns the values as { float, float } (in XMM0) or
19981 // { double, double } (which is returned in XMM0, XMM1).
19983 SDValue Arg = Op.getOperand(0);
19984 EVT ArgVT = Arg.getValueType();
19985 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19987 TargetLowering::ArgListTy Args;
19988 TargetLowering::ArgListEntry Entry;
19992 Entry.isSExt = false;
19993 Entry.isZExt = false;
19994 Args.push_back(Entry);
19996 bool isF64 = ArgVT == MVT::f64;
19997 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19998 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19999 // the results are returned via SRet in memory.
20000 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
20001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20003 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
20005 Type *RetTy = isF64
20006 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
20007 : (Type*)VectorType::get(ArgTy, 4);
20009 TargetLowering::CallLoweringInfo CLI(DAG);
20010 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
20011 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
20013 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
20016 // Returned in xmm0 and xmm1.
20017 return CallResult.first;
20019 // Returned in bits 0:31 and 32:64 xmm0.
20020 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20021 CallResult.first, DAG.getIntPtrConstant(0, dl));
20022 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
20023 CallResult.first, DAG.getIntPtrConstant(1, dl));
20024 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
20025 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
20028 /// Widen a vector input to a vector of NVT. The
20029 /// input vector must have the same element type as NVT.
20030 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
20031 bool FillWithZeroes = false) {
20032 // Check if InOp already has the right width.
20033 MVT InVT = InOp.getSimpleValueType();
20037 if (InOp.isUndef())
20038 return DAG.getUNDEF(NVT);
20040 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
20041 "input and widen element type must match");
20043 unsigned InNumElts = InVT.getVectorNumElements();
20044 unsigned WidenNumElts = NVT.getVectorNumElements();
20045 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
20046 "Unexpected request for vector widening");
20048 EVT EltVT = NVT.getVectorElementType();
20051 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
20052 InOp.getNumOperands() == 2) {
20053 SDValue N1 = InOp.getOperand(1);
20054 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
20056 InOp = InOp.getOperand(0);
20057 InVT = InOp.getSimpleValueType();
20058 InNumElts = InVT.getVectorNumElements();
20061 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
20062 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
20063 SmallVector<SDValue, 16> Ops;
20064 for (unsigned i = 0; i < InNumElts; ++i)
20065 Ops.push_back(InOp.getOperand(i));
20067 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
20068 DAG.getUNDEF(EltVT);
20069 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
20070 Ops.push_back(FillVal);
20071 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
20073 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
20075 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
20076 InOp, DAG.getIntPtrConstant(0, dl));
20079 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
20080 SelectionDAG &DAG) {
20081 assert(Subtarget->hasAVX512() &&
20082 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20084 // X86 scatter kills mask register, so its type should be added to
20085 // the list of return values.
20086 // If the "scatter" has 2 return values, it is already handled.
20087 if (Op.getNode()->getNumValues() == 2)
20090 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20091 SDValue Src = N->getValue();
20092 MVT VT = Src.getSimpleValueType();
20093 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20096 SDValue NewScatter;
20097 SDValue Index = N->getIndex();
20098 SDValue Mask = N->getMask();
20099 SDValue Chain = N->getChain();
20100 SDValue BasePtr = N->getBasePtr();
20101 MVT MemVT = N->getMemoryVT().getSimpleVT();
20102 MVT IndexVT = Index.getSimpleValueType();
20103 MVT MaskVT = Mask.getSimpleValueType();
20105 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20106 // The v2i32 value was promoted to v2i64.
20107 // Now we "redo" the type legalizer's work and widen the original
20108 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20110 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20111 "Unexpected memory type");
20112 int ShuffleMask[] = {0, 2, -1, -1};
20113 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20114 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20115 // Now we have 4 elements instead of 2.
20116 // Expand the index.
20117 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20118 Index = ExtendToType(Index, NewIndexVT, DAG);
20120 // Expand the mask with zeroes
20121 // Mask may be <2 x i64> or <2 x i1> at this moment
20122 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20123 "Unexpected mask type");
20124 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20125 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20129 unsigned NumElts = VT.getVectorNumElements();
20130 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20131 !Index.getSimpleValueType().is512BitVector()) {
20132 // AVX512F supports only 512-bit vectors. Or data or index should
20133 // be 512 bit wide. If now the both index and data are 256-bit, but
20134 // the vector contains 8 elements, we just sign-extend the index
20135 if (IndexVT == MVT::v8i32)
20136 // Just extend index
20137 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20139 // The minimal number of elts in scatter is 8
20142 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20143 // Use original index here, do not modify the index twice
20144 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20145 if (IndexVT.getScalarType() == MVT::i32)
20146 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20149 // At this point we have promoted mask operand
20150 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20151 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20152 // Use the original mask here, do not modify the mask twice
20153 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20155 // The value that should be stored
20156 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20157 Src = ExtendToType(Src, NewVT, DAG);
20160 // If the mask is "wide" at this point - truncate it to i1 vector
20161 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20162 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20164 // The mask is killed by scatter, add it to the values
20165 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20166 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20167 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20168 N->getMemOperand());
20169 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20170 return SDValue(NewScatter.getNode(), 0);
20173 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20174 SelectionDAG &DAG) {
20176 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20177 MVT VT = Op.getSimpleValueType();
20178 SDValue Mask = N->getMask();
20181 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20182 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20183 // This operation is legal for targets with VLX, but without
20184 // VLX the vector should be widened to 512 bit
20185 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20186 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20187 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20188 SDValue Src0 = N->getSrc0();
20189 Src0 = ExtendToType(Src0, WideDataVT, DAG);
20190 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20191 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20192 N->getBasePtr(), Mask, Src0,
20193 N->getMemoryVT(), N->getMemOperand(),
20194 N->getExtensionType());
20196 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20197 NewLoad.getValue(0),
20198 DAG.getIntPtrConstant(0, dl));
20199 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20200 return DAG.getMergeValues(RetOps, dl);
20205 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20206 SelectionDAG &DAG) {
20207 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20208 SDValue DataToStore = N->getValue();
20209 MVT VT = DataToStore.getSimpleValueType();
20210 SDValue Mask = N->getMask();
20213 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20214 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20215 // This operation is legal for targets with VLX, but without
20216 // VLX the vector should be widened to 512 bit
20217 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20218 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20219 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20220 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20221 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20222 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20223 Mask, N->getMemoryVT(), N->getMemOperand(),
20224 N->isTruncatingStore());
20229 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20230 SelectionDAG &DAG) {
20231 assert(Subtarget->hasAVX512() &&
20232 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20234 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20236 MVT VT = Op.getSimpleValueType();
20237 SDValue Index = N->getIndex();
20238 SDValue Mask = N->getMask();
20239 SDValue Src0 = N->getValue();
20240 MVT IndexVT = Index.getSimpleValueType();
20241 MVT MaskVT = Mask.getSimpleValueType();
20243 unsigned NumElts = VT.getVectorNumElements();
20244 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20246 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20247 !Index.getSimpleValueType().is512BitVector()) {
20248 // AVX512F supports only 512-bit vectors. Or data or index should
20249 // be 512 bit wide. If now the both index and data are 256-bit, but
20250 // the vector contains 8 elements, we just sign-extend the index
20251 if (NumElts == 8) {
20252 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20253 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
20254 N->getOperand(3), Index };
20255 DAG.UpdateNodeOperands(N, Ops);
20259 // Minimal number of elements in Gather
20262 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20263 Index = ExtendToType(Index, NewIndexVT, DAG);
20264 if (IndexVT.getScalarType() == MVT::i32)
20265 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20268 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20269 // At this point we have promoted mask operand
20270 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20271 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20272 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20273 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20275 // The pass-thru value
20276 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20277 Src0 = ExtendToType(Src0, NewVT, DAG);
20279 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20280 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20281 N->getMemoryVT(), dl, Ops,
20282 N->getMemOperand());
20283 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20284 NewGather.getValue(0),
20285 DAG.getIntPtrConstant(0, dl));
20286 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20287 return DAG.getMergeValues(RetOps, dl);
20292 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20293 SelectionDAG &DAG) const {
20294 // TODO: Eventually, the lowering of these nodes should be informed by or
20295 // deferred to the GC strategy for the function in which they appear. For
20296 // now, however, they must be lowered to something. Since they are logically
20297 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20298 // require special handling for these nodes), lower them as literal NOOPs for
20300 SmallVector<SDValue, 2> Ops;
20302 Ops.push_back(Op.getOperand(0));
20303 if (Op->getGluedNode())
20304 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20307 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20308 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20313 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20314 SelectionDAG &DAG) const {
20315 // TODO: Eventually, the lowering of these nodes should be informed by or
20316 // deferred to the GC strategy for the function in which they appear. For
20317 // now, however, they must be lowered to something. Since they are logically
20318 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20319 // require special handling for these nodes), lower them as literal NOOPs for
20321 SmallVector<SDValue, 2> Ops;
20323 Ops.push_back(Op.getOperand(0));
20324 if (Op->getGluedNode())
20325 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20328 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20329 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20334 /// LowerOperation - Provide custom lowering hooks for some operations.
20336 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20337 switch (Op.getOpcode()) {
20338 default: llvm_unreachable("Should not custom lower this!");
20339 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20340 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20341 return LowerCMP_SWAP(Op, Subtarget, DAG);
20342 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
20343 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
20344 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
20345 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
20346 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20347 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
20348 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
20349 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20350 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
20351 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20352 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20353 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
20354 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
20355 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
20356 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
20357 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
20358 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
20359 case ISD::SHL_PARTS:
20360 case ISD::SRA_PARTS:
20361 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
20362 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
20363 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
20364 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
20365 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
20366 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20367 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
20368 case ISD::SIGN_EXTEND_VECTOR_INREG:
20369 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20370 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
20371 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
20372 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
20373 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
20375 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
20376 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
20377 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
20378 case ISD::SETCC: return LowerSETCC(Op, DAG);
20379 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
20380 case ISD::SELECT: return LowerSELECT(Op, DAG);
20381 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
20382 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
20383 case ISD::VASTART: return LowerVASTART(Op, DAG);
20384 case ISD::VAARG: return LowerVAARG(Op, DAG);
20385 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
20386 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20387 case ISD::INTRINSIC_VOID:
20388 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20389 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
20390 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
20391 case ISD::FRAME_TO_ARGS_OFFSET:
20392 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20393 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20394 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
20395 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
20396 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
20397 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
20398 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
20399 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
20400 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
20401 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20403 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
20404 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20405 case ISD::UMUL_LOHI:
20406 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20407 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20410 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20416 case ISD::UMULO: return LowerXALUO(Op, DAG);
20417 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20418 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20422 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20423 case ISD::ADD: return LowerADD(Op, DAG);
20424 case ISD::SUB: return LowerSUB(Op, DAG);
20428 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20429 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20430 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20431 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20432 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20433 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20434 case ISD::GC_TRANSITION_START:
20435 return LowerGC_TRANSITION_START(Op, DAG);
20436 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20440 /// ReplaceNodeResults - Replace a node with an illegal result type
20441 /// with a new node built out of custom code.
20442 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20443 SmallVectorImpl<SDValue>&Results,
20444 SelectionDAG &DAG) const {
20446 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20447 switch (N->getOpcode()) {
20449 llvm_unreachable("Do not know how to custom type legalize this operation!");
20450 case X86ISD::AVG: {
20451 // Legalize types for X86ISD::AVG by expanding vectors.
20452 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20454 auto InVT = N->getValueType(0);
20455 auto InVTSize = InVT.getSizeInBits();
20456 const unsigned RegSize =
20457 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20458 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20459 "512-bit vector requires AVX512");
20460 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20461 "256-bit vector requires AVX2");
20463 auto ElemVT = InVT.getVectorElementType();
20464 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20465 RegSize / ElemVT.getSizeInBits());
20466 assert(RegSize % InVT.getSizeInBits() == 0);
20467 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20469 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20470 Ops[0] = N->getOperand(0);
20471 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20472 Ops[0] = N->getOperand(1);
20473 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20475 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20476 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20477 DAG.getIntPtrConstant(0, dl)));
20480 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20481 case X86ISD::FMINC:
20483 case X86ISD::FMAXC:
20484 case X86ISD::FMAX: {
20485 EVT VT = N->getValueType(0);
20486 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20487 SDValue UNDEF = DAG.getUNDEF(VT);
20488 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20489 N->getOperand(0), UNDEF);
20490 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20491 N->getOperand(1), UNDEF);
20492 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20495 case ISD::SIGN_EXTEND_INREG:
20500 // We don't want to expand or promote these.
20507 case ISD::UDIVREM: {
20508 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20509 Results.push_back(V);
20512 case ISD::FP_TO_SINT:
20513 case ISD::FP_TO_UINT: {
20514 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20516 std::pair<SDValue,SDValue> Vals =
20517 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20518 SDValue FIST = Vals.first, StackSlot = Vals.second;
20519 if (FIST.getNode()) {
20520 EVT VT = N->getValueType(0);
20521 // Return a load from the stack slot.
20522 if (StackSlot.getNode())
20523 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20524 MachinePointerInfo(),
20525 false, false, false, 0));
20527 Results.push_back(FIST);
20531 case ISD::UINT_TO_FP: {
20532 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20533 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20534 N->getValueType(0) != MVT::v2f32)
20536 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20538 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20540 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20541 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20542 DAG.getBitcast(MVT::v2i64, VBias));
20543 Or = DAG.getBitcast(MVT::v2f64, Or);
20544 // TODO: Are there any fast-math-flags to propagate here?
20545 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20546 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20549 case ISD::FP_ROUND: {
20550 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20552 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20553 Results.push_back(V);
20556 case ISD::FP_EXTEND: {
20557 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20558 // No other ValueType for FP_EXTEND should reach this point.
20559 assert(N->getValueType(0) == MVT::v2f32 &&
20560 "Do not know how to legalize this Node");
20563 case ISD::INTRINSIC_W_CHAIN: {
20564 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20566 default : llvm_unreachable("Do not know how to custom type "
20567 "legalize this intrinsic operation!");
20568 case Intrinsic::x86_rdtsc:
20569 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20571 case Intrinsic::x86_rdtscp:
20572 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20574 case Intrinsic::x86_rdpmc:
20575 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20578 case ISD::INTRINSIC_WO_CHAIN: {
20579 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20580 Results.push_back(V);
20583 case ISD::READCYCLECOUNTER: {
20584 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20587 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20588 EVT T = N->getValueType(0);
20589 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20590 bool Regs64bit = T == MVT::i128;
20591 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20592 SDValue cpInL, cpInH;
20593 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20594 DAG.getConstant(0, dl, HalfT));
20595 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20596 DAG.getConstant(1, dl, HalfT));
20597 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20598 Regs64bit ? X86::RAX : X86::EAX,
20600 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20601 Regs64bit ? X86::RDX : X86::EDX,
20602 cpInH, cpInL.getValue(1));
20603 SDValue swapInL, swapInH;
20604 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20605 DAG.getConstant(0, dl, HalfT));
20606 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20607 DAG.getConstant(1, dl, HalfT));
20608 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20609 Regs64bit ? X86::RBX : X86::EBX,
20610 swapInL, cpInH.getValue(1));
20611 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20612 Regs64bit ? X86::RCX : X86::ECX,
20613 swapInH, swapInL.getValue(1));
20614 SDValue Ops[] = { swapInH.getValue(0),
20616 swapInH.getValue(1) };
20617 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20618 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20619 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20620 X86ISD::LCMPXCHG8_DAG;
20621 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20622 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20623 Regs64bit ? X86::RAX : X86::EAX,
20624 HalfT, Result.getValue(1));
20625 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20626 Regs64bit ? X86::RDX : X86::EDX,
20627 HalfT, cpOutL.getValue(2));
20628 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20630 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20631 MVT::i32, cpOutH.getValue(2));
20633 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20634 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20635 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20637 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20638 Results.push_back(Success);
20639 Results.push_back(EFLAGS.getValue(1));
20642 case ISD::ATOMIC_SWAP:
20643 case ISD::ATOMIC_LOAD_ADD:
20644 case ISD::ATOMIC_LOAD_SUB:
20645 case ISD::ATOMIC_LOAD_AND:
20646 case ISD::ATOMIC_LOAD_OR:
20647 case ISD::ATOMIC_LOAD_XOR:
20648 case ISD::ATOMIC_LOAD_NAND:
20649 case ISD::ATOMIC_LOAD_MIN:
20650 case ISD::ATOMIC_LOAD_MAX:
20651 case ISD::ATOMIC_LOAD_UMIN:
20652 case ISD::ATOMIC_LOAD_UMAX:
20653 case ISD::ATOMIC_LOAD: {
20654 // Delegate to generic TypeLegalization. Situations we can really handle
20655 // should have already been dealt with by AtomicExpandPass.cpp.
20658 case ISD::BITCAST: {
20659 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20660 EVT DstVT = N->getValueType(0);
20661 EVT SrcVT = N->getOperand(0)->getValueType(0);
20663 if (SrcVT != MVT::f64 ||
20664 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20667 unsigned NumElts = DstVT.getVectorNumElements();
20668 EVT SVT = DstVT.getVectorElementType();
20669 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20670 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20671 MVT::v2f64, N->getOperand(0));
20672 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20674 if (ExperimentalVectorWideningLegalization) {
20675 // If we are legalizing vectors by widening, we already have the desired
20676 // legal vector type, just return it.
20677 Results.push_back(ToVecInt);
20681 SmallVector<SDValue, 8> Elts;
20682 for (unsigned i = 0, e = NumElts; i != e; ++i)
20683 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20684 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20686 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20691 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20692 switch ((X86ISD::NodeType)Opcode) {
20693 case X86ISD::FIRST_NUMBER: break;
20694 case X86ISD::BSF: return "X86ISD::BSF";
20695 case X86ISD::BSR: return "X86ISD::BSR";
20696 case X86ISD::SHLD: return "X86ISD::SHLD";
20697 case X86ISD::SHRD: return "X86ISD::SHRD";
20698 case X86ISD::FAND: return "X86ISD::FAND";
20699 case X86ISD::FANDN: return "X86ISD::FANDN";
20700 case X86ISD::FOR: return "X86ISD::FOR";
20701 case X86ISD::FXOR: return "X86ISD::FXOR";
20702 case X86ISD::FILD: return "X86ISD::FILD";
20703 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20704 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20705 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20706 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20707 case X86ISD::FLD: return "X86ISD::FLD";
20708 case X86ISD::FST: return "X86ISD::FST";
20709 case X86ISD::CALL: return "X86ISD::CALL";
20710 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20711 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20712 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20713 case X86ISD::BT: return "X86ISD::BT";
20714 case X86ISD::CMP: return "X86ISD::CMP";
20715 case X86ISD::COMI: return "X86ISD::COMI";
20716 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20717 case X86ISD::CMPM: return "X86ISD::CMPM";
20718 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20719 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20720 case X86ISD::SETCC: return "X86ISD::SETCC";
20721 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20722 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20723 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20724 case X86ISD::CMOV: return "X86ISD::CMOV";
20725 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20726 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20727 case X86ISD::IRET: return "X86ISD::IRET";
20728 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20729 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20730 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20731 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20732 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20733 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20734 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20735 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20736 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20737 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20738 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20739 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20740 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20741 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20742 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20743 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20744 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20745 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20746 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20747 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20748 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20749 case X86ISD::HADD: return "X86ISD::HADD";
20750 case X86ISD::HSUB: return "X86ISD::HSUB";
20751 case X86ISD::FHADD: return "X86ISD::FHADD";
20752 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20753 case X86ISD::ABS: return "X86ISD::ABS";
20754 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20755 case X86ISD::FMAX: return "X86ISD::FMAX";
20756 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20757 case X86ISD::FMIN: return "X86ISD::FMIN";
20758 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20759 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20760 case X86ISD::FMINC: return "X86ISD::FMINC";
20761 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20762 case X86ISD::FRCP: return "X86ISD::FRCP";
20763 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20764 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20765 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20766 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20767 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20768 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20769 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20770 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20771 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20772 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20773 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20774 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20775 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20776 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20777 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20778 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20779 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20780 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20781 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20782 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20783 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20784 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20785 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20786 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20787 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20788 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20789 case X86ISD::CVT2MASK: return "X86ISD::CVT2MASK";
20790 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20791 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20792 case X86ISD::VSHL: return "X86ISD::VSHL";
20793 case X86ISD::VSRL: return "X86ISD::VSRL";
20794 case X86ISD::VSRA: return "X86ISD::VSRA";
20795 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20796 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20797 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20798 case X86ISD::CMPP: return "X86ISD::CMPP";
20799 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20800 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20801 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20802 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20803 case X86ISD::ADD: return "X86ISD::ADD";
20804 case X86ISD::SUB: return "X86ISD::SUB";
20805 case X86ISD::ADC: return "X86ISD::ADC";
20806 case X86ISD::SBB: return "X86ISD::SBB";
20807 case X86ISD::SMUL: return "X86ISD::SMUL";
20808 case X86ISD::UMUL: return "X86ISD::UMUL";
20809 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20810 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20811 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20812 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20813 case X86ISD::INC: return "X86ISD::INC";
20814 case X86ISD::DEC: return "X86ISD::DEC";
20815 case X86ISD::OR: return "X86ISD::OR";
20816 case X86ISD::XOR: return "X86ISD::XOR";
20817 case X86ISD::AND: return "X86ISD::AND";
20818 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20819 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20820 case X86ISD::PTEST: return "X86ISD::PTEST";
20821 case X86ISD::TESTP: return "X86ISD::TESTP";
20822 case X86ISD::TESTM: return "X86ISD::TESTM";
20823 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20824 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20825 case X86ISD::KTEST: return "X86ISD::KTEST";
20826 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20827 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20828 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20829 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20830 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20831 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20832 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20833 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20834 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20835 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20836 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20837 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20838 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20839 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20840 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20841 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20842 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20843 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20844 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20845 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20846 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20847 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20848 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20849 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20850 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20851 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20852 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20853 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20854 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20855 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20856 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20857 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20858 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20859 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20860 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20861 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20862 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20863 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20864 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20865 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20866 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20867 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20868 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20869 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20870 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20871 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20872 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20873 case X86ISD::SAHF: return "X86ISD::SAHF";
20874 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20875 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20876 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20877 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20878 case X86ISD::VPROT: return "X86ISD::VPROT";
20879 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20880 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20881 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20882 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20883 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20884 case X86ISD::FMADD: return "X86ISD::FMADD";
20885 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20886 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20887 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20888 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20889 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20890 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20891 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20892 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20893 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20894 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20895 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20896 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20897 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20898 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20899 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20900 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20901 case X86ISD::XTEST: return "X86ISD::XTEST";
20902 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20903 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20904 case X86ISD::SELECT: return "X86ISD::SELECT";
20905 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20906 case X86ISD::RCP28: return "X86ISD::RCP28";
20907 case X86ISD::EXP2: return "X86ISD::EXP2";
20908 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20909 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20910 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20911 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20912 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20913 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20914 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20915 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20916 case X86ISD::ADDS: return "X86ISD::ADDS";
20917 case X86ISD::SUBS: return "X86ISD::SUBS";
20918 case X86ISD::AVG: return "X86ISD::AVG";
20919 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20920 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20921 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20922 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20923 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20924 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20925 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20930 // isLegalAddressingMode - Return true if the addressing mode represented
20931 // by AM is legal for this target, for a load/store of the specified type.
20932 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20933 const AddrMode &AM, Type *Ty,
20934 unsigned AS) const {
20935 // X86 supports extremely general addressing modes.
20936 CodeModel::Model M = getTargetMachine().getCodeModel();
20937 Reloc::Model R = getTargetMachine().getRelocationModel();
20939 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20940 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20945 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20947 // If a reference to this global requires an extra load, we can't fold it.
20948 if (isGlobalStubReference(GVFlags))
20951 // If BaseGV requires a register for the PIC base, we cannot also have a
20952 // BaseReg specified.
20953 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20956 // If lower 4G is not available, then we must use rip-relative addressing.
20957 if ((M != CodeModel::Small || R != Reloc::Static) &&
20958 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20962 switch (AM.Scale) {
20968 // These scales always work.
20973 // These scales are formed with basereg+scalereg. Only accept if there is
20978 default: // Other stuff never works.
20985 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20986 unsigned Bits = Ty->getScalarSizeInBits();
20988 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20989 // particularly cheaper than those without.
20993 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20994 // variable shifts just as cheap as scalar ones.
20995 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20998 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20999 // fully general vector.
21003 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
21004 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21006 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
21007 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
21008 return NumBits1 > NumBits2;
21011 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
21012 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
21015 if (!isTypeLegal(EVT::getEVT(Ty1)))
21018 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
21020 // Assuming the caller doesn't have a zeroext or signext return parameter,
21021 // truncation all the way down to i1 is valid.
21025 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
21026 return isInt<32>(Imm);
21029 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
21030 // Can also use sub to handle negated immediates.
21031 return isInt<32>(Imm);
21034 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
21035 if (!VT1.isInteger() || !VT2.isInteger())
21037 unsigned NumBits1 = VT1.getSizeInBits();
21038 unsigned NumBits2 = VT2.getSizeInBits();
21039 return NumBits1 > NumBits2;
21042 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
21043 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21044 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
21047 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
21048 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
21049 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
21052 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
21053 EVT VT1 = Val.getValueType();
21054 if (isZExtFree(VT1, VT2))
21057 if (Val.getOpcode() != ISD::LOAD)
21060 if (!VT1.isSimple() || !VT1.isInteger() ||
21061 !VT2.isSimple() || !VT2.isInteger())
21064 switch (VT1.getSimpleVT().SimpleTy) {
21069 // X86 has 8, 16, and 32-bit zero-extending loads.
21076 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
21079 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
21080 if (!Subtarget->hasAnyFMA())
21083 VT = VT.getScalarType();
21085 if (!VT.isSimple())
21088 switch (VT.getSimpleVT().SimpleTy) {
21099 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21100 // i16 instructions are longer (0x66 prefix) and potentially slower.
21101 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21104 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21105 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21106 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21107 /// are assumed to be legal.
21109 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21111 if (!VT.isSimple())
21114 // Not for i1 vectors
21115 if (VT.getSimpleVT().getScalarType() == MVT::i1)
21118 // Very little shuffling can be done for 64-bit vectors right now.
21119 if (VT.getSimpleVT().getSizeInBits() == 64)
21122 // We only care that the types being shuffled are legal. The lowering can
21123 // handle any possible shuffle mask that results.
21124 return isTypeLegal(VT.getSimpleVT());
21128 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21130 // Just delegate to the generic legality, clear masks aren't special.
21131 return isShuffleMaskLegal(Mask, VT);
21134 //===----------------------------------------------------------------------===//
21135 // X86 Scheduler Hooks
21136 //===----------------------------------------------------------------------===//
21138 /// Utility function to emit xbegin specifying the start of an RTM region.
21139 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21140 const TargetInstrInfo *TII) {
21141 DebugLoc DL = MI->getDebugLoc();
21143 const BasicBlock *BB = MBB->getBasicBlock();
21144 MachineFunction::iterator I = ++MBB->getIterator();
21146 // For the v = xbegin(), we generate
21157 MachineBasicBlock *thisMBB = MBB;
21158 MachineFunction *MF = MBB->getParent();
21159 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21160 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21161 MF->insert(I, mainMBB);
21162 MF->insert(I, sinkMBB);
21164 // Transfer the remainder of BB and its successor edges to sinkMBB.
21165 sinkMBB->splice(sinkMBB->begin(), MBB,
21166 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21167 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21171 // # fallthrough to mainMBB
21172 // # abortion to sinkMBB
21173 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21174 thisMBB->addSuccessor(mainMBB);
21175 thisMBB->addSuccessor(sinkMBB);
21179 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21180 mainMBB->addSuccessor(sinkMBB);
21183 // EAX is live into the sinkMBB
21184 sinkMBB->addLiveIn(X86::EAX);
21185 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21186 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21189 MI->eraseFromParent();
21193 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21194 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21195 // in the .td file.
21196 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21197 const TargetInstrInfo *TII) {
21199 switch (MI->getOpcode()) {
21200 default: llvm_unreachable("illegal opcode!");
21201 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
21202 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21203 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
21204 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21205 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
21206 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21207 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
21208 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21211 DebugLoc dl = MI->getDebugLoc();
21212 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21214 unsigned NumArgs = MI->getNumOperands();
21215 for (unsigned i = 1; i < NumArgs; ++i) {
21216 MachineOperand &Op = MI->getOperand(i);
21217 if (!(Op.isReg() && Op.isImplicit()))
21218 MIB.addOperand(Op);
21220 if (MI->hasOneMemOperand())
21221 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21223 BuildMI(*BB, MI, dl,
21224 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21225 .addReg(X86::XMM0);
21227 MI->eraseFromParent();
21231 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21232 // defs in an instruction pattern
21233 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21234 const TargetInstrInfo *TII) {
21236 switch (MI->getOpcode()) {
21237 default: llvm_unreachable("illegal opcode!");
21238 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
21239 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21240 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
21241 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21242 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
21243 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21244 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
21245 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21248 DebugLoc dl = MI->getDebugLoc();
21249 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21251 unsigned NumArgs = MI->getNumOperands(); // remove the results
21252 for (unsigned i = 1; i < NumArgs; ++i) {
21253 MachineOperand &Op = MI->getOperand(i);
21254 if (!(Op.isReg() && Op.isImplicit()))
21255 MIB.addOperand(Op);
21257 if (MI->hasOneMemOperand())
21258 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21260 BuildMI(*BB, MI, dl,
21261 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21264 MI->eraseFromParent();
21268 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21269 const X86Subtarget *Subtarget) {
21270 DebugLoc dl = MI->getDebugLoc();
21271 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21273 // insert input VAL into EAX
21274 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21275 .addReg(MI->getOperand(0).getReg());
21276 // insert zero to ECX
21277 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21280 // insert zero to EDX
21281 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21284 // insert WRPKRU instruction
21285 BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21287 MI->eraseFromParent(); // The pseudo is gone now.
21291 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21292 const X86Subtarget *Subtarget) {
21293 DebugLoc dl = MI->getDebugLoc();
21294 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21296 // insert zero to ECX
21297 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21300 // insert RDPKRU instruction
21301 BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21302 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21305 MI->eraseFromParent(); // The pseudo is gone now.
21309 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21310 const X86Subtarget *Subtarget) {
21311 DebugLoc dl = MI->getDebugLoc();
21312 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21313 // Address into RAX/EAX, other two args into ECX, EDX.
21314 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21315 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21316 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21317 for (int i = 0; i < X86::AddrNumOperands; ++i)
21318 MIB.addOperand(MI->getOperand(i));
21320 unsigned ValOps = X86::AddrNumOperands;
21321 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21322 .addReg(MI->getOperand(ValOps).getReg());
21323 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21324 .addReg(MI->getOperand(ValOps+1).getReg());
21326 // The instruction doesn't actually take any operands though.
21327 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21329 MI->eraseFromParent(); // The pseudo is gone now.
21333 MachineBasicBlock *
21334 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21335 MachineBasicBlock *MBB) const {
21336 // Emit va_arg instruction on X86-64.
21338 // Operands to this pseudo-instruction:
21339 // 0 ) Output : destination address (reg)
21340 // 1-5) Input : va_list address (addr, i64mem)
21341 // 6 ) ArgSize : Size (in bytes) of vararg type
21342 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21343 // 8 ) Align : Alignment of type
21344 // 9 ) EFLAGS (implicit-def)
21346 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21347 static_assert(X86::AddrNumOperands == 5,
21348 "VAARG_64 assumes 5 address operands");
21350 unsigned DestReg = MI->getOperand(0).getReg();
21351 MachineOperand &Base = MI->getOperand(1);
21352 MachineOperand &Scale = MI->getOperand(2);
21353 MachineOperand &Index = MI->getOperand(3);
21354 MachineOperand &Disp = MI->getOperand(4);
21355 MachineOperand &Segment = MI->getOperand(5);
21356 unsigned ArgSize = MI->getOperand(6).getImm();
21357 unsigned ArgMode = MI->getOperand(7).getImm();
21358 unsigned Align = MI->getOperand(8).getImm();
21360 // Memory Reference
21361 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21362 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21363 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21365 // Machine Information
21366 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21367 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21368 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21369 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21370 DebugLoc DL = MI->getDebugLoc();
21372 // struct va_list {
21375 // i64 overflow_area (address)
21376 // i64 reg_save_area (address)
21378 // sizeof(va_list) = 24
21379 // alignment(va_list) = 8
21381 unsigned TotalNumIntRegs = 6;
21382 unsigned TotalNumXMMRegs = 8;
21383 bool UseGPOffset = (ArgMode == 1);
21384 bool UseFPOffset = (ArgMode == 2);
21385 unsigned MaxOffset = TotalNumIntRegs * 8 +
21386 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21388 /* Align ArgSize to a multiple of 8 */
21389 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21390 bool NeedsAlign = (Align > 8);
21392 MachineBasicBlock *thisMBB = MBB;
21393 MachineBasicBlock *overflowMBB;
21394 MachineBasicBlock *offsetMBB;
21395 MachineBasicBlock *endMBB;
21397 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
21398 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
21399 unsigned OffsetReg = 0;
21401 if (!UseGPOffset && !UseFPOffset) {
21402 // If we only pull from the overflow region, we don't create a branch.
21403 // We don't need to alter control flow.
21404 OffsetDestReg = 0; // unused
21405 OverflowDestReg = DestReg;
21407 offsetMBB = nullptr;
21408 overflowMBB = thisMBB;
21411 // First emit code to check if gp_offset (or fp_offset) is below the bound.
21412 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21413 // If not, pull from overflow_area. (branch to overflowMBB)
21418 // offsetMBB overflowMBB
21423 // Registers for the PHI in endMBB
21424 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21425 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21427 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21428 MachineFunction *MF = MBB->getParent();
21429 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21430 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21431 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21433 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21435 // Insert the new basic blocks
21436 MF->insert(MBBIter, offsetMBB);
21437 MF->insert(MBBIter, overflowMBB);
21438 MF->insert(MBBIter, endMBB);
21440 // Transfer the remainder of MBB and its successor edges to endMBB.
21441 endMBB->splice(endMBB->begin(), thisMBB,
21442 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21443 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21445 // Make offsetMBB and overflowMBB successors of thisMBB
21446 thisMBB->addSuccessor(offsetMBB);
21447 thisMBB->addSuccessor(overflowMBB);
21449 // endMBB is a successor of both offsetMBB and overflowMBB
21450 offsetMBB->addSuccessor(endMBB);
21451 overflowMBB->addSuccessor(endMBB);
21453 // Load the offset value into a register
21454 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21455 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21459 .addDisp(Disp, UseFPOffset ? 4 : 0)
21460 .addOperand(Segment)
21461 .setMemRefs(MMOBegin, MMOEnd);
21463 // Check if there is enough room left to pull this argument.
21464 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21466 .addImm(MaxOffset + 8 - ArgSizeA8);
21468 // Branch to "overflowMBB" if offset >= max
21469 // Fall through to "offsetMBB" otherwise
21470 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21471 .addMBB(overflowMBB);
21474 // In offsetMBB, emit code to use the reg_save_area.
21476 assert(OffsetReg != 0);
21478 // Read the reg_save_area address.
21479 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21480 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21485 .addOperand(Segment)
21486 .setMemRefs(MMOBegin, MMOEnd);
21488 // Zero-extend the offset
21489 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21490 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21493 .addImm(X86::sub_32bit);
21495 // Add the offset to the reg_save_area to get the final address.
21496 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21497 .addReg(OffsetReg64)
21498 .addReg(RegSaveReg);
21500 // Compute the offset for the next argument
21501 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21502 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21504 .addImm(UseFPOffset ? 16 : 8);
21506 // Store it back into the va_list.
21507 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21511 .addDisp(Disp, UseFPOffset ? 4 : 0)
21512 .addOperand(Segment)
21513 .addReg(NextOffsetReg)
21514 .setMemRefs(MMOBegin, MMOEnd);
21517 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21522 // Emit code to use overflow area
21525 // Load the overflow_area address into a register.
21526 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21527 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21532 .addOperand(Segment)
21533 .setMemRefs(MMOBegin, MMOEnd);
21535 // If we need to align it, do so. Otherwise, just copy the address
21536 // to OverflowDestReg.
21538 // Align the overflow address
21539 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21540 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21542 // aligned_addr = (addr + (align-1)) & ~(align-1)
21543 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21544 .addReg(OverflowAddrReg)
21547 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21549 .addImm(~(uint64_t)(Align-1));
21551 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21552 .addReg(OverflowAddrReg);
21555 // Compute the next overflow address after this argument.
21556 // (the overflow address should be kept 8-byte aligned)
21557 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21558 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21559 .addReg(OverflowDestReg)
21560 .addImm(ArgSizeA8);
21562 // Store the new overflow address.
21563 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21568 .addOperand(Segment)
21569 .addReg(NextAddrReg)
21570 .setMemRefs(MMOBegin, MMOEnd);
21572 // If we branched, emit the PHI to the front of endMBB.
21574 BuildMI(*endMBB, endMBB->begin(), DL,
21575 TII->get(X86::PHI), DestReg)
21576 .addReg(OffsetDestReg).addMBB(offsetMBB)
21577 .addReg(OverflowDestReg).addMBB(overflowMBB);
21580 // Erase the pseudo instruction
21581 MI->eraseFromParent();
21586 MachineBasicBlock *
21587 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21589 MachineBasicBlock *MBB) const {
21590 // Emit code to save XMM registers to the stack. The ABI says that the
21591 // number of registers to save is given in %al, so it's theoretically
21592 // possible to do an indirect jump trick to avoid saving all of them,
21593 // however this code takes a simpler approach and just executes all
21594 // of the stores if %al is non-zero. It's less code, and it's probably
21595 // easier on the hardware branch predictor, and stores aren't all that
21596 // expensive anyway.
21598 // Create the new basic blocks. One block contains all the XMM stores,
21599 // and one block is the final destination regardless of whether any
21600 // stores were performed.
21601 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21602 MachineFunction *F = MBB->getParent();
21603 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21604 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21605 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21606 F->insert(MBBIter, XMMSaveMBB);
21607 F->insert(MBBIter, EndMBB);
21609 // Transfer the remainder of MBB and its successor edges to EndMBB.
21610 EndMBB->splice(EndMBB->begin(), MBB,
21611 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21612 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21614 // The original block will now fall through to the XMM save block.
21615 MBB->addSuccessor(XMMSaveMBB);
21616 // The XMMSaveMBB will fall through to the end block.
21617 XMMSaveMBB->addSuccessor(EndMBB);
21619 // Now add the instructions.
21620 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21621 DebugLoc DL = MI->getDebugLoc();
21623 unsigned CountReg = MI->getOperand(0).getReg();
21624 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21625 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21627 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21628 // If %al is 0, branch around the XMM save block.
21629 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21630 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21631 MBB->addSuccessor(EndMBB);
21634 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21635 // that was just emitted, but clearly shouldn't be "saved".
21636 assert((MI->getNumOperands() <= 3 ||
21637 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21638 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21639 && "Expected last argument to be EFLAGS");
21640 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21641 // In the XMM save block, save all the XMM argument registers.
21642 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21643 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21644 MachineMemOperand *MMO = F->getMachineMemOperand(
21645 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21646 MachineMemOperand::MOStore,
21647 /*Size=*/16, /*Align=*/16);
21648 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21649 .addFrameIndex(RegSaveFrameIndex)
21650 .addImm(/*Scale=*/1)
21651 .addReg(/*IndexReg=*/0)
21652 .addImm(/*Disp=*/Offset)
21653 .addReg(/*Segment=*/0)
21654 .addReg(MI->getOperand(i).getReg())
21655 .addMemOperand(MMO);
21658 MI->eraseFromParent(); // The pseudo instruction is gone now.
21663 // The EFLAGS operand of SelectItr might be missing a kill marker
21664 // because there were multiple uses of EFLAGS, and ISel didn't know
21665 // which to mark. Figure out whether SelectItr should have had a
21666 // kill marker, and set it if it should. Returns the correct kill
21668 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21669 MachineBasicBlock* BB,
21670 const TargetRegisterInfo* TRI) {
21671 // Scan forward through BB for a use/def of EFLAGS.
21672 MachineBasicBlock::iterator miI(std::next(SelectItr));
21673 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21674 const MachineInstr& mi = *miI;
21675 if (mi.readsRegister(X86::EFLAGS))
21677 if (mi.definesRegister(X86::EFLAGS))
21678 break; // Should have kill-flag - update below.
21681 // If we hit the end of the block, check whether EFLAGS is live into a
21683 if (miI == BB->end()) {
21684 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21685 sEnd = BB->succ_end();
21686 sItr != sEnd; ++sItr) {
21687 MachineBasicBlock* succ = *sItr;
21688 if (succ->isLiveIn(X86::EFLAGS))
21693 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21694 // out. SelectMI should have a kill flag on EFLAGS.
21695 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21699 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21700 // together with other CMOV pseudo-opcodes into a single basic-block with
21701 // conditional jump around it.
21702 static bool isCMOVPseudo(MachineInstr *MI) {
21703 switch (MI->getOpcode()) {
21704 case X86::CMOV_FR32:
21705 case X86::CMOV_FR64:
21706 case X86::CMOV_GR8:
21707 case X86::CMOV_GR16:
21708 case X86::CMOV_GR32:
21709 case X86::CMOV_RFP32:
21710 case X86::CMOV_RFP64:
21711 case X86::CMOV_RFP80:
21712 case X86::CMOV_V2F64:
21713 case X86::CMOV_V2I64:
21714 case X86::CMOV_V4F32:
21715 case X86::CMOV_V4F64:
21716 case X86::CMOV_V4I64:
21717 case X86::CMOV_V16F32:
21718 case X86::CMOV_V8F32:
21719 case X86::CMOV_V8F64:
21720 case X86::CMOV_V8I64:
21721 case X86::CMOV_V8I1:
21722 case X86::CMOV_V16I1:
21723 case X86::CMOV_V32I1:
21724 case X86::CMOV_V64I1:
21732 MachineBasicBlock *
21733 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21734 MachineBasicBlock *BB) const {
21735 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21736 DebugLoc DL = MI->getDebugLoc();
21738 // To "insert" a SELECT_CC instruction, we actually have to insert the
21739 // diamond control-flow pattern. The incoming instruction knows the
21740 // destination vreg to set, the condition code register to branch on, the
21741 // true/false values to select between, and a branch opcode to use.
21742 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21743 MachineFunction::iterator It = ++BB->getIterator();
21748 // cmpTY ccX, r1, r2
21750 // fallthrough --> copy0MBB
21751 MachineBasicBlock *thisMBB = BB;
21752 MachineFunction *F = BB->getParent();
21754 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21755 // as described above, by inserting a BB, and then making a PHI at the join
21756 // point to select the true and false operands of the CMOV in the PHI.
21758 // The code also handles two different cases of multiple CMOV opcodes
21762 // In this case, there are multiple CMOVs in a row, all which are based on
21763 // the same condition setting (or the exact opposite condition setting).
21764 // In this case we can lower all the CMOVs using a single inserted BB, and
21765 // then make a number of PHIs at the join point to model the CMOVs. The only
21766 // trickiness here, is that in a case like:
21768 // t2 = CMOV cond1 t1, f1
21769 // t3 = CMOV cond1 t2, f2
21771 // when rewriting this into PHIs, we have to perform some renaming on the
21772 // temps since you cannot have a PHI operand refer to a PHI result earlier
21773 // in the same block. The "simple" but wrong lowering would be:
21775 // t2 = PHI t1(BB1), f1(BB2)
21776 // t3 = PHI t2(BB1), f2(BB2)
21778 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21779 // renaming is to note that on the path through BB1, t2 is really just a
21780 // copy of t1, and do that renaming, properly generating:
21782 // t2 = PHI t1(BB1), f1(BB2)
21783 // t3 = PHI t1(BB1), f2(BB2)
21785 // Case 2, we lower cascaded CMOVs such as
21787 // (CMOV (CMOV F, T, cc1), T, cc2)
21789 // to two successives branches. For that, we look for another CMOV as the
21790 // following instruction.
21792 // Without this, we would add a PHI between the two jumps, which ends up
21793 // creating a few copies all around. For instance, for
21795 // (sitofp (zext (fcmp une)))
21797 // we would generate:
21799 // ucomiss %xmm1, %xmm0
21800 // movss <1.0f>, %xmm0
21801 // movaps %xmm0, %xmm1
21803 // xorps %xmm1, %xmm1
21806 // movaps %xmm1, %xmm0
21810 // because this custom-inserter would have generated:
21822 // A: X = ...; Y = ...
21824 // C: Z = PHI [X, A], [Y, B]
21826 // E: PHI [X, C], [Z, D]
21828 // If we lower both CMOVs in a single step, we can instead generate:
21840 // A: X = ...; Y = ...
21842 // E: PHI [X, A], [X, C], [Y, D]
21844 // Which, in our sitofp/fcmp example, gives us something like:
21846 // ucomiss %xmm1, %xmm0
21847 // movss <1.0f>, %xmm0
21850 // xorps %xmm0, %xmm0
21854 MachineInstr *CascadedCMOV = nullptr;
21855 MachineInstr *LastCMOV = MI;
21856 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21857 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21858 MachineBasicBlock::iterator NextMIIt =
21859 std::next(MachineBasicBlock::iterator(MI));
21861 // Check for case 1, where there are multiple CMOVs with the same condition
21862 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21863 // number of jumps the most.
21865 if (isCMOVPseudo(MI)) {
21866 // See if we have a string of CMOVS with the same condition.
21867 while (NextMIIt != BB->end() &&
21868 isCMOVPseudo(NextMIIt) &&
21869 (NextMIIt->getOperand(3).getImm() == CC ||
21870 NextMIIt->getOperand(3).getImm() == OppCC)) {
21871 LastCMOV = &*NextMIIt;
21876 // This checks for case 2, but only do this if we didn't already find
21877 // case 1, as indicated by LastCMOV == MI.
21878 if (LastCMOV == MI &&
21879 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21880 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21881 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21882 CascadedCMOV = &*NextMIIt;
21885 MachineBasicBlock *jcc1MBB = nullptr;
21887 // If we have a cascaded CMOV, we lower it to two successive branches to
21888 // the same block. EFLAGS is used by both, so mark it as live in the second.
21889 if (CascadedCMOV) {
21890 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21891 F->insert(It, jcc1MBB);
21892 jcc1MBB->addLiveIn(X86::EFLAGS);
21895 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21896 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21897 F->insert(It, copy0MBB);
21898 F->insert(It, sinkMBB);
21900 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21901 // live into the sink and copy blocks.
21902 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21904 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21905 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21906 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21907 copy0MBB->addLiveIn(X86::EFLAGS);
21908 sinkMBB->addLiveIn(X86::EFLAGS);
21911 // Transfer the remainder of BB and its successor edges to sinkMBB.
21912 sinkMBB->splice(sinkMBB->begin(), BB,
21913 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21914 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21916 // Add the true and fallthrough blocks as its successors.
21917 if (CascadedCMOV) {
21918 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21919 BB->addSuccessor(jcc1MBB);
21921 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21922 // jump to the sinkMBB.
21923 jcc1MBB->addSuccessor(copy0MBB);
21924 jcc1MBB->addSuccessor(sinkMBB);
21926 BB->addSuccessor(copy0MBB);
21929 // The true block target of the first (or only) branch is always sinkMBB.
21930 BB->addSuccessor(sinkMBB);
21932 // Create the conditional branch instruction.
21933 unsigned Opc = X86::GetCondBranchFromCond(CC);
21934 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21936 if (CascadedCMOV) {
21937 unsigned Opc2 = X86::GetCondBranchFromCond(
21938 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21939 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21943 // %FalseValue = ...
21944 // # fallthrough to sinkMBB
21945 copy0MBB->addSuccessor(sinkMBB);
21948 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21950 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21951 MachineBasicBlock::iterator MIItEnd =
21952 std::next(MachineBasicBlock::iterator(LastCMOV));
21953 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21954 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21955 MachineInstrBuilder MIB;
21957 // As we are creating the PHIs, we have to be careful if there is more than
21958 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21959 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21960 // That also means that PHI construction must work forward from earlier to
21961 // later, and that the code must maintain a mapping from earlier PHI's
21962 // destination registers, and the registers that went into the PHI.
21964 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21965 unsigned DestReg = MIIt->getOperand(0).getReg();
21966 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21967 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21969 // If this CMOV we are generating is the opposite condition from
21970 // the jump we generated, then we have to swap the operands for the
21971 // PHI that is going to be generated.
21972 if (MIIt->getOperand(3).getImm() == OppCC)
21973 std::swap(Op1Reg, Op2Reg);
21975 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21976 Op1Reg = RegRewriteTable[Op1Reg].first;
21978 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21979 Op2Reg = RegRewriteTable[Op2Reg].second;
21981 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21982 TII->get(X86::PHI), DestReg)
21983 .addReg(Op1Reg).addMBB(copy0MBB)
21984 .addReg(Op2Reg).addMBB(thisMBB);
21986 // Add this PHI to the rewrite table.
21987 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21990 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21991 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21992 if (CascadedCMOV) {
21993 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21994 // Copy the PHI result to the register defined by the second CMOV.
21995 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21996 DL, TII->get(TargetOpcode::COPY),
21997 CascadedCMOV->getOperand(0).getReg())
21998 .addReg(MI->getOperand(0).getReg());
21999 CascadedCMOV->eraseFromParent();
22002 // Now remove the CMOV(s).
22003 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
22004 (MIIt++)->eraseFromParent();
22009 MachineBasicBlock *
22010 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
22011 MachineBasicBlock *BB) const {
22012 // Combine the following atomic floating-point modification pattern:
22013 // a.store(reg OP a.load(acquire), release)
22014 // Transform them into:
22015 // OPss (%gpr), %xmm
22016 // movss %xmm, (%gpr)
22017 // Or sd equivalent for 64-bit operations.
22019 switch (MI->getOpcode()) {
22020 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
22021 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
22022 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
22024 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22025 DebugLoc DL = MI->getDebugLoc();
22026 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
22027 MachineOperand MSrc = MI->getOperand(0);
22028 unsigned VSrc = MI->getOperand(5).getReg();
22029 const MachineOperand &Disp = MI->getOperand(3);
22030 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
22031 bool hasDisp = Disp.isGlobal() || Disp.isImm();
22032 if (hasDisp && MSrc.isReg())
22033 MSrc.setIsKill(false);
22034 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
22035 .addOperand(/*Base=*/MSrc)
22036 .addImm(/*Scale=*/1)
22037 .addReg(/*Index=*/0)
22038 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22040 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
22041 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
22043 .addOperand(/*Base=*/MSrc)
22044 .addImm(/*Scale=*/1)
22045 .addReg(/*Index=*/0)
22046 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
22047 .addReg(/*Segment=*/0);
22048 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
22049 MI->eraseFromParent(); // The pseudo instruction is gone now.
22053 MachineBasicBlock *
22054 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
22055 MachineBasicBlock *BB) const {
22056 MachineFunction *MF = BB->getParent();
22057 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22058 DebugLoc DL = MI->getDebugLoc();
22059 const BasicBlock *LLVM_BB = BB->getBasicBlock();
22061 assert(MF->shouldSplitStack());
22063 const bool Is64Bit = Subtarget->is64Bit();
22064 const bool IsLP64 = Subtarget->isTarget64BitLP64();
22066 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
22067 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
22070 // ... [Till the alloca]
22071 // If stacklet is not large enough, jump to mallocMBB
22074 // Allocate by subtracting from RSP
22075 // Jump to continueMBB
22078 // Allocate by call to runtime
22082 // [rest of original BB]
22085 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22086 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22087 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22089 MachineRegisterInfo &MRI = MF->getRegInfo();
22090 const TargetRegisterClass *AddrRegClass =
22091 getRegClassFor(getPointerTy(MF->getDataLayout()));
22093 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22094 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22095 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22096 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22097 sizeVReg = MI->getOperand(1).getReg(),
22098 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22100 MachineFunction::iterator MBBIter = ++BB->getIterator();
22102 MF->insert(MBBIter, bumpMBB);
22103 MF->insert(MBBIter, mallocMBB);
22104 MF->insert(MBBIter, continueMBB);
22106 continueMBB->splice(continueMBB->begin(), BB,
22107 std::next(MachineBasicBlock::iterator(MI)), BB->end());
22108 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22110 // Add code to the main basic block to check if the stack limit has been hit,
22111 // and if so, jump to mallocMBB otherwise to bumpMBB.
22112 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22113 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22114 .addReg(tmpSPVReg).addReg(sizeVReg);
22115 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22116 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22117 .addReg(SPLimitVReg);
22118 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22120 // bumpMBB simply decreases the stack pointer, since we know the current
22121 // stacklet has enough space.
22122 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22123 .addReg(SPLimitVReg);
22124 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22125 .addReg(SPLimitVReg);
22126 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22128 // Calls into a routine in libgcc to allocate more space from the heap.
22129 const uint32_t *RegMask =
22130 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22132 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22134 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22135 .addExternalSymbol("__morestack_allocate_stack_space")
22136 .addRegMask(RegMask)
22137 .addReg(X86::RDI, RegState::Implicit)
22138 .addReg(X86::RAX, RegState::ImplicitDefine);
22139 } else if (Is64Bit) {
22140 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22142 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22143 .addExternalSymbol("__morestack_allocate_stack_space")
22144 .addRegMask(RegMask)
22145 .addReg(X86::EDI, RegState::Implicit)
22146 .addReg(X86::EAX, RegState::ImplicitDefine);
22148 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22150 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22151 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22152 .addExternalSymbol("__morestack_allocate_stack_space")
22153 .addRegMask(RegMask)
22154 .addReg(X86::EAX, RegState::ImplicitDefine);
22158 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22161 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22162 .addReg(IsLP64 ? X86::RAX : X86::EAX);
22163 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22165 // Set up the CFG correctly.
22166 BB->addSuccessor(bumpMBB);
22167 BB->addSuccessor(mallocMBB);
22168 mallocMBB->addSuccessor(continueMBB);
22169 bumpMBB->addSuccessor(continueMBB);
22171 // Take care of the PHI nodes.
22172 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22173 MI->getOperand(0).getReg())
22174 .addReg(mallocPtrVReg).addMBB(mallocMBB)
22175 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22177 // Delete the original pseudo instruction.
22178 MI->eraseFromParent();
22181 return continueMBB;
22184 MachineBasicBlock *
22185 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22186 MachineBasicBlock *BB) const {
22187 assert(!Subtarget->isTargetMachO());
22188 DebugLoc DL = MI->getDebugLoc();
22189 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22190 *BB->getParent(), *BB, MI, DL, false);
22191 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22192 MI->eraseFromParent(); // The pseudo instruction is gone now.
22196 MachineBasicBlock *
22197 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22198 MachineBasicBlock *BB) const {
22199 MachineFunction *MF = BB->getParent();
22200 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22201 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22202 DebugLoc DL = MI->getDebugLoc();
22204 assert(!isAsynchronousEHPersonality(
22205 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22206 "SEH does not use catchret!");
22208 // Only 32-bit EH needs to worry about manually restoring stack pointers.
22209 if (!Subtarget->is32Bit())
22212 // C++ EH creates a new target block to hold the restore code, and wires up
22213 // the new block to the return destination with a normal JMP_4.
22214 MachineBasicBlock *RestoreMBB =
22215 MF->CreateMachineBasicBlock(BB->getBasicBlock());
22216 assert(BB->succ_size() == 1);
22217 MF->insert(std::next(BB->getIterator()), RestoreMBB);
22218 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22219 BB->addSuccessor(RestoreMBB);
22220 MI->getOperand(0).setMBB(RestoreMBB);
22222 auto RestoreMBBI = RestoreMBB->begin();
22223 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22224 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22228 MachineBasicBlock *
22229 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22230 MachineBasicBlock *BB) const {
22231 MachineFunction *MF = BB->getParent();
22232 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22233 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22234 // Only 32-bit SEH requires special handling for catchpad.
22235 if (IsSEH && Subtarget->is32Bit()) {
22236 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22237 DebugLoc DL = MI->getDebugLoc();
22238 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22240 MI->eraseFromParent();
22244 MachineBasicBlock *
22245 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22246 MachineBasicBlock *BB) const {
22247 // This is pretty easy. We're taking the value that we received from
22248 // our load from the relocation, sticking it in either RDI (x86-64)
22249 // or EAX and doing an indirect call. The return value will then
22250 // be in the normal return register.
22251 MachineFunction *F = BB->getParent();
22252 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22253 DebugLoc DL = MI->getDebugLoc();
22255 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22256 assert(MI->getOperand(3).isGlobal() && "This should be a global");
22258 // Get a register mask for the lowered call.
22259 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22260 // proper register mask.
22261 const uint32_t *RegMask =
22262 Subtarget->is64Bit() ?
22263 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22264 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22265 if (Subtarget->is64Bit()) {
22266 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22267 TII->get(X86::MOV64rm), X86::RDI)
22269 .addImm(0).addReg(0)
22270 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22271 MI->getOperand(3).getTargetFlags())
22273 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22274 addDirectMem(MIB, X86::RDI);
22275 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22276 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22277 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22278 TII->get(X86::MOV32rm), X86::EAX)
22280 .addImm(0).addReg(0)
22281 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22282 MI->getOperand(3).getTargetFlags())
22284 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22285 addDirectMem(MIB, X86::EAX);
22286 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22288 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22289 TII->get(X86::MOV32rm), X86::EAX)
22290 .addReg(TII->getGlobalBaseReg(F))
22291 .addImm(0).addReg(0)
22292 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22293 MI->getOperand(3).getTargetFlags())
22295 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22296 addDirectMem(MIB, X86::EAX);
22297 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22300 MI->eraseFromParent(); // The pseudo instruction is gone now.
22304 MachineBasicBlock *
22305 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22306 MachineBasicBlock *MBB) const {
22307 DebugLoc DL = MI->getDebugLoc();
22308 MachineFunction *MF = MBB->getParent();
22309 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22310 MachineRegisterInfo &MRI = MF->getRegInfo();
22312 const BasicBlock *BB = MBB->getBasicBlock();
22313 MachineFunction::iterator I = ++MBB->getIterator();
22315 // Memory Reference
22316 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22317 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22320 unsigned MemOpndSlot = 0;
22322 unsigned CurOp = 0;
22324 DstReg = MI->getOperand(CurOp++).getReg();
22325 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22326 assert(RC->hasType(MVT::i32) && "Invalid destination!");
22327 unsigned mainDstReg = MRI.createVirtualRegister(RC);
22328 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22330 MemOpndSlot = CurOp;
22332 MVT PVT = getPointerTy(MF->getDataLayout());
22333 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22334 "Invalid Pointer Size!");
22336 // For v = setjmp(buf), we generate
22339 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22340 // SjLjSetup restoreMBB
22346 // v = phi(main, restore)
22349 // if base pointer being used, load it from frame
22352 MachineBasicBlock *thisMBB = MBB;
22353 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22354 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22355 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22356 MF->insert(I, mainMBB);
22357 MF->insert(I, sinkMBB);
22358 MF->push_back(restoreMBB);
22359 restoreMBB->setHasAddressTaken();
22361 MachineInstrBuilder MIB;
22363 // Transfer the remainder of BB and its successor edges to sinkMBB.
22364 sinkMBB->splice(sinkMBB->begin(), MBB,
22365 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22366 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22369 unsigned PtrStoreOpc = 0;
22370 unsigned LabelReg = 0;
22371 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22372 Reloc::Model RM = MF->getTarget().getRelocationModel();
22373 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22374 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22376 // Prepare IP either in reg or imm.
22377 if (!UseImmLabel) {
22378 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22379 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22380 LabelReg = MRI.createVirtualRegister(PtrRC);
22381 if (Subtarget->is64Bit()) {
22382 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22386 .addMBB(restoreMBB)
22389 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22390 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22391 .addReg(XII->getGlobalBaseReg(MF))
22394 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22398 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22400 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22401 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22402 if (i == X86::AddrDisp)
22403 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22405 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22408 MIB.addReg(LabelReg);
22410 MIB.addMBB(restoreMBB);
22411 MIB.setMemRefs(MMOBegin, MMOEnd);
22413 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22414 .addMBB(restoreMBB);
22416 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22417 MIB.addRegMask(RegInfo->getNoPreservedMask());
22418 thisMBB->addSuccessor(mainMBB);
22419 thisMBB->addSuccessor(restoreMBB);
22423 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22424 mainMBB->addSuccessor(sinkMBB);
22427 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22428 TII->get(X86::PHI), DstReg)
22429 .addReg(mainDstReg).addMBB(mainMBB)
22430 .addReg(restoreDstReg).addMBB(restoreMBB);
22433 if (RegInfo->hasBasePointer(*MF)) {
22434 const bool Uses64BitFramePtr =
22435 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22436 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22437 X86FI->setRestoreBasePointer(MF);
22438 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22439 unsigned BasePtr = RegInfo->getBaseRegister();
22440 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22441 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22442 FramePtr, true, X86FI->getRestoreBasePointerOffset())
22443 .setMIFlag(MachineInstr::FrameSetup);
22445 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22446 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22447 restoreMBB->addSuccessor(sinkMBB);
22449 MI->eraseFromParent();
22453 MachineBasicBlock *
22454 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22455 MachineBasicBlock *MBB) const {
22456 DebugLoc DL = MI->getDebugLoc();
22457 MachineFunction *MF = MBB->getParent();
22458 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22459 MachineRegisterInfo &MRI = MF->getRegInfo();
22461 // Memory Reference
22462 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22463 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22465 MVT PVT = getPointerTy(MF->getDataLayout());
22466 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22467 "Invalid Pointer Size!");
22469 const TargetRegisterClass *RC =
22470 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22471 unsigned Tmp = MRI.createVirtualRegister(RC);
22472 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22473 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22474 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22475 unsigned SP = RegInfo->getStackRegister();
22477 MachineInstrBuilder MIB;
22479 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22480 const int64_t SPOffset = 2 * PVT.getStoreSize();
22482 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22483 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22486 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22487 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22488 MIB.addOperand(MI->getOperand(i));
22489 MIB.setMemRefs(MMOBegin, MMOEnd);
22491 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22492 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22493 if (i == X86::AddrDisp)
22494 MIB.addDisp(MI->getOperand(i), LabelOffset);
22496 MIB.addOperand(MI->getOperand(i));
22498 MIB.setMemRefs(MMOBegin, MMOEnd);
22500 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22501 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22502 if (i == X86::AddrDisp)
22503 MIB.addDisp(MI->getOperand(i), SPOffset);
22505 MIB.addOperand(MI->getOperand(i));
22507 MIB.setMemRefs(MMOBegin, MMOEnd);
22509 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22511 MI->eraseFromParent();
22515 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22516 // accumulator loops. Writing back to the accumulator allows the coalescer
22517 // to remove extra copies in the loop.
22518 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22519 MachineBasicBlock *
22520 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22521 MachineBasicBlock *MBB) const {
22522 MachineOperand &AddendOp = MI->getOperand(3);
22524 // Bail out early if the addend isn't a register - we can't switch these.
22525 if (!AddendOp.isReg())
22528 MachineFunction &MF = *MBB->getParent();
22529 MachineRegisterInfo &MRI = MF.getRegInfo();
22531 // Check whether the addend is defined by a PHI:
22532 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22533 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22534 if (!AddendDef.isPHI())
22537 // Look for the following pattern:
22539 // %addend = phi [%entry, 0], [%loop, %result]
22541 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22545 // %addend = phi [%entry, 0], [%loop, %result]
22547 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22549 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22550 assert(AddendDef.getOperand(i).isReg());
22551 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22552 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22553 if (&PHISrcInst == MI) {
22554 // Found a matching instruction.
22555 unsigned NewFMAOpc = 0;
22556 switch (MI->getOpcode()) {
22557 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22558 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22559 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22560 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22561 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22562 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22563 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22564 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22565 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22566 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22567 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22568 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22569 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22570 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22571 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22572 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22573 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22574 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22575 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22576 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22578 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22579 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22580 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22581 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22582 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22583 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22584 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22585 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22586 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22587 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22588 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22589 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22590 default: llvm_unreachable("Unrecognized FMA variant.");
22593 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22594 MachineInstrBuilder MIB =
22595 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22596 .addOperand(MI->getOperand(0))
22597 .addOperand(MI->getOperand(3))
22598 .addOperand(MI->getOperand(2))
22599 .addOperand(MI->getOperand(1));
22600 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22601 MI->eraseFromParent();
22608 MachineBasicBlock *
22609 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22610 MachineBasicBlock *BB) const {
22611 switch (MI->getOpcode()) {
22612 default: llvm_unreachable("Unexpected instr type to insert");
22613 case X86::TAILJMPd64:
22614 case X86::TAILJMPr64:
22615 case X86::TAILJMPm64:
22616 case X86::TAILJMPd64_REX:
22617 case X86::TAILJMPr64_REX:
22618 case X86::TAILJMPm64_REX:
22619 llvm_unreachable("TAILJMP64 would not be touched here.");
22620 case X86::TCRETURNdi64:
22621 case X86::TCRETURNri64:
22622 case X86::TCRETURNmi64:
22624 case X86::WIN_ALLOCA:
22625 return EmitLoweredWinAlloca(MI, BB);
22626 case X86::CATCHRET:
22627 return EmitLoweredCatchRet(MI, BB);
22628 case X86::CATCHPAD:
22629 return EmitLoweredCatchPad(MI, BB);
22630 case X86::SEG_ALLOCA_32:
22631 case X86::SEG_ALLOCA_64:
22632 return EmitLoweredSegAlloca(MI, BB);
22633 case X86::TLSCall_32:
22634 case X86::TLSCall_64:
22635 return EmitLoweredTLSCall(MI, BB);
22636 case X86::CMOV_FR32:
22637 case X86::CMOV_FR64:
22638 case X86::CMOV_FR128:
22639 case X86::CMOV_GR8:
22640 case X86::CMOV_GR16:
22641 case X86::CMOV_GR32:
22642 case X86::CMOV_RFP32:
22643 case X86::CMOV_RFP64:
22644 case X86::CMOV_RFP80:
22645 case X86::CMOV_V2F64:
22646 case X86::CMOV_V2I64:
22647 case X86::CMOV_V4F32:
22648 case X86::CMOV_V4F64:
22649 case X86::CMOV_V4I64:
22650 case X86::CMOV_V16F32:
22651 case X86::CMOV_V8F32:
22652 case X86::CMOV_V8F64:
22653 case X86::CMOV_V8I64:
22654 case X86::CMOV_V8I1:
22655 case X86::CMOV_V16I1:
22656 case X86::CMOV_V32I1:
22657 case X86::CMOV_V64I1:
22658 return EmitLoweredSelect(MI, BB);
22660 case X86::RDFLAGS32:
22661 case X86::RDFLAGS64: {
22662 DebugLoc DL = MI->getDebugLoc();
22663 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22665 MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22667 MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22668 BuildMI(*BB, MI, DL, TII->get(PushF));
22669 BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22671 MI->eraseFromParent(); // The pseudo is gone now.
22675 case X86::WRFLAGS32:
22676 case X86::WRFLAGS64: {
22677 DebugLoc DL = MI->getDebugLoc();
22678 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22680 MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22682 MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22683 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22684 BuildMI(*BB, MI, DL, TII->get(PopF));
22686 MI->eraseFromParent(); // The pseudo is gone now.
22690 case X86::RELEASE_FADD32mr:
22691 case X86::RELEASE_FADD64mr:
22692 return EmitLoweredAtomicFP(MI, BB);
22694 case X86::FP32_TO_INT16_IN_MEM:
22695 case X86::FP32_TO_INT32_IN_MEM:
22696 case X86::FP32_TO_INT64_IN_MEM:
22697 case X86::FP64_TO_INT16_IN_MEM:
22698 case X86::FP64_TO_INT32_IN_MEM:
22699 case X86::FP64_TO_INT64_IN_MEM:
22700 case X86::FP80_TO_INT16_IN_MEM:
22701 case X86::FP80_TO_INT32_IN_MEM:
22702 case X86::FP80_TO_INT64_IN_MEM: {
22703 MachineFunction *F = BB->getParent();
22704 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22705 DebugLoc DL = MI->getDebugLoc();
22707 // Change the floating point control register to use "round towards zero"
22708 // mode when truncating to an integer value.
22709 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22710 addFrameReference(BuildMI(*BB, MI, DL,
22711 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22713 // Load the old value of the high byte of the control word...
22715 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22716 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22719 // Set the high part to be round to zero...
22720 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22723 // Reload the modified control word now...
22724 addFrameReference(BuildMI(*BB, MI, DL,
22725 TII->get(X86::FLDCW16m)), CWFrameIdx);
22727 // Restore the memory image of control word to original value
22728 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22731 // Get the X86 opcode to use.
22733 switch (MI->getOpcode()) {
22734 default: llvm_unreachable("illegal opcode!");
22735 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22736 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22737 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22738 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22739 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22740 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22741 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22742 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22743 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22747 MachineOperand &Op = MI->getOperand(0);
22749 AM.BaseType = X86AddressMode::RegBase;
22750 AM.Base.Reg = Op.getReg();
22752 AM.BaseType = X86AddressMode::FrameIndexBase;
22753 AM.Base.FrameIndex = Op.getIndex();
22755 Op = MI->getOperand(1);
22757 AM.Scale = Op.getImm();
22758 Op = MI->getOperand(2);
22760 AM.IndexReg = Op.getImm();
22761 Op = MI->getOperand(3);
22762 if (Op.isGlobal()) {
22763 AM.GV = Op.getGlobal();
22765 AM.Disp = Op.getImm();
22767 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22768 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22770 // Reload the original control word now.
22771 addFrameReference(BuildMI(*BB, MI, DL,
22772 TII->get(X86::FLDCW16m)), CWFrameIdx);
22774 MI->eraseFromParent(); // The pseudo instruction is gone now.
22777 // String/text processing lowering.
22778 case X86::PCMPISTRM128REG:
22779 case X86::VPCMPISTRM128REG:
22780 case X86::PCMPISTRM128MEM:
22781 case X86::VPCMPISTRM128MEM:
22782 case X86::PCMPESTRM128REG:
22783 case X86::VPCMPESTRM128REG:
22784 case X86::PCMPESTRM128MEM:
22785 case X86::VPCMPESTRM128MEM:
22786 assert(Subtarget->hasSSE42() &&
22787 "Target must have SSE4.2 or AVX features enabled");
22788 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22790 // String/text processing lowering.
22791 case X86::PCMPISTRIREG:
22792 case X86::VPCMPISTRIREG:
22793 case X86::PCMPISTRIMEM:
22794 case X86::VPCMPISTRIMEM:
22795 case X86::PCMPESTRIREG:
22796 case X86::VPCMPESTRIREG:
22797 case X86::PCMPESTRIMEM:
22798 case X86::VPCMPESTRIMEM:
22799 assert(Subtarget->hasSSE42() &&
22800 "Target must have SSE4.2 or AVX features enabled");
22801 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22803 // Thread synchronization.
22805 return EmitMonitor(MI, BB, Subtarget);
22808 return EmitWRPKRU(MI, BB, Subtarget);
22810 return EmitRDPKRU(MI, BB, Subtarget);
22813 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22815 case X86::VASTART_SAVE_XMM_REGS:
22816 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22818 case X86::VAARG_64:
22819 return EmitVAARG64WithCustomInserter(MI, BB);
22821 case X86::EH_SjLj_SetJmp32:
22822 case X86::EH_SjLj_SetJmp64:
22823 return emitEHSjLjSetJmp(MI, BB);
22825 case X86::EH_SjLj_LongJmp32:
22826 case X86::EH_SjLj_LongJmp64:
22827 return emitEHSjLjLongJmp(MI, BB);
22829 case TargetOpcode::STATEPOINT:
22830 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22831 // this point in the process. We diverge later.
22832 return emitPatchPoint(MI, BB);
22834 case TargetOpcode::STACKMAP:
22835 case TargetOpcode::PATCHPOINT:
22836 return emitPatchPoint(MI, BB);
22838 case X86::VFMADDPDr213r:
22839 case X86::VFMADDPSr213r:
22840 case X86::VFMADDSDr213r:
22841 case X86::VFMADDSSr213r:
22842 case X86::VFMSUBPDr213r:
22843 case X86::VFMSUBPSr213r:
22844 case X86::VFMSUBSDr213r:
22845 case X86::VFMSUBSSr213r:
22846 case X86::VFNMADDPDr213r:
22847 case X86::VFNMADDPSr213r:
22848 case X86::VFNMADDSDr213r:
22849 case X86::VFNMADDSSr213r:
22850 case X86::VFNMSUBPDr213r:
22851 case X86::VFNMSUBPSr213r:
22852 case X86::VFNMSUBSDr213r:
22853 case X86::VFNMSUBSSr213r:
22854 case X86::VFMADDSUBPDr213r:
22855 case X86::VFMADDSUBPSr213r:
22856 case X86::VFMSUBADDPDr213r:
22857 case X86::VFMSUBADDPSr213r:
22858 case X86::VFMADDPDr213rY:
22859 case X86::VFMADDPSr213rY:
22860 case X86::VFMSUBPDr213rY:
22861 case X86::VFMSUBPSr213rY:
22862 case X86::VFNMADDPDr213rY:
22863 case X86::VFNMADDPSr213rY:
22864 case X86::VFNMSUBPDr213rY:
22865 case X86::VFNMSUBPSr213rY:
22866 case X86::VFMADDSUBPDr213rY:
22867 case X86::VFMADDSUBPSr213rY:
22868 case X86::VFMSUBADDPDr213rY:
22869 case X86::VFMSUBADDPSr213rY:
22870 return emitFMA3Instr(MI, BB);
22874 //===----------------------------------------------------------------------===//
22875 // X86 Optimization Hooks
22876 //===----------------------------------------------------------------------===//
22878 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22881 const SelectionDAG &DAG,
22882 unsigned Depth) const {
22883 unsigned BitWidth = KnownZero.getBitWidth();
22884 unsigned Opc = Op.getOpcode();
22885 assert((Opc >= ISD::BUILTIN_OP_END ||
22886 Opc == ISD::INTRINSIC_WO_CHAIN ||
22887 Opc == ISD::INTRINSIC_W_CHAIN ||
22888 Opc == ISD::INTRINSIC_VOID) &&
22889 "Should use MaskedValueIsZero if you don't know whether Op"
22890 " is a target node!");
22892 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22906 // These nodes' second result is a boolean.
22907 if (Op.getResNo() == 0)
22910 case X86ISD::SETCC:
22911 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22913 case ISD::INTRINSIC_WO_CHAIN: {
22914 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22915 unsigned NumLoBits = 0;
22918 case Intrinsic::x86_sse_movmsk_ps:
22919 case Intrinsic::x86_avx_movmsk_ps_256:
22920 case Intrinsic::x86_sse2_movmsk_pd:
22921 case Intrinsic::x86_avx_movmsk_pd_256:
22922 case Intrinsic::x86_mmx_pmovmskb:
22923 case Intrinsic::x86_sse2_pmovmskb_128:
22924 case Intrinsic::x86_avx2_pmovmskb: {
22925 // High bits of movmskp{s|d}, pmovmskb are known zero.
22927 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22928 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22929 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22930 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22931 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22932 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22933 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22934 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22936 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22945 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22947 const SelectionDAG &,
22948 unsigned Depth) const {
22949 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22950 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22951 return Op.getValueType().getScalarSizeInBits();
22957 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22958 /// node is a GlobalAddress + offset.
22959 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22960 const GlobalValue* &GA,
22961 int64_t &Offset) const {
22962 if (N->getOpcode() == X86ISD::Wrapper) {
22963 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22964 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22965 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22969 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22972 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22973 /// FIXME: This could be expanded to support 512 bit vectors as well.
22974 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22975 TargetLowering::DAGCombinerInfo &DCI,
22976 const X86Subtarget* Subtarget) {
22978 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22979 SDValue V1 = SVOp->getOperand(0);
22980 SDValue V2 = SVOp->getOperand(1);
22981 MVT VT = SVOp->getSimpleValueType(0);
22982 unsigned NumElems = VT.getVectorNumElements();
22984 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22985 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22989 // V UNDEF BUILD_VECTOR UNDEF
22991 // CONCAT_VECTOR CONCAT_VECTOR
22994 // RESULT: V + zero extended
22996 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22997 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22998 V1.getOperand(1).getOpcode() != ISD::UNDEF)
23001 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
23004 // To match the shuffle mask, the first half of the mask should
23005 // be exactly the first vector, and all the rest a splat with the
23006 // first element of the second one.
23007 for (unsigned i = 0; i != NumElems/2; ++i)
23008 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
23009 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
23012 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
23013 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
23014 if (Ld->hasNUsesOfValue(1, 0)) {
23015 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
23016 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
23018 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
23020 Ld->getPointerInfo(),
23021 Ld->getAlignment(),
23022 false/*isVolatile*/, true/*ReadMem*/,
23023 false/*WriteMem*/);
23025 // Make sure the newly-created LOAD is in the same position as Ld in
23026 // terms of dependency. We create a TokenFactor for Ld and ResNode,
23027 // and update uses of Ld's output chain to use the TokenFactor.
23028 if (Ld->hasAnyUseOfValue(1)) {
23029 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23030 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
23031 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
23032 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
23033 SDValue(ResNode.getNode(), 1));
23036 return DAG.getBitcast(VT, ResNode);
23040 // Emit a zeroed vector and insert the desired subvector on its
23042 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
23043 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
23044 return DCI.CombineTo(N, InsV);
23050 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
23053 /// This is the leaf of the recursive combinine below. When we have found some
23054 /// chain of single-use x86 shuffle instructions and accumulated the combined
23055 /// shuffle mask represented by them, this will try to pattern match that mask
23056 /// into either a single instruction if there is a special purpose instruction
23057 /// for this operation, or into a PSHUFB instruction which is a fully general
23058 /// instruction but should only be used to replace chains over a certain depth.
23059 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
23060 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
23061 TargetLowering::DAGCombinerInfo &DCI,
23062 const X86Subtarget *Subtarget) {
23063 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
23065 // Find the operand that enters the chain. Note that multiple uses are OK
23066 // here, we're not going to remove the operand we find.
23067 SDValue Input = Op.getOperand(0);
23068 while (Input.getOpcode() == ISD::BITCAST)
23069 Input = Input.getOperand(0);
23071 MVT VT = Input.getSimpleValueType();
23072 MVT RootVT = Root.getSimpleValueType();
23075 if (Mask.size() == 1) {
23076 int Index = Mask[0];
23077 assert((Index >= 0 || Index == SM_SentinelUndef ||
23078 Index == SM_SentinelZero) &&
23079 "Invalid shuffle index found!");
23081 // We may end up with an accumulated mask of size 1 as a result of
23082 // widening of shuffle operands (see function canWidenShuffleElements).
23083 // If the only shuffle index is equal to SM_SentinelZero then propagate
23084 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
23085 // mask, and therefore the entire chain of shuffles can be folded away.
23086 if (Index == SM_SentinelZero)
23087 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23089 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23094 // Use the float domain if the operand type is a floating point type.
23095 bool FloatDomain = VT.isFloatingPoint();
23097 // For floating point shuffles, we don't have free copies in the shuffle
23098 // instructions or the ability to load as part of the instruction, so
23099 // canonicalize their shuffles to UNPCK or MOV variants.
23101 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23102 // vectors because it can have a load folded into it that UNPCK cannot. This
23103 // doesn't preclude something switching to the shorter encoding post-RA.
23105 // FIXME: Should teach these routines about AVX vector widths.
23106 if (FloatDomain && VT.is128BitVector()) {
23107 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23108 bool Lo = Mask.equals({0, 0});
23111 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23112 // is no slower than UNPCKLPD but has the option to fold the input operand
23113 // into even an unaligned memory load.
23114 if (Lo && Subtarget->hasSSE3()) {
23115 Shuffle = X86ISD::MOVDDUP;
23116 ShuffleVT = MVT::v2f64;
23118 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23119 // than the UNPCK variants.
23120 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23121 ShuffleVT = MVT::v4f32;
23123 if (Depth == 1 && Root->getOpcode() == Shuffle)
23124 return false; // Nothing to do!
23125 Op = DAG.getBitcast(ShuffleVT, Input);
23126 DCI.AddToWorklist(Op.getNode());
23127 if (Shuffle == X86ISD::MOVDDUP)
23128 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23130 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23131 DCI.AddToWorklist(Op.getNode());
23132 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23136 if (Subtarget->hasSSE3() &&
23137 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23138 bool Lo = Mask.equals({0, 0, 2, 2});
23139 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
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);
23146 DCI.AddToWorklist(Op.getNode());
23147 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23151 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23152 bool Lo = Mask.equals({0, 0, 1, 1});
23153 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23154 MVT ShuffleVT = MVT::v4f32;
23155 if (Depth == 1 && Root->getOpcode() == Shuffle)
23156 return false; // Nothing to do!
23157 Op = DAG.getBitcast(ShuffleVT, Input);
23158 DCI.AddToWorklist(Op.getNode());
23159 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23160 DCI.AddToWorklist(Op.getNode());
23161 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23167 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23168 // variants as none of these have single-instruction variants that are
23169 // superior to the UNPCK formulation.
23170 if (!FloatDomain && VT.is128BitVector() &&
23171 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23172 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23173 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23175 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23176 bool Lo = Mask[0] == 0;
23177 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23178 if (Depth == 1 && Root->getOpcode() == Shuffle)
23179 return false; // Nothing to do!
23181 switch (Mask.size()) {
23183 ShuffleVT = MVT::v8i16;
23186 ShuffleVT = MVT::v16i8;
23189 llvm_unreachable("Impossible mask size!");
23191 Op = DAG.getBitcast(ShuffleVT, Input);
23192 DCI.AddToWorklist(Op.getNode());
23193 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23194 DCI.AddToWorklist(Op.getNode());
23195 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23200 // Don't try to re-form single instruction chains under any circumstances now
23201 // that we've done encoding canonicalization for them.
23205 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23206 // can replace them with a single PSHUFB instruction profitably. Intel's
23207 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23208 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23209 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23210 SmallVector<SDValue, 16> PSHUFBMask;
23211 int NumBytes = VT.getSizeInBits() / 8;
23212 int Ratio = NumBytes / Mask.size();
23213 for (int i = 0; i < NumBytes; ++i) {
23214 if (Mask[i / Ratio] == SM_SentinelUndef) {
23215 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23218 int M = Mask[i / Ratio] != SM_SentinelZero
23219 ? Ratio * Mask[i / Ratio] + i % Ratio
23221 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23223 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23224 Op = DAG.getBitcast(ByteVT, Input);
23225 DCI.AddToWorklist(Op.getNode());
23226 SDValue PSHUFBMaskOp =
23227 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23228 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23229 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23230 DCI.AddToWorklist(Op.getNode());
23231 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23236 // Failed to find any combines.
23240 /// \brief Fully generic combining of x86 shuffle instructions.
23242 /// This should be the last combine run over the x86 shuffle instructions. Once
23243 /// they have been fully optimized, this will recursively consider all chains
23244 /// of single-use shuffle instructions, build a generic model of the cumulative
23245 /// shuffle operation, and check for simpler instructions which implement this
23246 /// operation. We use this primarily for two purposes:
23248 /// 1) Collapse generic shuffles to specialized single instructions when
23249 /// equivalent. In most cases, this is just an encoding size win, but
23250 /// sometimes we will collapse multiple generic shuffles into a single
23251 /// special-purpose shuffle.
23252 /// 2) Look for sequences of shuffle instructions with 3 or more total
23253 /// instructions, and replace them with the slightly more expensive SSSE3
23254 /// PSHUFB instruction if available. We do this as the last combining step
23255 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
23256 /// a suitable short sequence of other instructions. The PHUFB will either
23257 /// use a register or have to read from memory and so is slightly (but only
23258 /// slightly) more expensive than the other shuffle instructions.
23260 /// Because this is inherently a quadratic operation (for each shuffle in
23261 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23262 /// This should never be an issue in practice as the shuffle lowering doesn't
23263 /// produce sequences of more than 8 instructions.
23265 /// FIXME: We will currently miss some cases where the redundant shuffling
23266 /// would simplify under the threshold for PSHUFB formation because of
23267 /// combine-ordering. To fix this, we should do the redundant instruction
23268 /// combining in this recursive walk.
23269 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23270 ArrayRef<int> RootMask,
23271 int Depth, bool HasPSHUFB,
23273 TargetLowering::DAGCombinerInfo &DCI,
23274 const X86Subtarget *Subtarget) {
23275 // Bound the depth of our recursive combine because this is ultimately
23276 // quadratic in nature.
23280 // Directly rip through bitcasts to find the underlying operand.
23281 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23282 Op = Op.getOperand(0);
23284 MVT VT = Op.getSimpleValueType();
23285 if (!VT.isVector())
23286 return false; // Bail if we hit a non-vector.
23288 assert(Root.getSimpleValueType().isVector() &&
23289 "Shuffles operate on vector types!");
23290 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23291 "Can only combine shuffles of the same vector register size.");
23293 if (!isTargetShuffle(Op.getOpcode()))
23295 SmallVector<int, 16> OpMask;
23297 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23298 // We only can combine unary shuffles which we can decode the mask for.
23299 if (!HaveMask || !IsUnary)
23302 assert(VT.getVectorNumElements() == OpMask.size() &&
23303 "Different mask size from vector size!");
23304 assert(((RootMask.size() > OpMask.size() &&
23305 RootMask.size() % OpMask.size() == 0) ||
23306 (OpMask.size() > RootMask.size() &&
23307 OpMask.size() % RootMask.size() == 0) ||
23308 OpMask.size() == RootMask.size()) &&
23309 "The smaller number of elements must divide the larger.");
23310 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23311 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23312 assert(((RootRatio == 1 && OpRatio == 1) ||
23313 (RootRatio == 1) != (OpRatio == 1)) &&
23314 "Must not have a ratio for both incoming and op masks!");
23316 SmallVector<int, 16> Mask;
23317 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23319 // Merge this shuffle operation's mask into our accumulated mask. Note that
23320 // this shuffle's mask will be the first applied to the input, followed by the
23321 // root mask to get us all the way to the root value arrangement. The reason
23322 // for this order is that we are recursing up the operation chain.
23323 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23324 int RootIdx = i / RootRatio;
23325 if (RootMask[RootIdx] < 0) {
23326 // This is a zero or undef lane, we're done.
23327 Mask.push_back(RootMask[RootIdx]);
23331 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23332 int OpIdx = RootMaskedIdx / OpRatio;
23333 if (OpMask[OpIdx] < 0) {
23334 // The incoming lanes are zero or undef, it doesn't matter which ones we
23336 Mask.push_back(OpMask[OpIdx]);
23340 // Ok, we have non-zero lanes, map them through.
23341 Mask.push_back(OpMask[OpIdx] * OpRatio +
23342 RootMaskedIdx % OpRatio);
23345 // See if we can recurse into the operand to combine more things.
23346 switch (Op.getOpcode()) {
23347 case X86ISD::PSHUFB:
23349 case X86ISD::PSHUFD:
23350 case X86ISD::PSHUFHW:
23351 case X86ISD::PSHUFLW:
23352 if (Op.getOperand(0).hasOneUse() &&
23353 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23354 HasPSHUFB, DAG, DCI, Subtarget))
23358 case X86ISD::UNPCKL:
23359 case X86ISD::UNPCKH:
23360 assert(Op.getOperand(0) == Op.getOperand(1) &&
23361 "We only combine unary shuffles!");
23362 // We can't check for single use, we have to check that this shuffle is the
23364 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23365 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23366 HasPSHUFB, DAG, DCI, Subtarget))
23371 // Minor canonicalization of the accumulated shuffle mask to make it easier
23372 // to match below. All this does is detect masks with squential pairs of
23373 // elements, and shrink them to the half-width mask. It does this in a loop
23374 // so it will reduce the size of the mask to the minimal width mask which
23375 // performs an equivalent shuffle.
23376 SmallVector<int, 16> WidenedMask;
23377 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23378 Mask = std::move(WidenedMask);
23379 WidenedMask.clear();
23382 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23386 /// \brief Get the PSHUF-style mask from PSHUF node.
23388 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23389 /// PSHUF-style masks that can be reused with such instructions.
23390 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23391 MVT VT = N.getSimpleValueType();
23392 SmallVector<int, 4> Mask;
23394 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23398 // If we have more than 128-bits, only the low 128-bits of shuffle mask
23399 // matter. Check that the upper masks are repeats and remove them.
23400 if (VT.getSizeInBits() > 128) {
23401 int LaneElts = 128 / VT.getScalarSizeInBits();
23403 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23404 for (int j = 0; j < LaneElts; ++j)
23405 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23406 "Mask doesn't repeat in high 128-bit lanes!");
23408 Mask.resize(LaneElts);
23411 switch (N.getOpcode()) {
23412 case X86ISD::PSHUFD:
23414 case X86ISD::PSHUFLW:
23417 case X86ISD::PSHUFHW:
23418 Mask.erase(Mask.begin(), Mask.begin() + 4);
23419 for (int &M : Mask)
23423 llvm_unreachable("No valid shuffle instruction found!");
23427 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23429 /// We walk up the chain and look for a combinable shuffle, skipping over
23430 /// shuffles that we could hoist this shuffle's transformation past without
23431 /// altering anything.
23433 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23435 TargetLowering::DAGCombinerInfo &DCI) {
23436 assert(N.getOpcode() == X86ISD::PSHUFD &&
23437 "Called with something other than an x86 128-bit half shuffle!");
23440 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23441 // of the shuffles in the chain so that we can form a fresh chain to replace
23443 SmallVector<SDValue, 8> Chain;
23444 SDValue V = N.getOperand(0);
23445 for (; V.hasOneUse(); V = V.getOperand(0)) {
23446 switch (V.getOpcode()) {
23448 return SDValue(); // Nothing combined!
23451 // Skip bitcasts as we always know the type for the target specific
23455 case X86ISD::PSHUFD:
23456 // Found another dword shuffle.
23459 case X86ISD::PSHUFLW:
23460 // Check that the low words (being shuffled) are the identity in the
23461 // dword shuffle, and the high words are self-contained.
23462 if (Mask[0] != 0 || Mask[1] != 1 ||
23463 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23466 Chain.push_back(V);
23469 case X86ISD::PSHUFHW:
23470 // Check that the high words (being shuffled) are the identity in the
23471 // dword shuffle, and the low words are self-contained.
23472 if (Mask[2] != 2 || Mask[3] != 3 ||
23473 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23476 Chain.push_back(V);
23479 case X86ISD::UNPCKL:
23480 case X86ISD::UNPCKH:
23481 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23482 // shuffle into a preceding word shuffle.
23483 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23484 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23487 // Search for a half-shuffle which we can combine with.
23488 unsigned CombineOp =
23489 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23490 if (V.getOperand(0) != V.getOperand(1) ||
23491 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23493 Chain.push_back(V);
23494 V = V.getOperand(0);
23496 switch (V.getOpcode()) {
23498 return SDValue(); // Nothing to combine.
23500 case X86ISD::PSHUFLW:
23501 case X86ISD::PSHUFHW:
23502 if (V.getOpcode() == CombineOp)
23505 Chain.push_back(V);
23509 V = V.getOperand(0);
23513 } while (V.hasOneUse());
23516 // Break out of the loop if we break out of the switch.
23520 if (!V.hasOneUse())
23521 // We fell out of the loop without finding a viable combining instruction.
23524 // Merge this node's mask and our incoming mask.
23525 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23526 for (int &M : Mask)
23528 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23529 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23531 // Rebuild the chain around this new shuffle.
23532 while (!Chain.empty()) {
23533 SDValue W = Chain.pop_back_val();
23535 if (V.getValueType() != W.getOperand(0).getValueType())
23536 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23538 switch (W.getOpcode()) {
23540 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23542 case X86ISD::UNPCKL:
23543 case X86ISD::UNPCKH:
23544 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23547 case X86ISD::PSHUFD:
23548 case X86ISD::PSHUFLW:
23549 case X86ISD::PSHUFHW:
23550 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23554 if (V.getValueType() != N.getValueType())
23555 V = DAG.getBitcast(N.getValueType(), V);
23557 // Return the new chain to replace N.
23561 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23564 /// We walk up the chain, skipping shuffles of the other half and looking
23565 /// through shuffles which switch halves trying to find a shuffle of the same
23566 /// pair of dwords.
23567 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23569 TargetLowering::DAGCombinerInfo &DCI) {
23571 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23572 "Called with something other than an x86 128-bit half shuffle!");
23574 unsigned CombineOpcode = N.getOpcode();
23576 // Walk up a single-use chain looking for a combinable shuffle.
23577 SDValue V = N.getOperand(0);
23578 for (; V.hasOneUse(); V = V.getOperand(0)) {
23579 switch (V.getOpcode()) {
23581 return false; // Nothing combined!
23584 // Skip bitcasts as we always know the type for the target specific
23588 case X86ISD::PSHUFLW:
23589 case X86ISD::PSHUFHW:
23590 if (V.getOpcode() == CombineOpcode)
23593 // Other-half shuffles are no-ops.
23596 // Break out of the loop if we break out of the switch.
23600 if (!V.hasOneUse())
23601 // We fell out of the loop without finding a viable combining instruction.
23604 // Combine away the bottom node as its shuffle will be accumulated into
23605 // a preceding shuffle.
23606 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23608 // Record the old value.
23611 // Merge this node's mask and our incoming mask (adjusted to account for all
23612 // the pshufd instructions encountered).
23613 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23614 for (int &M : Mask)
23616 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23617 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23619 // Check that the shuffles didn't cancel each other out. If not, we need to
23620 // combine to the new one.
23622 // Replace the combinable shuffle with the combined one, updating all users
23623 // so that we re-evaluate the chain here.
23624 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23629 /// \brief Try to combine x86 target specific shuffles.
23630 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23631 TargetLowering::DAGCombinerInfo &DCI,
23632 const X86Subtarget *Subtarget) {
23634 MVT VT = N.getSimpleValueType();
23635 SmallVector<int, 4> Mask;
23637 switch (N.getOpcode()) {
23638 case X86ISD::PSHUFD:
23639 case X86ISD::PSHUFLW:
23640 case X86ISD::PSHUFHW:
23641 Mask = getPSHUFShuffleMask(N);
23642 assert(Mask.size() == 4);
23644 case X86ISD::UNPCKL: {
23645 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23646 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23647 // moves upper half elements into the lower half part. For example:
23649 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23651 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23653 // will be combined to:
23655 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23657 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23658 // happen due to advanced instructions.
23659 if (!VT.is128BitVector())
23662 auto Op0 = N.getOperand(0);
23663 auto Op1 = N.getOperand(1);
23664 if (Op0.getOpcode() == ISD::UNDEF &&
23665 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23666 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23668 unsigned NumElts = VT.getVectorNumElements();
23669 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23670 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23673 auto ShufOp = Op1.getOperand(0);
23674 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23675 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23679 case X86ISD::BLENDI: {
23680 SDValue V0 = N->getOperand(0);
23681 SDValue V1 = N->getOperand(1);
23682 assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23683 "Unexpected input vector types");
23685 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23686 // operands and changing the mask to 1. This saves us a bunch of
23687 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23688 // x86InstrInfo knows how to commute this back after instruction selection
23689 // if it would help register allocation.
23691 // TODO: If optimizing for size or a processor that doesn't suffer from
23692 // partial register update stalls, this should be transformed into a MOVSD
23693 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23695 if (VT == MVT::v2f64)
23696 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23697 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23698 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23699 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23708 // Nuke no-op shuffles that show up after combining.
23709 if (isNoopShuffleMask(Mask))
23710 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23712 // Look for simplifications involving one or two shuffle instructions.
23713 SDValue V = N.getOperand(0);
23714 switch (N.getOpcode()) {
23717 case X86ISD::PSHUFLW:
23718 case X86ISD::PSHUFHW:
23719 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23721 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23722 return SDValue(); // We combined away this shuffle, so we're done.
23724 // See if this reduces to a PSHUFD which is no more expensive and can
23725 // combine with more operations. Note that it has to at least flip the
23726 // dwords as otherwise it would have been removed as a no-op.
23727 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23728 int DMask[] = {0, 1, 2, 3};
23729 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23730 DMask[DOffset + 0] = DOffset + 1;
23731 DMask[DOffset + 1] = DOffset + 0;
23732 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23733 V = DAG.getBitcast(DVT, V);
23734 DCI.AddToWorklist(V.getNode());
23735 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23736 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23737 DCI.AddToWorklist(V.getNode());
23738 return DAG.getBitcast(VT, V);
23741 // Look for shuffle patterns which can be implemented as a single unpack.
23742 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23743 // only works when we have a PSHUFD followed by two half-shuffles.
23744 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23745 (V.getOpcode() == X86ISD::PSHUFLW ||
23746 V.getOpcode() == X86ISD::PSHUFHW) &&
23747 V.getOpcode() != N.getOpcode() &&
23749 SDValue D = V.getOperand(0);
23750 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23751 D = D.getOperand(0);
23752 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23753 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23754 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23755 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23756 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23758 for (int i = 0; i < 4; ++i) {
23759 WordMask[i + NOffset] = Mask[i] + NOffset;
23760 WordMask[i + VOffset] = VMask[i] + VOffset;
23762 // Map the word mask through the DWord mask.
23764 for (int i = 0; i < 8; ++i)
23765 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23766 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23767 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23768 // We can replace all three shuffles with an unpack.
23769 V = DAG.getBitcast(VT, D.getOperand(0));
23770 DCI.AddToWorklist(V.getNode());
23771 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23780 case X86ISD::PSHUFD:
23781 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23790 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23792 /// We combine this directly on the abstract vector shuffle nodes so it is
23793 /// easier to generically match. We also insert dummy vector shuffle nodes for
23794 /// the operands which explicitly discard the lanes which are unused by this
23795 /// operation to try to flow through the rest of the combiner the fact that
23796 /// they're unused.
23797 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23798 SelectionDAG &DAG) {
23800 EVT VT = N->getValueType(0);
23801 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23802 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23805 // We only handle target-independent shuffles.
23806 // FIXME: It would be easy and harmless to use the target shuffle mask
23807 // extraction tool to support more.
23808 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23811 auto *SVN = cast<ShuffleVectorSDNode>(N);
23812 SmallVector<int, 8> Mask;
23813 for (int M : SVN->getMask())
23816 SDValue V1 = N->getOperand(0);
23817 SDValue V2 = N->getOperand(1);
23819 // We require the first shuffle operand to be the FSUB node, and the second to
23820 // be the FADD node.
23821 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23822 ShuffleVectorSDNode::commuteMask(Mask);
23824 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23827 // If there are other uses of these operations we can't fold them.
23828 if (!V1->hasOneUse() || !V2->hasOneUse())
23831 // Ensure that both operations have the same operands. Note that we can
23832 // commute the FADD operands.
23833 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23834 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23835 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23838 // We're looking for blends between FADD and FSUB nodes. We insist on these
23839 // nodes being lined up in a specific expected pattern.
23840 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23841 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23842 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23845 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23848 /// PerformShuffleCombine - Performs several different shuffle combines.
23849 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23850 TargetLowering::DAGCombinerInfo &DCI,
23851 const X86Subtarget *Subtarget) {
23853 SDValue N0 = N->getOperand(0);
23854 SDValue N1 = N->getOperand(1);
23855 EVT VT = N->getValueType(0);
23857 // Don't create instructions with illegal types after legalize types has run.
23858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23859 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23862 // If we have legalized the vector types, look for blends of FADD and FSUB
23863 // nodes that we can fuse into an ADDSUB node.
23864 if (TLI.isTypeLegal(VT))
23865 if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23868 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23869 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23870 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23871 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23873 // During Type Legalization, when promoting illegal vector types,
23874 // the backend might introduce new shuffle dag nodes and bitcasts.
23876 // This code performs the following transformation:
23877 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23878 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23880 // We do this only if both the bitcast and the BINOP dag nodes have
23881 // one use. Also, perform this transformation only if the new binary
23882 // operation is legal. This is to avoid introducing dag nodes that
23883 // potentially need to be further expanded (or custom lowered) into a
23884 // less optimal sequence of dag nodes.
23885 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23886 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23887 N0.getOpcode() == ISD::BITCAST) {
23888 SDValue BC0 = N0.getOperand(0);
23889 EVT SVT = BC0.getValueType();
23890 unsigned Opcode = BC0.getOpcode();
23891 unsigned NumElts = VT.getVectorNumElements();
23893 if (BC0.hasOneUse() && SVT.isVector() &&
23894 SVT.getVectorNumElements() * 2 == NumElts &&
23895 TLI.isOperationLegal(Opcode, VT)) {
23896 bool CanFold = false;
23908 unsigned SVTNumElts = SVT.getVectorNumElements();
23909 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23910 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23911 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23912 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23913 CanFold = SVOp->getMaskElt(i) < 0;
23916 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23917 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23918 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23919 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23924 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23925 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23926 // consecutive, non-overlapping, and in the right order.
23927 SmallVector<SDValue, 16> Elts;
23928 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23929 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23931 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23934 if (isTargetShuffle(N->getOpcode())) {
23936 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23937 if (Shuffle.getNode())
23940 // Try recursively combining arbitrary sequences of x86 shuffle
23941 // instructions into higher-order shuffles. We do this after combining
23942 // specific PSHUF instruction sequences into their minimal form so that we
23943 // can evaluate how many specialized shuffle instructions are involved in
23944 // a particular chain.
23945 SmallVector<int, 1> NonceMask; // Just a placeholder.
23946 NonceMask.push_back(0);
23947 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23948 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23950 return SDValue(); // This routine will use CombineTo to replace N.
23956 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23957 /// specific shuffle of a load can be folded into a single element load.
23958 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23959 /// shuffles have been custom lowered so we need to handle those here.
23960 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23961 TargetLowering::DAGCombinerInfo &DCI) {
23962 if (DCI.isBeforeLegalizeOps())
23965 SDValue InVec = N->getOperand(0);
23966 SDValue EltNo = N->getOperand(1);
23967 EVT EltVT = N->getValueType(0);
23969 if (!isa<ConstantSDNode>(EltNo))
23972 EVT OriginalVT = InVec.getValueType();
23974 if (InVec.getOpcode() == ISD::BITCAST) {
23975 // Don't duplicate a load with other uses.
23976 if (!InVec.hasOneUse())
23978 EVT BCVT = InVec.getOperand(0).getValueType();
23979 if (!BCVT.isVector() ||
23980 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23982 InVec = InVec.getOperand(0);
23985 EVT CurrentVT = InVec.getValueType();
23987 if (!isTargetShuffle(InVec.getOpcode()))
23990 // Don't duplicate a load with other uses.
23991 if (!InVec.hasOneUse())
23994 SmallVector<int, 16> ShuffleMask;
23996 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23997 ShuffleMask, UnaryShuffle))
24000 // Select the input vector, guarding against out of range extract vector.
24001 unsigned NumElems = CurrentVT.getVectorNumElements();
24002 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
24003 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
24005 if (Idx == SM_SentinelZero)
24006 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
24007 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
24008 if (Idx == SM_SentinelUndef)
24009 return DAG.getUNDEF(EltVT);
24011 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
24012 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
24013 : InVec.getOperand(1);
24015 // If inputs to shuffle are the same for both ops, then allow 2 uses
24016 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
24017 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
24019 if (LdNode.getOpcode() == ISD::BITCAST) {
24020 // Don't duplicate a load with other uses.
24021 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
24024 AllowedUses = 1; // only allow 1 load use if we have a bitcast
24025 LdNode = LdNode.getOperand(0);
24028 if (!ISD::isNormalLoad(LdNode.getNode()))
24031 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
24033 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
24036 // If there's a bitcast before the shuffle, check if the load type and
24037 // alignment is valid.
24038 unsigned Align = LN0->getAlignment();
24039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24040 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
24041 EltVT.getTypeForEVT(*DAG.getContext()));
24043 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
24046 // All checks match so transform back to vector_shuffle so that DAG combiner
24047 // can finish the job
24050 // Create shuffle node taking into account the case that its a unary shuffle
24051 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
24052 : InVec.getOperand(1);
24053 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
24054 InVec.getOperand(0), Shuffle,
24056 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
24057 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
24061 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
24062 const X86Subtarget *Subtarget) {
24063 SDValue N0 = N->getOperand(0);
24064 EVT VT = N->getValueType(0);
24066 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
24067 // special and don't usually play with other vector types, it's better to
24068 // handle them early to be sure we emit efficient code by avoiding
24069 // store-load conversions.
24070 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
24071 N0.getValueType() == MVT::v2i32 &&
24072 isNullConstant(N0.getOperand(1))) {
24073 SDValue N00 = N0->getOperand(0);
24074 if (N00.getValueType() == MVT::i32)
24075 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
24078 // Convert a bitcasted integer logic operation that has one bitcasted
24079 // floating-point operand and one constant operand into a floating-point
24080 // logic operation. This may create a load of the constant, but that is
24081 // cheaper than materializing the constant in an integer register and
24082 // transferring it to an SSE register or transferring the SSE operand to
24083 // integer register and back.
24085 switch (N0.getOpcode()) {
24086 case ISD::AND: FPOpcode = X86ISD::FAND; break;
24087 case ISD::OR: FPOpcode = X86ISD::FOR; break;
24088 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24089 default: return SDValue();
24091 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24092 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24093 isa<ConstantSDNode>(N0.getOperand(1)) &&
24094 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24095 N0.getOperand(0).getOperand(0).getValueType() == VT) {
24096 SDValue N000 = N0.getOperand(0).getOperand(0);
24097 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24098 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24104 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24105 /// generation and convert it from being a bunch of shuffles and extracts
24106 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24107 /// storing the value and loading scalars back, while for x64 we should
24108 /// use 64-bit extracts and shifts.
24109 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24110 TargetLowering::DAGCombinerInfo &DCI) {
24111 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24114 SDValue InputVector = N->getOperand(0);
24115 SDLoc dl(InputVector);
24116 // Detect mmx to i32 conversion through a v2i32 elt extract.
24117 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24118 N->getValueType(0) == MVT::i32 &&
24119 InputVector.getValueType() == MVT::v2i32) {
24121 // The bitcast source is a direct mmx result.
24122 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24123 if (MMXSrc.getValueType() == MVT::x86mmx)
24124 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24125 N->getValueType(0),
24126 InputVector.getNode()->getOperand(0));
24128 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24129 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24130 MMXSrc.getValueType() == MVT::i64) {
24131 SDValue MMXSrcOp = MMXSrc.getOperand(0);
24132 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24133 MMXSrcOp.getValueType() == MVT::v1i64 &&
24134 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24135 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24136 N->getValueType(0), MMXSrcOp.getOperand(0));
24140 EVT VT = N->getValueType(0);
24142 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24143 InputVector.getOpcode() == ISD::BITCAST &&
24144 isa<ConstantSDNode>(InputVector.getOperand(0))) {
24145 uint64_t ExtractedElt =
24146 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24147 uint64_t InputValue =
24148 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24149 uint64_t Res = (InputValue >> ExtractedElt) & 1;
24150 return DAG.getConstant(Res, dl, MVT::i1);
24152 // Only operate on vectors of 4 elements, where the alternative shuffling
24153 // gets to be more expensive.
24154 if (InputVector.getValueType() != MVT::v4i32)
24157 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24158 // single use which is a sign-extend or zero-extend, and all elements are
24160 SmallVector<SDNode *, 4> Uses;
24161 unsigned ExtractedElements = 0;
24162 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24163 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24164 if (UI.getUse().getResNo() != InputVector.getResNo())
24167 SDNode *Extract = *UI;
24168 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24171 if (Extract->getValueType(0) != MVT::i32)
24173 if (!Extract->hasOneUse())
24175 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24176 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24178 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24181 // Record which element was extracted.
24182 ExtractedElements |=
24183 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24185 Uses.push_back(Extract);
24188 // If not all the elements were used, this may not be worthwhile.
24189 if (ExtractedElements != 15)
24192 // Ok, we've now decided to do the transformation.
24193 // If 64-bit shifts are legal, use the extract-shift sequence,
24194 // otherwise bounce the vector off the cache.
24195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24198 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24199 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24200 auto &DL = DAG.getDataLayout();
24201 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24202 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24203 DAG.getConstant(0, dl, VecIdxTy));
24204 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24205 DAG.getConstant(1, dl, VecIdxTy));
24207 SDValue ShAmt = DAG.getConstant(
24208 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24209 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24210 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24211 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24212 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24213 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24214 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24216 // Store the value to a temporary stack slot.
24217 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24218 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24219 MachinePointerInfo(), false, false, 0);
24221 EVT ElementType = InputVector.getValueType().getVectorElementType();
24222 unsigned EltSize = ElementType.getSizeInBits() / 8;
24224 // Replace each use (extract) with a load of the appropriate element.
24225 for (unsigned i = 0; i < 4; ++i) {
24226 uint64_t Offset = EltSize * i;
24227 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24228 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24230 SDValue ScalarAddr =
24231 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24233 // Load the scalar.
24234 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24235 ScalarAddr, MachinePointerInfo(),
24236 false, false, false, 0);
24241 // Replace the extracts
24242 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24243 UE = Uses.end(); UI != UE; ++UI) {
24244 SDNode *Extract = *UI;
24246 SDValue Idx = Extract->getOperand(1);
24247 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24248 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24251 // The replacement was made in place; don't return anything.
24256 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24257 const X86Subtarget *Subtarget) {
24259 SDValue Cond = N->getOperand(0);
24260 SDValue LHS = N->getOperand(1);
24261 SDValue RHS = N->getOperand(2);
24263 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24264 SDValue CondSrc = Cond->getOperand(0);
24265 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24266 Cond = CondSrc->getOperand(0);
24269 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24272 // A vselect where all conditions and data are constants can be optimized into
24273 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24274 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24275 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24278 unsigned MaskValue = 0;
24279 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24282 MVT VT = N->getSimpleValueType(0);
24283 unsigned NumElems = VT.getVectorNumElements();
24284 SmallVector<int, 8> ShuffleMask(NumElems, -1);
24285 for (unsigned i = 0; i < NumElems; ++i) {
24286 // Be sure we emit undef where we can.
24287 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24288 ShuffleMask[i] = -1;
24290 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24293 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24294 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24296 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24299 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24301 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24302 TargetLowering::DAGCombinerInfo &DCI,
24303 const X86Subtarget *Subtarget) {
24305 SDValue Cond = N->getOperand(0);
24306 // Get the LHS/RHS of the select.
24307 SDValue LHS = N->getOperand(1);
24308 SDValue RHS = N->getOperand(2);
24309 EVT VT = LHS.getValueType();
24310 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24312 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24313 // instructions match the semantics of the common C idiom x<y?x:y but not
24314 // x<=y?x:y, because of how they handle negative zero (which can be
24315 // ignored in unsafe-math mode).
24316 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24317 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24318 VT != MVT::f80 && VT != MVT::f128 &&
24319 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24320 (Subtarget->hasSSE2() ||
24321 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24322 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24324 unsigned Opcode = 0;
24325 // Check for x CC y ? x : y.
24326 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24327 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24331 // Converting this to a min would handle NaNs incorrectly, and swapping
24332 // the operands would cause it to handle comparisons between positive
24333 // and negative zero incorrectly.
24334 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24335 if (!DAG.getTarget().Options.UnsafeFPMath &&
24336 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24338 std::swap(LHS, RHS);
24340 Opcode = X86ISD::FMIN;
24343 // Converting this to a min would handle comparisons between positive
24344 // and negative zero incorrectly.
24345 if (!DAG.getTarget().Options.UnsafeFPMath &&
24346 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24348 Opcode = X86ISD::FMIN;
24351 // Converting this to a min would handle both negative zeros and NaNs
24352 // incorrectly, but we can swap the operands to fix both.
24353 std::swap(LHS, RHS);
24357 Opcode = X86ISD::FMIN;
24361 // Converting this to a max would handle comparisons between positive
24362 // and negative zero incorrectly.
24363 if (!DAG.getTarget().Options.UnsafeFPMath &&
24364 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24366 Opcode = X86ISD::FMAX;
24369 // Converting this to a max would handle NaNs incorrectly, and swapping
24370 // the operands would cause it to handle comparisons between positive
24371 // and negative zero incorrectly.
24372 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24373 if (!DAG.getTarget().Options.UnsafeFPMath &&
24374 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24376 std::swap(LHS, RHS);
24378 Opcode = X86ISD::FMAX;
24381 // Converting this to a max would handle both negative zeros and NaNs
24382 // incorrectly, but we can swap the operands to fix both.
24383 std::swap(LHS, RHS);
24387 Opcode = X86ISD::FMAX;
24390 // Check for x CC y ? y : x -- a min/max with reversed arms.
24391 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24392 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24396 // Converting this to a min would handle comparisons between positive
24397 // and negative zero incorrectly, and swapping the operands would
24398 // cause it to handle NaNs incorrectly.
24399 if (!DAG.getTarget().Options.UnsafeFPMath &&
24400 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24401 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24403 std::swap(LHS, RHS);
24405 Opcode = X86ISD::FMIN;
24408 // Converting this to a min would handle NaNs incorrectly.
24409 if (!DAG.getTarget().Options.UnsafeFPMath &&
24410 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24412 Opcode = X86ISD::FMIN;
24415 // Converting this to a min would handle both negative zeros and NaNs
24416 // incorrectly, but we can swap the operands to fix both.
24417 std::swap(LHS, RHS);
24421 Opcode = X86ISD::FMIN;
24425 // Converting this to a max would handle NaNs incorrectly.
24426 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24428 Opcode = X86ISD::FMAX;
24431 // Converting this to a max would handle comparisons between positive
24432 // and negative zero incorrectly, and swapping the operands would
24433 // cause it to handle NaNs incorrectly.
24434 if (!DAG.getTarget().Options.UnsafeFPMath &&
24435 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24436 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24438 std::swap(LHS, RHS);
24440 Opcode = X86ISD::FMAX;
24443 // Converting this to a max would handle both negative zeros and NaNs
24444 // incorrectly, but we can swap the operands to fix both.
24445 std::swap(LHS, RHS);
24449 Opcode = X86ISD::FMAX;
24455 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24458 EVT CondVT = Cond.getValueType();
24459 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24460 CondVT.getVectorElementType() == MVT::i1) {
24461 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24462 // lowering on KNL. In this case we convert it to
24463 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24464 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24465 // Since SKX these selects have a proper lowering.
24466 EVT OpVT = LHS.getValueType();
24467 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24468 (OpVT.getVectorElementType() == MVT::i8 ||
24469 OpVT.getVectorElementType() == MVT::i16) &&
24470 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24471 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24472 DCI.AddToWorklist(Cond.getNode());
24473 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24476 // If this is a select between two integer constants, try to do some
24478 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24479 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24480 // Don't do this for crazy integer types.
24481 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24482 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24483 // so that TrueC (the true value) is larger than FalseC.
24484 bool NeedsCondInvert = false;
24486 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24487 // Efficiently invertible.
24488 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24489 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24490 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24491 NeedsCondInvert = true;
24492 std::swap(TrueC, FalseC);
24495 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24496 if (FalseC->getAPIntValue() == 0 &&
24497 TrueC->getAPIntValue().isPowerOf2()) {
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, LHS.getValueType(), Cond);
24505 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24506 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24507 DAG.getConstant(ShAmt, DL, MVT::i8));
24510 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24511 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24512 if (NeedsCondInvert) // Invert the condition if needed.
24513 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24514 DAG.getConstant(1, DL, Cond.getValueType()));
24516 // Zero extend the condition if needed.
24517 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24518 FalseC->getValueType(0), Cond);
24519 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24520 SDValue(FalseC, 0));
24523 // Optimize cases that will turn into an LEA instruction. This requires
24524 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24525 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24526 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24527 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24529 bool isFastMultiplier = false;
24531 switch ((unsigned char)Diff) {
24533 case 1: // result = add base, cond
24534 case 2: // result = lea base( , cond*2)
24535 case 3: // result = lea base(cond, cond*2)
24536 case 4: // result = lea base( , cond*4)
24537 case 5: // result = lea base(cond, cond*4)
24538 case 8: // result = lea base( , cond*8)
24539 case 9: // result = lea base(cond, cond*8)
24540 isFastMultiplier = true;
24545 if (isFastMultiplier) {
24546 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24547 if (NeedsCondInvert) // Invert the condition if needed.
24548 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24549 DAG.getConstant(1, DL, Cond.getValueType()));
24551 // Zero extend the condition if needed.
24552 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24554 // Scale the condition by the difference.
24556 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24557 DAG.getConstant(Diff, DL,
24558 Cond.getValueType()));
24560 // Add the base if non-zero.
24561 if (FalseC->getAPIntValue() != 0)
24562 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24563 SDValue(FalseC, 0));
24570 // Canonicalize max and min:
24571 // (x > y) ? x : y -> (x >= y) ? x : y
24572 // (x < y) ? x : y -> (x <= y) ? x : y
24573 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24574 // the need for an extra compare
24575 // against zero. e.g.
24576 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24578 // testl %edi, %edi
24580 // cmovgl %edi, %eax
24584 // cmovsl %eax, %edi
24585 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24586 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24587 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24588 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24593 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24594 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24595 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24596 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24601 // Early exit check
24602 if (!TLI.isTypeLegal(VT))
24605 // Match VSELECTs into subs with unsigned saturation.
24606 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24607 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24608 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24609 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24610 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24612 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24613 // left side invert the predicate to simplify logic below.
24615 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24617 CC = ISD::getSetCCInverse(CC, true);
24618 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24622 if (Other.getNode() && Other->getNumOperands() == 2 &&
24623 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24624 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24625 SDValue CondRHS = Cond->getOperand(1);
24627 // Look for a general sub with unsigned saturation first.
24628 // x >= y ? x-y : 0 --> subus x, y
24629 // x > y ? x-y : 0 --> subus x, y
24630 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24631 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24632 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24634 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24635 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24636 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24637 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24638 // If the RHS is a constant we have to reverse the const
24639 // canonicalization.
24640 // x > C-1 ? x+-C : 0 --> subus x, C
24641 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24642 CondRHSConst->getAPIntValue() ==
24643 (-OpRHSConst->getAPIntValue() - 1))
24644 return DAG.getNode(
24645 X86ISD::SUBUS, DL, VT, OpLHS,
24646 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24648 // Another special case: If C was a sign bit, the sub has been
24649 // canonicalized into a xor.
24650 // FIXME: Would it be better to use computeKnownBits to determine
24651 // whether it's safe to decanonicalize the xor?
24652 // x s< 0 ? x^C : 0 --> subus x, C
24653 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24654 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24655 OpRHSConst->getAPIntValue().isSignBit())
24656 // Note that we have to rebuild the RHS constant here to ensure we
24657 // don't rely on particular values of undef lanes.
24658 return DAG.getNode(
24659 X86ISD::SUBUS, DL, VT, OpLHS,
24660 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24665 // Simplify vector selection if condition value type matches vselect
24667 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24668 assert(Cond.getValueType().isVector() &&
24669 "vector select expects a vector selector!");
24671 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24672 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24674 // Try invert the condition if true value is not all 1s and false value
24676 if (!TValIsAllOnes && !FValIsAllZeros &&
24677 // Check if the selector will be produced by CMPP*/PCMP*
24678 Cond.getOpcode() == ISD::SETCC &&
24679 // Check if SETCC has already been promoted
24680 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24682 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24683 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24685 if (TValIsAllZeros || FValIsAllOnes) {
24686 SDValue CC = Cond.getOperand(2);
24687 ISD::CondCode NewCC =
24688 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24689 Cond.getOperand(0).getValueType().isInteger());
24690 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24691 std::swap(LHS, RHS);
24692 TValIsAllOnes = FValIsAllOnes;
24693 FValIsAllZeros = TValIsAllZeros;
24697 if (TValIsAllOnes || FValIsAllZeros) {
24700 if (TValIsAllOnes && FValIsAllZeros)
24702 else if (TValIsAllOnes)
24704 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24705 else if (FValIsAllZeros)
24706 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24707 DAG.getBitcast(CondVT, LHS));
24709 return DAG.getBitcast(VT, Ret);
24713 // We should generate an X86ISD::BLENDI from a vselect if its argument
24714 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24715 // constants. This specific pattern gets generated when we split a
24716 // selector for a 512 bit vector in a machine without AVX512 (but with
24717 // 256-bit vectors), during legalization:
24719 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24721 // Iff we find this pattern and the build_vectors are built from
24722 // constants, we translate the vselect into a shuffle_vector that we
24723 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24724 if ((N->getOpcode() == ISD::VSELECT ||
24725 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24726 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24727 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24728 if (Shuffle.getNode())
24732 // If this is a *dynamic* select (non-constant condition) and we can match
24733 // this node with one of the variable blend instructions, restructure the
24734 // condition so that the blends can use the high bit of each element and use
24735 // SimplifyDemandedBits to simplify the condition operand.
24736 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24737 !DCI.isBeforeLegalize() &&
24738 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24739 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24741 // Don't optimize vector selects that map to mask-registers.
24745 // We can only handle the cases where VSELECT is directly legal on the
24746 // subtarget. We custom lower VSELECT nodes with constant conditions and
24747 // this makes it hard to see whether a dynamic VSELECT will correctly
24748 // lower, so we both check the operation's status and explicitly handle the
24749 // cases where a *dynamic* blend will fail even though a constant-condition
24750 // blend could be custom lowered.
24751 // FIXME: We should find a better way to handle this class of problems.
24752 // Potentially, we should combine constant-condition vselect nodes
24753 // pre-legalization into shuffles and not mark as many types as custom
24755 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24757 // FIXME: We don't support i16-element blends currently. We could and
24758 // should support them by making *all* the bits in the condition be set
24759 // rather than just the high bit and using an i8-element blend.
24760 if (VT.getVectorElementType() == MVT::i16)
24762 // Dynamic blending was only available from SSE4.1 onward.
24763 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24765 // Byte blends are only available in AVX2
24766 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24769 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24770 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24772 APInt KnownZero, KnownOne;
24773 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24774 DCI.isBeforeLegalizeOps());
24775 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24776 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24778 // If we changed the computation somewhere in the DAG, this change
24779 // will affect all users of Cond.
24780 // Make sure it is fine and update all the nodes so that we do not
24781 // use the generic VSELECT anymore. Otherwise, we may perform
24782 // wrong optimizations as we messed up with the actual expectation
24783 // for the vector boolean values.
24784 if (Cond != TLO.Old) {
24785 // Check all uses of that condition operand to check whether it will be
24786 // consumed by non-BLEND instructions, which may depend on all bits are
24788 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24790 if (I->getOpcode() != ISD::VSELECT)
24791 // TODO: Add other opcodes eventually lowered into BLEND.
24794 // Update all the users of the condition, before committing the change,
24795 // so that the VSELECT optimizations that expect the correct vector
24796 // boolean value will not be triggered.
24797 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24799 DAG.ReplaceAllUsesOfValueWith(
24801 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24802 Cond, I->getOperand(1), I->getOperand(2)));
24803 DCI.CommitTargetLoweringOpt(TLO);
24806 // At this point, only Cond is changed. Change the condition
24807 // just for N to keep the opportunity to optimize all other
24808 // users their own way.
24809 DAG.ReplaceAllUsesOfValueWith(
24811 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24812 TLO.New, N->getOperand(1), N->getOperand(2)));
24820 // Check whether a boolean test is testing a boolean value generated by
24821 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24824 // Simplify the following patterns:
24825 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24826 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24827 // to (Op EFLAGS Cond)
24829 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24830 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24831 // to (Op EFLAGS !Cond)
24833 // where Op could be BRCOND or CMOV.
24835 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24836 // Quit if not CMP and SUB with its value result used.
24837 if (Cmp.getOpcode() != X86ISD::CMP &&
24838 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24841 // Quit if not used as a boolean value.
24842 if (CC != X86::COND_E && CC != X86::COND_NE)
24845 // Check CMP operands. One of them should be 0 or 1 and the other should be
24846 // an SetCC or extended from it.
24847 SDValue Op1 = Cmp.getOperand(0);
24848 SDValue Op2 = Cmp.getOperand(1);
24851 const ConstantSDNode* C = nullptr;
24852 bool needOppositeCond = (CC == X86::COND_E);
24853 bool checkAgainstTrue = false; // Is it a comparison against 1?
24855 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24857 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24859 else // Quit if all operands are not constants.
24862 if (C->getZExtValue() == 1) {
24863 needOppositeCond = !needOppositeCond;
24864 checkAgainstTrue = true;
24865 } else if (C->getZExtValue() != 0)
24866 // Quit if the constant is neither 0 or 1.
24869 bool truncatedToBoolWithAnd = false;
24870 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24871 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24872 SetCC.getOpcode() == ISD::TRUNCATE ||
24873 SetCC.getOpcode() == ISD::AND) {
24874 if (SetCC.getOpcode() == ISD::AND) {
24876 if (isOneConstant(SetCC.getOperand(0)))
24878 if (isOneConstant(SetCC.getOperand(1)))
24882 SetCC = SetCC.getOperand(OpIdx);
24883 truncatedToBoolWithAnd = true;
24885 SetCC = SetCC.getOperand(0);
24888 switch (SetCC.getOpcode()) {
24889 case X86ISD::SETCC_CARRY:
24890 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24891 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24892 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24893 // truncated to i1 using 'and'.
24894 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24896 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24897 "Invalid use of SETCC_CARRY!");
24899 case X86ISD::SETCC:
24900 // Set the condition code or opposite one if necessary.
24901 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24902 if (needOppositeCond)
24903 CC = X86::GetOppositeBranchCondition(CC);
24904 return SetCC.getOperand(1);
24905 case X86ISD::CMOV: {
24906 // Check whether false/true value has canonical one, i.e. 0 or 1.
24907 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24908 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24909 // Quit if true value is not a constant.
24912 // Quit if false value is not a constant.
24914 SDValue Op = SetCC.getOperand(0);
24915 // Skip 'zext' or 'trunc' node.
24916 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24917 Op.getOpcode() == ISD::TRUNCATE)
24918 Op = Op.getOperand(0);
24919 // A special case for rdrand/rdseed, where 0 is set if false cond is
24921 if ((Op.getOpcode() != X86ISD::RDRAND &&
24922 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24925 // Quit if false value is not the constant 0 or 1.
24926 bool FValIsFalse = true;
24927 if (FVal && FVal->getZExtValue() != 0) {
24928 if (FVal->getZExtValue() != 1)
24930 // If FVal is 1, opposite cond is needed.
24931 needOppositeCond = !needOppositeCond;
24932 FValIsFalse = false;
24934 // Quit if TVal is not the constant opposite of FVal.
24935 if (FValIsFalse && TVal->getZExtValue() != 1)
24937 if (!FValIsFalse && TVal->getZExtValue() != 0)
24939 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24940 if (needOppositeCond)
24941 CC = X86::GetOppositeBranchCondition(CC);
24942 return SetCC.getOperand(3);
24949 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24951 /// (X86or (X86setcc) (X86setcc))
24952 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24953 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24954 X86::CondCode &CC1, SDValue &Flags,
24956 if (Cond->getOpcode() == X86ISD::CMP) {
24957 if (!isNullConstant(Cond->getOperand(1)))
24960 Cond = Cond->getOperand(0);
24965 SDValue SetCC0, SetCC1;
24966 switch (Cond->getOpcode()) {
24967 default: return false;
24974 SetCC0 = Cond->getOperand(0);
24975 SetCC1 = Cond->getOperand(1);
24979 // Make sure we have SETCC nodes, using the same flags value.
24980 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24981 SetCC1.getOpcode() != X86ISD::SETCC ||
24982 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24985 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24986 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24987 Flags = SetCC0->getOperand(1);
24991 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24992 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24993 TargetLowering::DAGCombinerInfo &DCI,
24994 const X86Subtarget *Subtarget) {
24997 // If the flag operand isn't dead, don't touch this CMOV.
24998 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
25001 SDValue FalseOp = N->getOperand(0);
25002 SDValue TrueOp = N->getOperand(1);
25003 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
25004 SDValue Cond = N->getOperand(3);
25006 if (CC == X86::COND_E || CC == X86::COND_NE) {
25007 switch (Cond.getOpcode()) {
25011 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
25012 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
25013 return (CC == X86::COND_E) ? FalseOp : TrueOp;
25019 Flags = checkBoolTestSetCCCombine(Cond, CC);
25020 if (Flags.getNode() &&
25021 // Extra check as FCMOV only supports a subset of X86 cond.
25022 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
25023 SDValue Ops[] = { FalseOp, TrueOp,
25024 DAG.getConstant(CC, DL, MVT::i8), Flags };
25025 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25028 // If this is a select between two integer constants, try to do some
25029 // optimizations. Note that the operands are ordered the opposite of SELECT
25031 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
25032 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
25033 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
25034 // larger than FalseC (the false value).
25035 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
25036 CC = X86::GetOppositeBranchCondition(CC);
25037 std::swap(TrueC, FalseC);
25038 std::swap(TrueOp, FalseOp);
25041 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
25042 // This is efficient for any integer data type (including i8/i16) and
25044 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
25045 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25046 DAG.getConstant(CC, DL, MVT::i8), Cond);
25048 // Zero extend the condition if needed.
25049 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
25051 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
25052 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
25053 DAG.getConstant(ShAmt, DL, MVT::i8));
25054 if (N->getNumValues() == 2) // Dead flag value?
25055 return DCI.CombineTo(N, Cond, SDValue());
25059 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
25060 // for any integer data type, including i8/i16.
25061 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
25062 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25063 DAG.getConstant(CC, DL, MVT::i8), Cond);
25065 // Zero extend the condition if needed.
25066 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
25067 FalseC->getValueType(0), Cond);
25068 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25069 SDValue(FalseC, 0));
25071 if (N->getNumValues() == 2) // Dead flag value?
25072 return DCI.CombineTo(N, Cond, SDValue());
25076 // Optimize cases that will turn into an LEA instruction. This requires
25077 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
25078 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
25079 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
25080 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
25082 bool isFastMultiplier = false;
25084 switch ((unsigned char)Diff) {
25086 case 1: // result = add base, cond
25087 case 2: // result = lea base( , cond*2)
25088 case 3: // result = lea base(cond, cond*2)
25089 case 4: // result = lea base( , cond*4)
25090 case 5: // result = lea base(cond, cond*4)
25091 case 8: // result = lea base( , cond*8)
25092 case 9: // result = lea base(cond, cond*8)
25093 isFastMultiplier = true;
25098 if (isFastMultiplier) {
25099 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25100 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25101 DAG.getConstant(CC, DL, MVT::i8), Cond);
25102 // Zero extend the condition if needed.
25103 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25105 // Scale the condition by the difference.
25107 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25108 DAG.getConstant(Diff, DL, Cond.getValueType()));
25110 // Add the base if non-zero.
25111 if (FalseC->getAPIntValue() != 0)
25112 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25113 SDValue(FalseC, 0));
25114 if (N->getNumValues() == 2) // Dead flag value?
25115 return DCI.CombineTo(N, Cond, SDValue());
25122 // Handle these cases:
25123 // (select (x != c), e, c) -> select (x != c), e, x),
25124 // (select (x == c), c, e) -> select (x == c), x, e)
25125 // where the c is an integer constant, and the "select" is the combination
25126 // of CMOV and CMP.
25128 // The rationale for this change is that the conditional-move from a constant
25129 // needs two instructions, however, conditional-move from a register needs
25130 // only one instruction.
25132 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25133 // some instruction-combining opportunities. This opt needs to be
25134 // postponed as late as possible.
25136 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25137 // the DCI.xxxx conditions are provided to postpone the optimization as
25138 // late as possible.
25140 ConstantSDNode *CmpAgainst = nullptr;
25141 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25142 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25143 !isa<ConstantSDNode>(Cond.getOperand(0))) {
25145 if (CC == X86::COND_NE &&
25146 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25147 CC = X86::GetOppositeBranchCondition(CC);
25148 std::swap(TrueOp, FalseOp);
25151 if (CC == X86::COND_E &&
25152 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25153 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25154 DAG.getConstant(CC, DL, MVT::i8), Cond };
25155 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25160 // Fold and/or of setcc's to double CMOV:
25161 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25162 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25164 // This combine lets us generate:
25165 // cmovcc1 (jcc1 if we don't have CMOV)
25171 // cmovne (jne if we don't have CMOV)
25172 // When we can't use the CMOV instruction, it might increase branch
25174 // When we can use CMOV, or when there is no mispredict, this improves
25175 // throughput and reduces register pressure.
25177 if (CC == X86::COND_NE) {
25179 X86::CondCode CC0, CC1;
25181 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25183 std::swap(FalseOp, TrueOp);
25184 CC0 = X86::GetOppositeBranchCondition(CC0);
25185 CC1 = X86::GetOppositeBranchCondition(CC1);
25188 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25190 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25191 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25192 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25193 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25201 /// PerformMulCombine - Optimize a single multiply with constant into two
25202 /// in order to implement it with two cheaper instructions, e.g.
25203 /// LEA + SHL, LEA + LEA.
25204 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25205 TargetLowering::DAGCombinerInfo &DCI) {
25206 // An imul is usually smaller than the alternative sequence.
25207 if (DAG.getMachineFunction().getFunction()->optForMinSize())
25210 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25213 EVT VT = N->getValueType(0);
25214 if (VT != MVT::i64 && VT != MVT::i32)
25217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25220 uint64_t MulAmt = C->getZExtValue();
25221 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25224 uint64_t MulAmt1 = 0;
25225 uint64_t MulAmt2 = 0;
25226 if ((MulAmt % 9) == 0) {
25228 MulAmt2 = MulAmt / 9;
25229 } else if ((MulAmt % 5) == 0) {
25231 MulAmt2 = MulAmt / 5;
25232 } else if ((MulAmt % 3) == 0) {
25234 MulAmt2 = MulAmt / 3;
25240 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25242 if (isPowerOf2_64(MulAmt2) &&
25243 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25244 // If second multiplifer is pow2, issue it first. We want the multiply by
25245 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25247 std::swap(MulAmt1, MulAmt2);
25249 if (isPowerOf2_64(MulAmt1))
25250 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25251 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25253 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25254 DAG.getConstant(MulAmt1, DL, VT));
25256 if (isPowerOf2_64(MulAmt2))
25257 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25258 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25260 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25261 DAG.getConstant(MulAmt2, DL, VT));
25265 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25266 && "Both cases that could cause potential overflows should have "
25267 "already been handled.");
25268 if (isPowerOf2_64(MulAmt - 1))
25269 // (mul x, 2^N + 1) => (add (shl x, N), x)
25270 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25271 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25272 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25275 else if (isPowerOf2_64(MulAmt + 1))
25276 // (mul x, 2^N - 1) => (sub (shl x, N), x)
25277 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25279 DAG.getConstant(Log2_64(MulAmt + 1),
25280 DL, MVT::i8)), N->getOperand(0));
25284 // Do not add new nodes to DAG combiner worklist.
25285 DCI.CombineTo(N, NewMul, false);
25290 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25291 SDValue N0 = N->getOperand(0);
25292 SDValue N1 = N->getOperand(1);
25293 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25294 EVT VT = N0.getValueType();
25296 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25297 // since the result of setcc_c is all zero's or all ones.
25298 if (VT.isInteger() && !VT.isVector() &&
25299 N1C && N0.getOpcode() == ISD::AND &&
25300 N0.getOperand(1).getOpcode() == ISD::Constant) {
25301 SDValue N00 = N0.getOperand(0);
25302 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25303 APInt ShAmt = N1C->getAPIntValue();
25304 Mask = Mask.shl(ShAmt);
25305 bool MaskOK = false;
25306 // We can handle cases concerning bit-widening nodes containing setcc_c if
25307 // we carefully interrogate the mask to make sure we are semantics
25309 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25310 // of the underlying setcc_c operation if the setcc_c was zero extended.
25311 // Consider the following example:
25312 // zext(setcc_c) -> i32 0x0000FFFF
25313 // c1 -> i32 0x0000FFFF
25314 // c2 -> i32 0x00000001
25315 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25316 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
25317 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25319 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25320 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25322 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25323 N00.getOpcode() == ISD::ANY_EXTEND) &&
25324 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25325 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25327 if (MaskOK && Mask != 0) {
25329 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25333 // Hardware support for vector shifts is sparse which makes us scalarize the
25334 // vector operations in many cases. Also, on sandybridge ADD is faster than
25336 // (shl V, 1) -> add V,V
25337 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25338 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25339 assert(N0.getValueType().isVector() && "Invalid vector shift type");
25340 // We shift all of the values by one. In many cases we do not have
25341 // hardware support for this operation. This is better expressed as an ADD
25343 if (N1SplatC->getAPIntValue() == 1)
25344 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25350 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25351 SDValue N0 = N->getOperand(0);
25352 SDValue N1 = N->getOperand(1);
25353 EVT VT = N0.getValueType();
25354 unsigned Size = VT.getSizeInBits();
25356 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25357 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25358 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25359 // depending on sign of (SarConst - [56,48,32,24,16])
25361 // sexts in X86 are MOVs. The MOVs have the same code size
25362 // as above SHIFTs (only SHIFT on 1 has lower code size).
25363 // However the MOVs have 2 advantages to a SHIFT:
25364 // 1. MOVs can write to a register that differs from source
25365 // 2. MOVs accept memory operands
25367 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25368 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25369 N0.getOperand(1).getOpcode() != ISD::Constant)
25372 SDValue N00 = N0.getOperand(0);
25373 SDValue N01 = N0.getOperand(1);
25374 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25375 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25376 EVT CVT = N1.getValueType();
25378 if (SarConst.isNegative())
25381 for (MVT SVT : MVT::integer_valuetypes()) {
25382 unsigned ShiftSize = SVT.getSizeInBits();
25383 // skipping types without corresponding sext/zext and
25384 // ShlConst that is not one of [56,48,32,24,16]
25385 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25389 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25390 SarConst = SarConst - (Size - ShiftSize);
25393 else if (SarConst.isNegative())
25394 return DAG.getNode(ISD::SHL, DL, VT, NN,
25395 DAG.getConstant(-SarConst, DL, CVT));
25397 return DAG.getNode(ISD::SRA, DL, VT, NN,
25398 DAG.getConstant(SarConst, DL, CVT));
25403 /// \brief Returns a vector of 0s if the node in input is a vector logical
25404 /// shift by a constant amount which is known to be bigger than or equal
25405 /// to the vector element size in bits.
25406 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25407 const X86Subtarget *Subtarget) {
25408 EVT VT = N->getValueType(0);
25410 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25411 (!Subtarget->hasInt256() ||
25412 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25415 SDValue Amt = N->getOperand(1);
25417 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25418 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25419 APInt ShiftAmt = AmtSplat->getAPIntValue();
25420 unsigned MaxAmount =
25421 VT.getSimpleVT().getVectorElementType().getSizeInBits();
25423 // SSE2/AVX2 logical shifts always return a vector of 0s
25424 // if the shift amount is bigger than or equal to
25425 // the element size. The constant shift amount will be
25426 // encoded as a 8-bit immediate.
25427 if (ShiftAmt.trunc(8).uge(MaxAmount))
25428 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25434 /// PerformShiftCombine - Combine shifts.
25435 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25436 TargetLowering::DAGCombinerInfo &DCI,
25437 const X86Subtarget *Subtarget) {
25438 if (N->getOpcode() == ISD::SHL)
25439 if (SDValue V = PerformSHLCombine(N, DAG))
25442 if (N->getOpcode() == ISD::SRA)
25443 if (SDValue V = PerformSRACombine(N, DAG))
25446 // Try to fold this logical shift into a zero vector.
25447 if (N->getOpcode() != ISD::SRA)
25448 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25454 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
25455 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25456 // and friends. Likewise for OR -> CMPNEQSS.
25457 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25458 TargetLowering::DAGCombinerInfo &DCI,
25459 const X86Subtarget *Subtarget) {
25462 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25463 // we're requiring SSE2 for both.
25464 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25465 SDValue N0 = N->getOperand(0);
25466 SDValue N1 = N->getOperand(1);
25467 SDValue CMP0 = N0->getOperand(1);
25468 SDValue CMP1 = N1->getOperand(1);
25471 // The SETCCs should both refer to the same CMP.
25472 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25475 SDValue CMP00 = CMP0->getOperand(0);
25476 SDValue CMP01 = CMP0->getOperand(1);
25477 EVT VT = CMP00.getValueType();
25479 if (VT == MVT::f32 || VT == MVT::f64) {
25480 bool ExpectingFlags = false;
25481 // Check for any users that want flags:
25482 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25483 !ExpectingFlags && UI != UE; ++UI)
25484 switch (UI->getOpcode()) {
25489 ExpectingFlags = true;
25491 case ISD::CopyToReg:
25492 case ISD::SIGN_EXTEND:
25493 case ISD::ZERO_EXTEND:
25494 case ISD::ANY_EXTEND:
25498 if (!ExpectingFlags) {
25499 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25500 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25502 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25503 X86::CondCode tmp = cc0;
25508 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
25509 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25510 // FIXME: need symbolic constants for these magic numbers.
25511 // See X86ATTInstPrinter.cpp:printSSECC().
25512 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25513 if (Subtarget->hasAVX512()) {
25514 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25516 DAG.getConstant(x86cc, DL, MVT::i8));
25517 if (N->getValueType(0) != MVT::i1)
25518 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25522 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25523 CMP00.getValueType(), CMP00, CMP01,
25524 DAG.getConstant(x86cc, DL,
25527 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25528 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25530 if (is64BitFP && !Subtarget->is64Bit()) {
25531 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25532 // 64-bit integer, since that's not a legal type. Since
25533 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25534 // bits, but can do this little dance to extract the lowest 32 bits
25535 // and work with those going forward.
25536 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25538 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25539 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25540 Vector32, DAG.getIntPtrConstant(0, DL));
25544 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25545 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25546 DAG.getConstant(1, DL, IntVT));
25547 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25549 return OneBitOfTruth;
25557 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25558 /// so it can be folded inside ANDNP.
25559 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25560 EVT VT = N->getValueType(0);
25562 // Match direct AllOnes for 128 and 256-bit vectors
25563 if (ISD::isBuildVectorAllOnes(N))
25566 // Look through a bit convert.
25567 if (N->getOpcode() == ISD::BITCAST)
25568 N = N->getOperand(0).getNode();
25570 // Sometimes the operand may come from a insert_subvector building a 256-bit
25572 if (VT.is256BitVector() &&
25573 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25574 SDValue V1 = N->getOperand(0);
25575 SDValue V2 = N->getOperand(1);
25577 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25578 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25579 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25580 ISD::isBuildVectorAllOnes(V2.getNode()))
25587 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25588 // register. In most cases we actually compare or select YMM-sized registers
25589 // and mixing the two types creates horrible code. This method optimizes
25590 // some of the transition sequences.
25591 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25592 TargetLowering::DAGCombinerInfo &DCI,
25593 const X86Subtarget *Subtarget) {
25594 EVT VT = N->getValueType(0);
25595 if (!VT.is256BitVector())
25598 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25599 N->getOpcode() == ISD::ZERO_EXTEND ||
25600 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25602 SDValue Narrow = N->getOperand(0);
25603 EVT NarrowVT = Narrow->getValueType(0);
25604 if (!NarrowVT.is128BitVector())
25607 if (Narrow->getOpcode() != ISD::XOR &&
25608 Narrow->getOpcode() != ISD::AND &&
25609 Narrow->getOpcode() != ISD::OR)
25612 SDValue N0 = Narrow->getOperand(0);
25613 SDValue N1 = Narrow->getOperand(1);
25616 // The Left side has to be a trunc.
25617 if (N0.getOpcode() != ISD::TRUNCATE)
25620 // The type of the truncated inputs.
25621 EVT WideVT = N0->getOperand(0)->getValueType(0);
25625 // The right side has to be a 'trunc' or a constant vector.
25626 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25627 ConstantSDNode *RHSConstSplat = nullptr;
25628 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25629 RHSConstSplat = RHSBV->getConstantSplatNode();
25630 if (!RHSTrunc && !RHSConstSplat)
25633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25635 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25638 // Set N0 and N1 to hold the inputs to the new wide operation.
25639 N0 = N0->getOperand(0);
25640 if (RHSConstSplat) {
25641 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25642 SDValue(RHSConstSplat, 0));
25643 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25644 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25645 } else if (RHSTrunc) {
25646 N1 = N1->getOperand(0);
25649 // Generate the wide operation.
25650 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25651 unsigned Opcode = N->getOpcode();
25653 case ISD::ANY_EXTEND:
25655 case ISD::ZERO_EXTEND: {
25656 unsigned InBits = NarrowVT.getScalarSizeInBits();
25657 APInt Mask = APInt::getAllOnesValue(InBits);
25658 Mask = Mask.zext(VT.getScalarSizeInBits());
25659 return DAG.getNode(ISD::AND, DL, VT,
25660 Op, DAG.getConstant(Mask, DL, VT));
25662 case ISD::SIGN_EXTEND:
25663 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25664 Op, DAG.getValueType(NarrowVT));
25666 llvm_unreachable("Unexpected opcode");
25670 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25671 TargetLowering::DAGCombinerInfo &DCI,
25672 const X86Subtarget *Subtarget) {
25673 SDValue N0 = N->getOperand(0);
25674 SDValue N1 = N->getOperand(1);
25677 // A vector zext_in_reg may be represented as a shuffle,
25678 // feeding into a bitcast (this represents anyext) feeding into
25679 // an and with a mask.
25680 // We'd like to try to combine that into a shuffle with zero
25681 // plus a bitcast, removing the and.
25682 if (N0.getOpcode() != ISD::BITCAST ||
25683 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25686 // The other side of the AND should be a splat of 2^C, where C
25687 // is the number of bits in the source type.
25688 if (N1.getOpcode() == ISD::BITCAST)
25689 N1 = N1.getOperand(0);
25690 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25692 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25694 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25695 EVT SrcType = Shuffle->getValueType(0);
25697 // We expect a single-source shuffle
25698 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25701 unsigned SrcSize = SrcType.getScalarSizeInBits();
25703 APInt SplatValue, SplatUndef;
25704 unsigned SplatBitSize;
25706 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25707 SplatBitSize, HasAnyUndefs))
25710 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25711 // Make sure the splat matches the mask we expect
25712 if (SplatBitSize > ResSize ||
25713 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25716 // Make sure the input and output size make sense
25717 if (SrcSize >= ResSize || ResSize % SrcSize)
25720 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25721 // The number of u's between each two values depends on the ratio between
25722 // the source and dest type.
25723 unsigned ZextRatio = ResSize / SrcSize;
25724 bool IsZext = true;
25725 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25726 if (i % ZextRatio) {
25727 if (Shuffle->getMaskElt(i) > 0) {
25733 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25734 // Expected element number
25744 // Ok, perform the transformation - replace the shuffle with
25745 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25746 // (instead of undef) where the k elements come from the zero vector.
25747 SmallVector<int, 8> Mask;
25748 unsigned NumElems = SrcType.getVectorNumElements();
25749 for (unsigned i = 0; i < NumElems; ++i)
25751 Mask.push_back(NumElems);
25753 Mask.push_back(i / ZextRatio);
25755 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25756 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25757 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25760 /// If both input operands of a logic op are being cast from floating point
25761 /// types, try to convert this into a floating point logic node to avoid
25762 /// unnecessary moves from SSE to integer registers.
25763 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25764 const X86Subtarget *Subtarget) {
25765 unsigned FPOpcode = ISD::DELETED_NODE;
25766 if (N->getOpcode() == ISD::AND)
25767 FPOpcode = X86ISD::FAND;
25768 else if (N->getOpcode() == ISD::OR)
25769 FPOpcode = X86ISD::FOR;
25770 else if (N->getOpcode() == ISD::XOR)
25771 FPOpcode = X86ISD::FXOR;
25773 assert(FPOpcode != ISD::DELETED_NODE &&
25774 "Unexpected input node for FP logic conversion");
25776 EVT VT = N->getValueType(0);
25777 SDValue N0 = N->getOperand(0);
25778 SDValue N1 = N->getOperand(1);
25780 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25781 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25782 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25783 SDValue N00 = N0.getOperand(0);
25784 SDValue N10 = N1.getOperand(0);
25785 EVT N00Type = N00.getValueType();
25786 EVT N10Type = N10.getValueType();
25787 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25788 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25789 return DAG.getBitcast(VT, FPLogic);
25795 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25796 TargetLowering::DAGCombinerInfo &DCI,
25797 const X86Subtarget *Subtarget) {
25798 if (DCI.isBeforeLegalizeOps())
25801 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25804 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25807 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25810 EVT VT = N->getValueType(0);
25811 SDValue N0 = N->getOperand(0);
25812 SDValue N1 = N->getOperand(1);
25815 // Create BEXTR instructions
25816 // BEXTR is ((X >> imm) & (2**size-1))
25817 if (VT == MVT::i32 || VT == MVT::i64) {
25818 // Check for BEXTR.
25819 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25820 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25821 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25822 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25823 if (MaskNode && ShiftNode) {
25824 uint64_t Mask = MaskNode->getZExtValue();
25825 uint64_t Shift = ShiftNode->getZExtValue();
25826 if (isMask_64(Mask)) {
25827 uint64_t MaskSize = countPopulation(Mask);
25828 if (Shift + MaskSize <= VT.getSizeInBits())
25829 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25830 DAG.getConstant(Shift | (MaskSize << 8), DL,
25839 // Want to form ANDNP nodes:
25840 // 1) In the hopes of then easily combining them with OR and AND nodes
25841 // to form PBLEND/PSIGN.
25842 // 2) To match ANDN packed intrinsics
25843 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25846 // Check LHS for vnot
25847 if (N0.getOpcode() == ISD::XOR &&
25848 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25849 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25850 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25852 // Check RHS for vnot
25853 if (N1.getOpcode() == ISD::XOR &&
25854 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25855 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25856 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25861 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25862 TargetLowering::DAGCombinerInfo &DCI,
25863 const X86Subtarget *Subtarget) {
25864 if (DCI.isBeforeLegalizeOps())
25867 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25870 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25873 SDValue N0 = N->getOperand(0);
25874 SDValue N1 = N->getOperand(1);
25875 EVT VT = N->getValueType(0);
25877 // look for psign/blend
25878 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25879 if (!Subtarget->hasSSSE3() ||
25880 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25883 // Canonicalize pandn to RHS
25884 if (N0.getOpcode() == X86ISD::ANDNP)
25886 // or (and (m, y), (pandn m, x))
25887 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25888 SDValue Mask = N1.getOperand(0);
25889 SDValue X = N1.getOperand(1);
25891 if (N0.getOperand(0) == Mask)
25892 Y = N0.getOperand(1);
25893 if (N0.getOperand(1) == Mask)
25894 Y = N0.getOperand(0);
25896 // Check to see if the mask appeared in both the AND and ANDNP and
25900 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25901 // Look through mask bitcast.
25902 if (Mask.getOpcode() == ISD::BITCAST)
25903 Mask = Mask.getOperand(0);
25904 if (X.getOpcode() == ISD::BITCAST)
25905 X = X.getOperand(0);
25906 if (Y.getOpcode() == ISD::BITCAST)
25907 Y = Y.getOperand(0);
25909 EVT MaskVT = Mask.getValueType();
25911 // Validate that the Mask operand is a vector sra node.
25912 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25913 // there is no psrai.b
25914 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25915 unsigned SraAmt = ~0;
25916 if (Mask.getOpcode() == ISD::SRA) {
25917 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25918 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25919 SraAmt = AmtConst->getZExtValue();
25920 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25921 SDValue SraC = Mask.getOperand(1);
25922 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25924 if ((SraAmt + 1) != EltBits)
25929 // Now we know we at least have a plendvb with the mask val. See if
25930 // we can form a psignb/w/d.
25931 // psign = x.type == y.type == mask.type && y = sub(0, x);
25932 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25933 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25934 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25935 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25936 "Unsupported VT for PSIGN");
25937 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25938 return DAG.getBitcast(VT, Mask);
25940 // PBLENDVB only available on SSE 4.1
25941 if (!Subtarget->hasSSE41())
25944 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25946 X = DAG.getBitcast(BlendVT, X);
25947 Y = DAG.getBitcast(BlendVT, Y);
25948 Mask = DAG.getBitcast(BlendVT, Mask);
25949 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25950 return DAG.getBitcast(VT, Mask);
25954 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25957 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25958 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25960 // SHLD/SHRD instructions have lower register pressure, but on some
25961 // platforms they have higher latency than the equivalent
25962 // series of shifts/or that would otherwise be generated.
25963 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25964 // have higher latencies and we are not optimizing for size.
25965 if (!OptForSize && Subtarget->isSHLDSlow())
25968 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25970 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25972 if (!N0.hasOneUse() || !N1.hasOneUse())
25975 SDValue ShAmt0 = N0.getOperand(1);
25976 if (ShAmt0.getValueType() != MVT::i8)
25978 SDValue ShAmt1 = N1.getOperand(1);
25979 if (ShAmt1.getValueType() != MVT::i8)
25981 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25982 ShAmt0 = ShAmt0.getOperand(0);
25983 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25984 ShAmt1 = ShAmt1.getOperand(0);
25987 unsigned Opc = X86ISD::SHLD;
25988 SDValue Op0 = N0.getOperand(0);
25989 SDValue Op1 = N1.getOperand(0);
25990 if (ShAmt0.getOpcode() == ISD::SUB) {
25991 Opc = X86ISD::SHRD;
25992 std::swap(Op0, Op1);
25993 std::swap(ShAmt0, ShAmt1);
25996 unsigned Bits = VT.getSizeInBits();
25997 if (ShAmt1.getOpcode() == ISD::SUB) {
25998 SDValue Sum = ShAmt1.getOperand(0);
25999 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
26000 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
26001 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
26002 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
26003 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
26004 return DAG.getNode(Opc, DL, VT,
26006 DAG.getNode(ISD::TRUNCATE, DL,
26009 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
26010 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
26012 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
26013 return DAG.getNode(Opc, DL, VT,
26014 N0.getOperand(0), N1.getOperand(0),
26015 DAG.getNode(ISD::TRUNCATE, DL,
26022 // Generate NEG and CMOV for integer abs.
26023 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
26024 EVT VT = N->getValueType(0);
26026 // Since X86 does not have CMOV for 8-bit integer, we don't convert
26027 // 8-bit integer abs to NEG and CMOV.
26028 if (VT.isInteger() && VT.getSizeInBits() == 8)
26031 SDValue N0 = N->getOperand(0);
26032 SDValue N1 = N->getOperand(1);
26035 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
26036 // and change it to SUB and CMOV.
26037 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
26038 N0.getOpcode() == ISD::ADD &&
26039 N0.getOperand(1) == N1 &&
26040 N1.getOpcode() == ISD::SRA &&
26041 N1.getOperand(0) == N0.getOperand(0))
26042 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
26043 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
26044 // Generate SUB & CMOV.
26045 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26046 DAG.getConstant(0, DL, VT), N0.getOperand(0));
26048 SDValue Ops[] = { N0.getOperand(0), Neg,
26049 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
26050 SDValue(Neg.getNode(), 1) };
26051 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
26056 // Try to turn tests against the signbit in the form of:
26057 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
26060 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
26061 // This is only worth doing if the output type is i8.
26062 if (N->getValueType(0) != MVT::i8)
26065 SDValue N0 = N->getOperand(0);
26066 SDValue N1 = N->getOperand(1);
26068 // We should be performing an xor against a truncated shift.
26069 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
26072 // Make sure we are performing an xor against one.
26073 if (!isOneConstant(N1))
26076 // SetCC on x86 zero extends so only act on this if it's a logical shift.
26077 SDValue Shift = N0.getOperand(0);
26078 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
26081 // Make sure we are truncating from one of i16, i32 or i64.
26082 EVT ShiftTy = Shift.getValueType();
26083 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26086 // Make sure the shift amount extracts the sign bit.
26087 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26088 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26091 // Create a greater-than comparison against -1.
26092 // N.B. Using SETGE against 0 works but we want a canonical looking
26093 // comparison, using SETGT matches up with what TranslateX86CC.
26095 SDValue ShiftOp = Shift.getOperand(0);
26096 EVT ShiftOpTy = ShiftOp.getValueType();
26097 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26098 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26102 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26103 TargetLowering::DAGCombinerInfo &DCI,
26104 const X86Subtarget *Subtarget) {
26105 if (DCI.isBeforeLegalizeOps())
26108 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26111 if (Subtarget->hasCMov())
26112 if (SDValue RV = performIntegerAbsCombine(N, DAG))
26115 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26121 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26122 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26123 /// X86ISD::AVG instruction.
26124 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26125 const X86Subtarget *Subtarget, SDLoc DL) {
26126 if (!VT.isVector() || !VT.isSimple())
26128 EVT InVT = In.getValueType();
26129 unsigned NumElems = VT.getVectorNumElements();
26131 EVT ScalarVT = VT.getVectorElementType();
26132 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26133 isPowerOf2_32(NumElems)))
26136 // InScalarVT is the intermediate type in AVG pattern and it should be greater
26137 // than the original input type (i8/i16).
26138 EVT InScalarVT = InVT.getVectorElementType();
26139 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26142 if (Subtarget->hasAVX512()) {
26143 if (VT.getSizeInBits() > 512)
26145 } else if (Subtarget->hasAVX2()) {
26146 if (VT.getSizeInBits() > 256)
26149 if (VT.getSizeInBits() > 128)
26153 // Detect the following pattern:
26155 // %1 = zext <N x i8> %a to <N x i32>
26156 // %2 = zext <N x i8> %b to <N x i32>
26157 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26158 // %4 = add nuw nsw <N x i32> %3, %2
26159 // %5 = lshr <N x i32> %N, <i32 1 x N>
26160 // %6 = trunc <N x i32> %5 to <N x i8>
26162 // In AVX512, the last instruction can also be a trunc store.
26164 if (In.getOpcode() != ISD::SRL)
26167 // A lambda checking the given SDValue is a constant vector and each element
26168 // is in the range [Min, Max].
26169 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26170 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26171 if (!BV || !BV->isConstant())
26173 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26174 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26177 uint64_t Val = C->getZExtValue();
26178 if (Val < Min || Val > Max)
26184 // Check if each element of the vector is left-shifted by one.
26185 auto LHS = In.getOperand(0);
26186 auto RHS = In.getOperand(1);
26187 if (!IsConstVectorInRange(RHS, 1, 1))
26189 if (LHS.getOpcode() != ISD::ADD)
26192 // Detect a pattern of a + b + 1 where the order doesn't matter.
26193 SDValue Operands[3];
26194 Operands[0] = LHS.getOperand(0);
26195 Operands[1] = LHS.getOperand(1);
26197 // Take care of the case when one of the operands is a constant vector whose
26198 // element is in the range [1, 256].
26199 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26200 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26201 Operands[0].getOperand(0).getValueType() == VT) {
26202 // The pattern is detected. Subtract one from the constant vector, then
26203 // demote it and emit X86ISD::AVG instruction.
26204 SDValue One = DAG.getConstant(1, DL, InScalarVT);
26205 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26206 SmallVector<SDValue, 8>(NumElems, One));
26207 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26208 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26209 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26213 if (Operands[0].getOpcode() == ISD::ADD)
26214 std::swap(Operands[0], Operands[1]);
26215 else if (Operands[1].getOpcode() != ISD::ADD)
26217 Operands[2] = Operands[1].getOperand(0);
26218 Operands[1] = Operands[1].getOperand(1);
26220 // Now we have three operands of two additions. Check that one of them is a
26221 // constant vector with ones, and the other two are promoted from i8/i16.
26222 for (int i = 0; i < 3; ++i) {
26223 if (!IsConstVectorInRange(Operands[i], 1, 1))
26225 std::swap(Operands[i], Operands[2]);
26227 // Check if Operands[0] and Operands[1] are results of type promotion.
26228 for (int j = 0; j < 2; ++j)
26229 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26230 Operands[j].getOperand(0).getValueType() != VT)
26233 // The pattern is detected, emit X86ISD::AVG instruction.
26234 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26235 Operands[1].getOperand(0));
26241 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26242 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26243 TargetLowering::DAGCombinerInfo &DCI,
26244 const X86Subtarget *Subtarget) {
26245 LoadSDNode *Ld = cast<LoadSDNode>(N);
26246 EVT RegVT = Ld->getValueType(0);
26247 EVT MemVT = Ld->getMemoryVT();
26249 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26251 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26252 // into two 16-byte operations.
26253 ISD::LoadExtType Ext = Ld->getExtensionType();
26255 unsigned AddressSpace = Ld->getAddressSpace();
26256 unsigned Alignment = Ld->getAlignment();
26257 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26258 Ext == ISD::NON_EXTLOAD &&
26259 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26260 AddressSpace, Alignment, &Fast) && !Fast) {
26261 unsigned NumElems = RegVT.getVectorNumElements();
26265 SDValue Ptr = Ld->getBasePtr();
26266 SDValue Increment =
26267 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26269 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26271 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26272 Ld->getPointerInfo(), Ld->isVolatile(),
26273 Ld->isNonTemporal(), Ld->isInvariant(),
26275 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26276 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26277 Ld->getPointerInfo(), Ld->isVolatile(),
26278 Ld->isNonTemporal(), Ld->isInvariant(),
26279 std::min(16U, Alignment));
26280 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26282 Load2.getValue(1));
26284 SDValue NewVec = DAG.getUNDEF(RegVT);
26285 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26286 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26287 return DCI.CombineTo(N, NewVec, TF, true);
26293 /// PerformMLOADCombine - Resolve extending loads
26294 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26295 TargetLowering::DAGCombinerInfo &DCI,
26296 const X86Subtarget *Subtarget) {
26297 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26298 if (Mld->getExtensionType() != ISD::SEXTLOAD)
26301 EVT VT = Mld->getValueType(0);
26302 unsigned NumElems = VT.getVectorNumElements();
26303 EVT LdVT = Mld->getMemoryVT();
26306 assert(LdVT != VT && "Cannot extend to the same type");
26307 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26308 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26309 // From, To sizes and ElemCount must be pow of two
26310 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26311 "Unexpected size for extending masked load");
26313 unsigned SizeRatio = ToSz / FromSz;
26314 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26316 // Create a type on which we perform the shuffle
26317 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26318 LdVT.getScalarType(), NumElems*SizeRatio);
26319 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26321 // Convert Src0 value
26322 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26323 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26324 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26325 for (unsigned i = 0; i != NumElems; ++i)
26326 ShuffleVec[i] = i * SizeRatio;
26328 // Can't shuffle using an illegal type.
26329 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26330 "WideVecVT should be legal");
26331 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26332 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26334 // Prepare the new mask
26336 SDValue Mask = Mld->getMask();
26337 if (Mask.getValueType() == VT) {
26338 // Mask and original value have the same type
26339 NewMask = DAG.getBitcast(WideVecVT, Mask);
26340 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26341 for (unsigned i = 0; i != NumElems; ++i)
26342 ShuffleVec[i] = i * SizeRatio;
26343 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26344 ShuffleVec[i] = NumElems * SizeRatio;
26345 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26346 DAG.getConstant(0, dl, WideVecVT),
26350 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26351 unsigned WidenNumElts = NumElems*SizeRatio;
26352 unsigned MaskNumElts = VT.getVectorNumElements();
26353 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26356 unsigned NumConcat = WidenNumElts / MaskNumElts;
26357 SmallVector<SDValue, 16> Ops(NumConcat);
26358 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26360 for (unsigned i = 1; i != NumConcat; ++i)
26363 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26366 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26367 Mld->getBasePtr(), NewMask, WideSrc0,
26368 Mld->getMemoryVT(), Mld->getMemOperand(),
26370 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26371 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26373 /// PerformMSTORECombine - Resolve truncating stores
26374 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26375 const X86Subtarget *Subtarget) {
26376 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26377 if (!Mst->isTruncatingStore())
26380 EVT VT = Mst->getValue().getValueType();
26381 unsigned NumElems = VT.getVectorNumElements();
26382 EVT StVT = Mst->getMemoryVT();
26385 assert(StVT != VT && "Cannot truncate to the same type");
26386 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26387 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26389 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26391 // The truncating store is legal in some cases. For example
26392 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26393 // are designated for truncate store.
26394 // In this case we don't need any further transformations.
26395 if (TLI.isTruncStoreLegal(VT, StVT))
26398 // From, To sizes and ElemCount must be pow of two
26399 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26400 "Unexpected size for truncating masked store");
26401 // We are going to use the original vector elt for storing.
26402 // Accumulated smaller vector elements must be a multiple of the store size.
26403 assert (((NumElems * FromSz) % ToSz) == 0 &&
26404 "Unexpected ratio for truncating masked store");
26406 unsigned SizeRatio = FromSz / ToSz;
26407 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26409 // Create a type on which we perform the shuffle
26410 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26411 StVT.getScalarType(), NumElems*SizeRatio);
26413 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26415 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26416 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26417 for (unsigned i = 0; i != NumElems; ++i)
26418 ShuffleVec[i] = i * SizeRatio;
26420 // Can't shuffle using an illegal type.
26421 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26422 "WideVecVT should be legal");
26424 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26425 DAG.getUNDEF(WideVecVT),
26429 SDValue Mask = Mst->getMask();
26430 if (Mask.getValueType() == VT) {
26431 // Mask and original value have the same type
26432 NewMask = DAG.getBitcast(WideVecVT, Mask);
26433 for (unsigned i = 0; i != NumElems; ++i)
26434 ShuffleVec[i] = i * SizeRatio;
26435 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26436 ShuffleVec[i] = NumElems*SizeRatio;
26437 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26438 DAG.getConstant(0, dl, WideVecVT),
26442 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26443 unsigned WidenNumElts = NumElems*SizeRatio;
26444 unsigned MaskNumElts = VT.getVectorNumElements();
26445 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26448 unsigned NumConcat = WidenNumElts / MaskNumElts;
26449 SmallVector<SDValue, 16> Ops(NumConcat);
26450 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26452 for (unsigned i = 1; i != NumConcat; ++i)
26455 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26458 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26459 Mst->getBasePtr(), NewMask, StVT,
26460 Mst->getMemOperand(), false);
26462 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26463 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26464 const X86Subtarget *Subtarget) {
26465 StoreSDNode *St = cast<StoreSDNode>(N);
26466 EVT VT = St->getValue().getValueType();
26467 EVT StVT = St->getMemoryVT();
26469 SDValue StoredVal = St->getOperand(1);
26470 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26472 // If we are saving a concatenation of two XMM registers and 32-byte stores
26473 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26475 unsigned AddressSpace = St->getAddressSpace();
26476 unsigned Alignment = St->getAlignment();
26477 if (VT.is256BitVector() && StVT == VT &&
26478 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26479 AddressSpace, Alignment, &Fast) && !Fast) {
26480 unsigned NumElems = VT.getVectorNumElements();
26484 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26485 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26488 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26489 SDValue Ptr0 = St->getBasePtr();
26490 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26492 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26493 St->getPointerInfo(), St->isVolatile(),
26494 St->isNonTemporal(), Alignment);
26495 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26496 St->getPointerInfo(), St->isVolatile(),
26497 St->isNonTemporal(),
26498 std::min(16U, Alignment));
26499 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26502 // Optimize trunc store (of multiple scalars) to shuffle and store.
26503 // First, pack all of the elements in one place. Next, store to memory
26504 // in fewer chunks.
26505 if (St->isTruncatingStore() && VT.isVector()) {
26506 // Check if we can detect an AVG pattern from the truncation. If yes,
26507 // replace the trunc store by a normal store with the result of X86ISD::AVG
26510 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26512 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26513 St->getPointerInfo(), St->isVolatile(),
26514 St->isNonTemporal(), St->getAlignment());
26516 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26517 unsigned NumElems = VT.getVectorNumElements();
26518 assert(StVT != VT && "Cannot truncate to the same type");
26519 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26520 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26522 // The truncating store is legal in some cases. For example
26523 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26524 // are designated for truncate store.
26525 // In this case we don't need any further transformations.
26526 if (TLI.isTruncStoreLegal(VT, StVT))
26529 // From, To sizes and ElemCount must be pow of two
26530 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26531 // We are going to use the original vector elt for storing.
26532 // Accumulated smaller vector elements must be a multiple of the store size.
26533 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26535 unsigned SizeRatio = FromSz / ToSz;
26537 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26539 // Create a type on which we perform the shuffle
26540 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26541 StVT.getScalarType(), NumElems*SizeRatio);
26543 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26545 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26546 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26547 for (unsigned i = 0; i != NumElems; ++i)
26548 ShuffleVec[i] = i * SizeRatio;
26550 // Can't shuffle using an illegal type.
26551 if (!TLI.isTypeLegal(WideVecVT))
26554 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26555 DAG.getUNDEF(WideVecVT),
26557 // At this point all of the data is stored at the bottom of the
26558 // register. We now need to save it to mem.
26560 // Find the largest store unit
26561 MVT StoreType = MVT::i8;
26562 for (MVT Tp : MVT::integer_valuetypes()) {
26563 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26567 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26568 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26569 (64 <= NumElems * ToSz))
26570 StoreType = MVT::f64;
26572 // Bitcast the original vector into a vector of store-size units
26573 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26574 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26575 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26576 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26577 SmallVector<SDValue, 8> Chains;
26578 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26579 TLI.getPointerTy(DAG.getDataLayout()));
26580 SDValue Ptr = St->getBasePtr();
26582 // Perform one or more big stores into memory.
26583 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26584 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26585 StoreType, ShuffWide,
26586 DAG.getIntPtrConstant(i, dl));
26587 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26588 St->getPointerInfo(), St->isVolatile(),
26589 St->isNonTemporal(), St->getAlignment());
26590 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26591 Chains.push_back(Ch);
26594 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26597 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26598 // the FP state in cases where an emms may be missing.
26599 // A preferable solution to the general problem is to figure out the right
26600 // places to insert EMMS. This qualifies as a quick hack.
26602 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26603 if (VT.getSizeInBits() != 64)
26606 const Function *F = DAG.getMachineFunction().getFunction();
26607 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26609 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26610 if ((VT.isVector() ||
26611 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26612 isa<LoadSDNode>(St->getValue()) &&
26613 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26614 St->getChain().hasOneUse() && !St->isVolatile()) {
26615 SDNode* LdVal = St->getValue().getNode();
26616 LoadSDNode *Ld = nullptr;
26617 int TokenFactorIndex = -1;
26618 SmallVector<SDValue, 8> Ops;
26619 SDNode* ChainVal = St->getChain().getNode();
26620 // Must be a store of a load. We currently handle two cases: the load
26621 // is a direct child, and it's under an intervening TokenFactor. It is
26622 // possible to dig deeper under nested TokenFactors.
26623 if (ChainVal == LdVal)
26624 Ld = cast<LoadSDNode>(St->getChain());
26625 else if (St->getValue().hasOneUse() &&
26626 ChainVal->getOpcode() == ISD::TokenFactor) {
26627 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26628 if (ChainVal->getOperand(i).getNode() == LdVal) {
26629 TokenFactorIndex = i;
26630 Ld = cast<LoadSDNode>(St->getValue());
26632 Ops.push_back(ChainVal->getOperand(i));
26636 if (!Ld || !ISD::isNormalLoad(Ld))
26639 // If this is not the MMX case, i.e. we are just turning i64 load/store
26640 // into f64 load/store, avoid the transformation if there are multiple
26641 // uses of the loaded value.
26642 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26647 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26648 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26650 if (Subtarget->is64Bit() || F64IsLegal) {
26651 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26652 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26653 Ld->getPointerInfo(), Ld->isVolatile(),
26654 Ld->isNonTemporal(), Ld->isInvariant(),
26655 Ld->getAlignment());
26656 SDValue NewChain = NewLd.getValue(1);
26657 if (TokenFactorIndex != -1) {
26658 Ops.push_back(NewChain);
26659 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26661 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26662 St->getPointerInfo(),
26663 St->isVolatile(), St->isNonTemporal(),
26664 St->getAlignment());
26667 // Otherwise, lower to two pairs of 32-bit loads / stores.
26668 SDValue LoAddr = Ld->getBasePtr();
26669 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26670 DAG.getConstant(4, LdDL, MVT::i32));
26672 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26673 Ld->getPointerInfo(),
26674 Ld->isVolatile(), Ld->isNonTemporal(),
26675 Ld->isInvariant(), Ld->getAlignment());
26676 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26677 Ld->getPointerInfo().getWithOffset(4),
26678 Ld->isVolatile(), Ld->isNonTemporal(),
26680 MinAlign(Ld->getAlignment(), 4));
26682 SDValue NewChain = LoLd.getValue(1);
26683 if (TokenFactorIndex != -1) {
26684 Ops.push_back(LoLd);
26685 Ops.push_back(HiLd);
26686 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26689 LoAddr = St->getBasePtr();
26690 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26691 DAG.getConstant(4, StDL, MVT::i32));
26693 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26694 St->getPointerInfo(),
26695 St->isVolatile(), St->isNonTemporal(),
26696 St->getAlignment());
26697 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26698 St->getPointerInfo().getWithOffset(4),
26700 St->isNonTemporal(),
26701 MinAlign(St->getAlignment(), 4));
26702 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26705 // This is similar to the above case, but here we handle a scalar 64-bit
26706 // integer store that is extracted from a vector on a 32-bit target.
26707 // If we have SSE2, then we can treat it like a floating-point double
26708 // to get past legalization. The execution dependencies fixup pass will
26709 // choose the optimal machine instruction for the store if this really is
26710 // an integer or v2f32 rather than an f64.
26711 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26712 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26713 SDValue OldExtract = St->getOperand(1);
26714 SDValue ExtOp0 = OldExtract.getOperand(0);
26715 unsigned VecSize = ExtOp0.getValueSizeInBits();
26716 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26717 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26718 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26719 BitCast, OldExtract.getOperand(1));
26720 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26721 St->getPointerInfo(), St->isVolatile(),
26722 St->isNonTemporal(), St->getAlignment());
26728 /// Return 'true' if this vector operation is "horizontal"
26729 /// and return the operands for the horizontal operation in LHS and RHS. A
26730 /// horizontal operation performs the binary operation on successive elements
26731 /// of its first operand, then on successive elements of its second operand,
26732 /// returning the resulting values in a vector. For example, if
26733 /// A = < float a0, float a1, float a2, float a3 >
26735 /// B = < float b0, float b1, float b2, float b3 >
26736 /// then the result of doing a horizontal operation on A and B is
26737 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26738 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26739 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26740 /// set to A, RHS to B, and the routine returns 'true'.
26741 /// Note that the binary operation should have the property that if one of the
26742 /// operands is UNDEF then the result is UNDEF.
26743 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26744 // Look for the following pattern: if
26745 // A = < float a0, float a1, float a2, float a3 >
26746 // B = < float b0, float b1, float b2, float b3 >
26748 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26749 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26750 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26751 // which is A horizontal-op B.
26753 // At least one of the operands should be a vector shuffle.
26754 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26755 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26758 MVT VT = LHS.getSimpleValueType();
26760 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26761 "Unsupported vector type for horizontal add/sub");
26763 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26764 // operate independently on 128-bit lanes.
26765 unsigned NumElts = VT.getVectorNumElements();
26766 unsigned NumLanes = VT.getSizeInBits()/128;
26767 unsigned NumLaneElts = NumElts / NumLanes;
26768 assert((NumLaneElts % 2 == 0) &&
26769 "Vector type should have an even number of elements in each lane");
26770 unsigned HalfLaneElts = NumLaneElts/2;
26772 // View LHS in the form
26773 // LHS = VECTOR_SHUFFLE A, B, LMask
26774 // If LHS is not a shuffle then pretend it is the shuffle
26775 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26776 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26779 SmallVector<int, 16> LMask(NumElts);
26780 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26781 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26782 A = LHS.getOperand(0);
26783 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26784 B = LHS.getOperand(1);
26785 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26786 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26788 if (LHS.getOpcode() != ISD::UNDEF)
26790 for (unsigned i = 0; i != NumElts; ++i)
26794 // Likewise, view RHS in the form
26795 // RHS = VECTOR_SHUFFLE C, D, RMask
26797 SmallVector<int, 16> RMask(NumElts);
26798 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26799 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26800 C = RHS.getOperand(0);
26801 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26802 D = RHS.getOperand(1);
26803 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26804 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26806 if (RHS.getOpcode() != ISD::UNDEF)
26808 for (unsigned i = 0; i != NumElts; ++i)
26812 // Check that the shuffles are both shuffling the same vectors.
26813 if (!(A == C && B == D) && !(A == D && B == C))
26816 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26817 if (!A.getNode() && !B.getNode())
26820 // If A and B occur in reverse order in RHS, then "swap" them (which means
26821 // rewriting the mask).
26823 ShuffleVectorSDNode::commuteMask(RMask);
26825 // At this point LHS and RHS are equivalent to
26826 // LHS = VECTOR_SHUFFLE A, B, LMask
26827 // RHS = VECTOR_SHUFFLE A, B, RMask
26828 // Check that the masks correspond to performing a horizontal operation.
26829 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26830 for (unsigned i = 0; i != NumLaneElts; ++i) {
26831 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26833 // Ignore any UNDEF components.
26834 if (LIdx < 0 || RIdx < 0 ||
26835 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26836 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26839 // Check that successive elements are being operated on. If not, this is
26840 // not a horizontal operation.
26841 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26842 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26843 if (!(LIdx == Index && RIdx == Index + 1) &&
26844 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26849 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26850 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26854 /// Do target-specific dag combines on floating point adds.
26855 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26856 const X86Subtarget *Subtarget) {
26857 EVT VT = N->getValueType(0);
26858 SDValue LHS = N->getOperand(0);
26859 SDValue RHS = N->getOperand(1);
26861 // Try to synthesize horizontal adds from adds of shuffles.
26862 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26863 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26864 isHorizontalBinOp(LHS, RHS, true))
26865 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26869 /// Do target-specific dag combines on floating point subs.
26870 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26871 const X86Subtarget *Subtarget) {
26872 EVT VT = N->getValueType(0);
26873 SDValue LHS = N->getOperand(0);
26874 SDValue RHS = N->getOperand(1);
26876 // Try to synthesize horizontal subs from subs of shuffles.
26877 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26878 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26879 isHorizontalBinOp(LHS, RHS, false))
26880 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26884 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26886 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26887 SmallVector<SDValue, 8> &Regs) {
26888 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26889 Regs[0].getValueType() == MVT::v2i64));
26890 EVT OutVT = N->getValueType(0);
26891 EVT OutSVT = OutVT.getVectorElementType();
26892 EVT InVT = Regs[0].getValueType();
26893 EVT InSVT = InVT.getVectorElementType();
26896 // First, use mask to unset all bits that won't appear in the result.
26897 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26898 "OutSVT can only be either i8 or i16.");
26900 DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26901 SDValue MaskVec = DAG.getNode(
26902 ISD::BUILD_VECTOR, DL, InVT,
26903 SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26904 for (auto &Reg : Regs)
26905 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26907 MVT UnpackedVT, PackedVT;
26908 if (OutSVT == MVT::i8) {
26909 UnpackedVT = MVT::v8i16;
26910 PackedVT = MVT::v16i8;
26912 UnpackedVT = MVT::v4i32;
26913 PackedVT = MVT::v8i16;
26916 // In each iteration, truncate the type by a half size.
26917 auto RegNum = Regs.size();
26918 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26919 j < e; j *= 2, RegNum /= 2) {
26920 for (unsigned i = 0; i < RegNum; i++)
26921 Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26922 for (unsigned i = 0; i < RegNum / 2; i++)
26923 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26927 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26928 // then extract a subvector as the result since v8i8 is not a legal type.
26929 if (OutVT == MVT::v8i8) {
26930 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26931 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26932 DAG.getIntPtrConstant(0, DL));
26934 } else if (RegNum > 1) {
26935 Regs.resize(RegNum);
26936 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26941 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26943 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26944 SmallVector<SDValue, 8> &Regs) {
26945 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26946 EVT OutVT = N->getValueType(0);
26949 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26950 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26951 for (auto &Reg : Regs) {
26952 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26953 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26956 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26957 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26960 if (Regs.size() > 2) {
26961 Regs.resize(Regs.size() / 2);
26962 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26967 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26968 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26969 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26970 /// element that is extracted from a vector and then truncated, and it is
26971 /// diffcult to do this optimization based on them.
26972 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26973 const X86Subtarget *Subtarget) {
26974 EVT OutVT = N->getValueType(0);
26975 if (!OutVT.isVector())
26978 SDValue In = N->getOperand(0);
26979 if (!In.getValueType().isSimple())
26982 EVT InVT = In.getValueType();
26983 unsigned NumElems = OutVT.getVectorNumElements();
26985 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26986 // SSE2, and we need to take care of it specially.
26987 // AVX512 provides vpmovdb.
26988 if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26991 EVT OutSVT = OutVT.getVectorElementType();
26992 EVT InSVT = InVT.getVectorElementType();
26993 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26994 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26998 // SSSE3's pshufb results in less instructions in the cases below.
26999 if (Subtarget->hasSSSE3() && NumElems == 8 &&
27000 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
27001 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
27006 // Split a long vector into vectors of legal type.
27007 unsigned RegNum = InVT.getSizeInBits() / 128;
27008 SmallVector<SDValue, 8> SubVec(RegNum);
27009 if (InSVT == MVT::i32) {
27010 for (unsigned i = 0; i < RegNum; i++)
27011 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
27012 DAG.getIntPtrConstant(i * 4, DL));
27014 for (unsigned i = 0; i < RegNum; i++)
27015 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
27016 DAG.getIntPtrConstant(i * 2, DL));
27019 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
27020 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
27021 // truncate 2 x v4i32 to v8i16.
27022 if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
27023 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
27024 else if (InSVT == MVT::i32)
27025 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
27030 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
27031 const X86Subtarget *Subtarget) {
27032 // Try to detect AVG pattern first.
27033 SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
27034 Subtarget, SDLoc(N));
27038 return combineVectorTruncation(N, DAG, Subtarget);
27041 /// Do target-specific dag combines on floating point negations.
27042 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
27043 const X86Subtarget *Subtarget) {
27044 EVT VT = N->getValueType(0);
27045 EVT SVT = VT.getScalarType();
27046 SDValue Arg = N->getOperand(0);
27049 // Let legalize expand this if it isn't a legal type yet.
27050 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27053 // If we're negating a FMUL node on a target with FMA, then we can avoid the
27054 // use of a constant by performing (-0 - A*B) instead.
27055 // FIXME: Check rounding control flags as well once it becomes available.
27056 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
27057 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
27058 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
27059 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27060 Arg.getOperand(1), Zero);
27063 // If we're negating a FMA node, then we can adjust the
27064 // instruction to include the extra negation.
27065 if (Arg.hasOneUse()) {
27066 switch (Arg.getOpcode()) {
27067 case X86ISD::FMADD:
27068 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
27069 Arg.getOperand(1), Arg.getOperand(2));
27070 case X86ISD::FMSUB:
27071 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
27072 Arg.getOperand(1), Arg.getOperand(2));
27073 case X86ISD::FNMADD:
27074 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
27075 Arg.getOperand(1), Arg.getOperand(2));
27076 case X86ISD::FNMSUB:
27077 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
27078 Arg.getOperand(1), Arg.getOperand(2));
27084 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
27085 const X86Subtarget *Subtarget) {
27086 EVT VT = N->getValueType(0);
27087 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27088 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27089 // These logic operations may be executed in the integer domain.
27091 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27092 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27094 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27095 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27096 unsigned IntOpcode = 0;
27097 switch (N->getOpcode()) {
27098 default: llvm_unreachable("Unexpected FP logic op");
27099 case X86ISD::FOR: IntOpcode = ISD::OR; break;
27100 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27101 case X86ISD::FAND: IntOpcode = ISD::AND; break;
27102 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27104 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27105 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27109 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27110 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27111 const X86Subtarget *Subtarget) {
27112 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27114 // F[X]OR(0.0, x) -> x
27115 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27116 if (C->getValueAPF().isPosZero())
27117 return N->getOperand(1);
27119 // F[X]OR(x, 0.0) -> x
27120 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27121 if (C->getValueAPF().isPosZero())
27122 return N->getOperand(0);
27124 return lowerX86FPLogicOp(N, DAG, Subtarget);
27127 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27128 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27129 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27131 // Only perform optimizations if UnsafeMath is used.
27132 if (!DAG.getTarget().Options.UnsafeFPMath)
27135 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27136 // into FMINC and FMAXC, which are Commutative operations.
27137 unsigned NewOp = 0;
27138 switch (N->getOpcode()) {
27139 default: llvm_unreachable("unknown opcode");
27140 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
27141 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
27144 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27145 N->getOperand(0), N->getOperand(1));
27148 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27149 const X86Subtarget *Subtarget) {
27150 if (Subtarget->useSoftFloat())
27153 // TODO: Check for global or instruction-level "nnan". In that case, we
27154 // should be able to lower to FMAX/FMIN alone.
27155 // TODO: If an operand is already known to be a NaN or not a NaN, this
27156 // should be an optional swap and FMAX/FMIN.
27158 EVT VT = N->getValueType(0);
27159 if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27160 (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27161 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27164 // This takes at least 3 instructions, so favor a library call when operating
27165 // on a scalar and minimizing code size.
27166 if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27169 SDValue Op0 = N->getOperand(0);
27170 SDValue Op1 = N->getOperand(1);
27172 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27173 DAG.getDataLayout(), *DAG.getContext(), VT);
27175 // There are 4 possibilities involving NaN inputs, and these are the required
27179 // ----------------
27180 // Num | Max | Op0 |
27181 // Op0 ----------------
27182 // NaN | Op1 | NaN |
27183 // ----------------
27185 // The SSE FP max/min instructions were not designed for this case, but rather
27187 // Min = Op1 < Op0 ? Op1 : Op0
27188 // Max = Op1 > Op0 ? Op1 : Op0
27190 // So they always return Op0 if either input is a NaN. However, we can still
27191 // use those instructions for fmaxnum by selecting away a NaN input.
27193 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27194 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27195 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27196 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27198 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27199 // are NaN, the NaN value of Op1 is the result.
27200 auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27201 return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27204 /// Do target-specific dag combines on X86ISD::FAND nodes.
27205 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27206 const X86Subtarget *Subtarget) {
27207 // FAND(0.0, x) -> 0.0
27208 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27209 if (C->getValueAPF().isPosZero())
27210 return N->getOperand(0);
27212 // FAND(x, 0.0) -> 0.0
27213 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27214 if (C->getValueAPF().isPosZero())
27215 return N->getOperand(1);
27217 return lowerX86FPLogicOp(N, DAG, Subtarget);
27220 /// Do target-specific dag combines on X86ISD::FANDN nodes
27221 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27222 const X86Subtarget *Subtarget) {
27223 // FANDN(0.0, x) -> x
27224 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27225 if (C->getValueAPF().isPosZero())
27226 return N->getOperand(1);
27228 // FANDN(x, 0.0) -> 0.0
27229 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27230 if (C->getValueAPF().isPosZero())
27231 return N->getOperand(1);
27233 return lowerX86FPLogicOp(N, DAG, Subtarget);
27236 static SDValue PerformBTCombine(SDNode *N,
27238 TargetLowering::DAGCombinerInfo &DCI) {
27239 // BT ignores high bits in the bit index operand.
27240 SDValue Op1 = N->getOperand(1);
27241 if (Op1.hasOneUse()) {
27242 unsigned BitWidth = Op1.getValueSizeInBits();
27243 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27244 APInt KnownZero, KnownOne;
27245 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27246 !DCI.isBeforeLegalizeOps());
27247 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27248 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27249 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27250 DCI.CommitTargetLoweringOpt(TLO);
27255 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27256 SDValue Op = N->getOperand(0);
27257 if (Op.getOpcode() == ISD::BITCAST)
27258 Op = Op.getOperand(0);
27259 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27260 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27261 VT.getVectorElementType().getSizeInBits() ==
27262 OpVT.getVectorElementType().getSizeInBits()) {
27263 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27268 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27269 const X86Subtarget *Subtarget) {
27270 EVT VT = N->getValueType(0);
27271 if (!VT.isVector())
27274 SDValue N0 = N->getOperand(0);
27275 SDValue N1 = N->getOperand(1);
27276 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27279 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27280 // both SSE and AVX2 since there is no sign-extended shift right
27281 // operation on a vector with 64-bit elements.
27282 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27283 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27284 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27285 N0.getOpcode() == ISD::SIGN_EXTEND)) {
27286 SDValue N00 = N0.getOperand(0);
27288 // EXTLOAD has a better solution on AVX2,
27289 // it may be replaced with X86ISD::VSEXT node.
27290 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27291 if (!ISD::isNormalLoad(N00.getNode()))
27294 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27295 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27297 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27303 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27304 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27305 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27306 /// eliminate extend, add, and shift instructions.
27307 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27308 const X86Subtarget *Subtarget) {
27309 // TODO: This should be valid for other integer types.
27310 EVT VT = Sext->getValueType(0);
27311 if (VT != MVT::i64)
27314 // We need an 'add nsw' feeding into the 'sext'.
27315 SDValue Add = Sext->getOperand(0);
27316 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27319 // Having a constant operand to the 'add' ensures that we are not increasing
27320 // the instruction count because the constant is extended for free below.
27321 // A constant operand can also become the displacement field of an LEA.
27322 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27326 // Don't make the 'add' bigger if there's no hope of combining it with some
27327 // other 'add' or 'shl' instruction.
27328 // TODO: It may be profitable to generate simpler LEA instructions in place
27329 // of single 'add' instructions, but the cost model for selecting an LEA
27330 // currently has a high threshold.
27331 bool HasLEAPotential = false;
27332 for (auto *User : Sext->uses()) {
27333 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27334 HasLEAPotential = true;
27338 if (!HasLEAPotential)
27341 // Everything looks good, so pull the 'sext' ahead of the 'add'.
27342 int64_t AddConstant = AddOp1->getSExtValue();
27343 SDValue AddOp0 = Add.getOperand(0);
27344 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27345 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27347 // The wider add is guaranteed to not wrap because both operands are
27350 Flags.setNoSignedWrap(true);
27351 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27354 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27355 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27356 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27357 /// extends from AH (which we otherwise need to do contortions to access).
27358 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27359 SDValue N0 = N->getOperand(0);
27360 auto OpcodeN = N->getOpcode();
27361 auto OpcodeN0 = N0.getOpcode();
27362 if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27363 (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27366 EVT VT = N->getValueType(0);
27367 EVT InVT = N0.getValueType();
27368 if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27371 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27372 auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27373 : X86ISD::UDIVREM8_ZEXT_HREG;
27374 SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27376 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27377 return R.getValue(1);
27380 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27381 TargetLowering::DAGCombinerInfo &DCI,
27382 const X86Subtarget *Subtarget) {
27383 SDValue N0 = N->getOperand(0);
27384 EVT VT = N->getValueType(0);
27385 EVT SVT = VT.getScalarType();
27386 EVT InVT = N0.getValueType();
27387 EVT InSVT = InVT.getScalarType();
27390 if (SDValue DivRem8 = getDivRem8(N, DAG))
27393 if (!DCI.isBeforeLegalizeOps()) {
27394 if (InVT == MVT::i1) {
27395 SDValue Zero = DAG.getConstant(0, DL, VT);
27397 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27398 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27403 if (VT.isVector() && Subtarget->hasSSE2()) {
27404 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27405 EVT InVT = N.getValueType();
27406 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27407 Size / InVT.getScalarSizeInBits());
27408 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27409 DAG.getUNDEF(InVT));
27411 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27414 // If target-size is less than 128-bits, extend to a type that would extend
27415 // to 128 bits, extend that and extract the original target vector.
27416 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27417 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27418 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27419 unsigned Scale = 128 / VT.getSizeInBits();
27421 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27422 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27423 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27424 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27425 DAG.getIntPtrConstant(0, DL));
27428 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27429 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27430 if (VT.getSizeInBits() == 128 &&
27431 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27432 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27433 SDValue ExOp = ExtendVecSize(DL, N0, 128);
27434 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27437 // On pre-AVX2 targets, split into 128-bit nodes of
27438 // ISD::SIGN_EXTEND_VECTOR_INREG.
27439 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27440 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27441 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27442 unsigned NumVecs = VT.getSizeInBits() / 128;
27443 unsigned NumSubElts = 128 / SVT.getSizeInBits();
27444 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27445 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27447 SmallVector<SDValue, 8> Opnds;
27448 for (unsigned i = 0, Offset = 0; i != NumVecs;
27449 ++i, Offset += NumSubElts) {
27450 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27451 DAG.getIntPtrConstant(Offset, DL));
27452 SrcVec = ExtendVecSize(DL, SrcVec, 128);
27453 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27454 Opnds.push_back(SrcVec);
27456 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27460 if (Subtarget->hasAVX() && VT.is256BitVector())
27461 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27464 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27470 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27471 const X86Subtarget* Subtarget) {
27473 EVT VT = N->getValueType(0);
27475 // Let legalize expand this if it isn't a legal type yet.
27476 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27479 EVT ScalarVT = VT.getScalarType();
27480 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27483 SDValue A = N->getOperand(0);
27484 SDValue B = N->getOperand(1);
27485 SDValue C = N->getOperand(2);
27487 bool NegA = (A.getOpcode() == ISD::FNEG);
27488 bool NegB = (B.getOpcode() == ISD::FNEG);
27489 bool NegC = (C.getOpcode() == ISD::FNEG);
27491 // Negative multiplication when NegA xor NegB
27492 bool NegMul = (NegA != NegB);
27494 A = A.getOperand(0);
27496 B = B.getOperand(0);
27498 C = C.getOperand(0);
27502 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27504 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27506 return DAG.getNode(Opcode, dl, VT, A, B, C);
27509 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27510 TargetLowering::DAGCombinerInfo &DCI,
27511 const X86Subtarget *Subtarget) {
27512 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
27513 // (and (i32 x86isd::setcc_carry), 1)
27514 // This eliminates the zext. This transformation is necessary because
27515 // ISD::SETCC is always legalized to i8.
27517 SDValue N0 = N->getOperand(0);
27518 EVT VT = N->getValueType(0);
27520 if (N0.getOpcode() == ISD::AND &&
27522 N0.getOperand(0).hasOneUse()) {
27523 SDValue N00 = N0.getOperand(0);
27524 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27525 if (!isOneConstant(N0.getOperand(1)))
27527 return DAG.getNode(ISD::AND, dl, VT,
27528 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27529 N00.getOperand(0), N00.getOperand(1)),
27530 DAG.getConstant(1, dl, VT));
27534 if (N0.getOpcode() == ISD::TRUNCATE &&
27536 N0.getOperand(0).hasOneUse()) {
27537 SDValue N00 = N0.getOperand(0);
27538 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27539 return DAG.getNode(ISD::AND, dl, VT,
27540 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27541 N00.getOperand(0), N00.getOperand(1)),
27542 DAG.getConstant(1, dl, VT));
27546 if (VT.is256BitVector())
27547 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27550 if (SDValue DivRem8 = getDivRem8(N, DAG))
27556 // Optimize x == -y --> x+y == 0
27557 // x != -y --> x+y != 0
27558 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27559 const X86Subtarget* Subtarget) {
27560 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27561 SDValue LHS = N->getOperand(0);
27562 SDValue RHS = N->getOperand(1);
27563 EVT VT = N->getValueType(0);
27566 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27567 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27568 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27569 LHS.getOperand(1));
27570 return DAG.getSetCC(DL, N->getValueType(0), addV,
27571 DAG.getConstant(0, DL, addV.getValueType()), CC);
27573 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27574 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27575 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27576 RHS.getOperand(1));
27577 return DAG.getSetCC(DL, N->getValueType(0), addV,
27578 DAG.getConstant(0, DL, addV.getValueType()), CC);
27581 if (VT.getScalarType() == MVT::i1 &&
27582 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27584 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27585 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27586 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27588 if (!IsSEXT0 || !IsVZero1) {
27589 // Swap the operands and update the condition code.
27590 std::swap(LHS, RHS);
27591 CC = ISD::getSetCCSwappedOperands(CC);
27593 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27594 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27595 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27598 if (IsSEXT0 && IsVZero1) {
27599 assert(VT == LHS.getOperand(0).getValueType() &&
27600 "Uexpected operand type");
27601 if (CC == ISD::SETGT)
27602 return DAG.getConstant(0, DL, VT);
27603 if (CC == ISD::SETLE)
27604 return DAG.getConstant(1, DL, VT);
27605 if (CC == ISD::SETEQ || CC == ISD::SETGE)
27606 return DAG.getNOT(DL, LHS.getOperand(0), VT);
27608 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27609 "Unexpected condition code!");
27610 return LHS.getOperand(0);
27617 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27619 // Gather and Scatter instructions use k-registers for masks. The type of
27620 // the masks is v*i1. So the mask will be truncated anyway.
27621 // The SIGN_EXTEND_INREG my be dropped.
27622 SDValue Mask = N->getOperand(2);
27623 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27624 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27625 NewOps[2] = Mask.getOperand(0);
27626 DAG.UpdateNodeOperands(N, NewOps);
27631 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27632 // as "sbb reg,reg", since it can be extended without zext and produces
27633 // an all-ones bit which is more useful than 0/1 in some cases.
27634 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27637 return DAG.getNode(ISD::AND, DL, VT,
27638 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27639 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27641 DAG.getConstant(1, DL, VT));
27642 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27643 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27644 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27645 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27649 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27650 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27651 TargetLowering::DAGCombinerInfo &DCI,
27652 const X86Subtarget *Subtarget) {
27654 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27655 SDValue EFLAGS = N->getOperand(1);
27657 if (CC == X86::COND_A) {
27658 // Try to convert COND_A into COND_B in an attempt to facilitate
27659 // materializing "setb reg".
27661 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27662 // cannot take an immediate as its first operand.
27664 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27665 EFLAGS.getValueType().isInteger() &&
27666 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27667 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27668 EFLAGS.getNode()->getVTList(),
27669 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27670 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27671 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27675 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27676 // a zext and produces an all-ones bit which is more useful than 0/1 in some
27678 if (CC == X86::COND_B)
27679 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27681 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27682 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27683 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27689 // Optimize branch condition evaluation.
27691 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27692 TargetLowering::DAGCombinerInfo &DCI,
27693 const X86Subtarget *Subtarget) {
27695 SDValue Chain = N->getOperand(0);
27696 SDValue Dest = N->getOperand(1);
27697 SDValue EFLAGS = N->getOperand(3);
27698 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27700 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27701 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27702 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27709 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27710 SelectionDAG &DAG) {
27711 // Take advantage of vector comparisons producing 0 or -1 in each lane to
27712 // optimize away operation when it's from a constant.
27714 // The general transformation is:
27715 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27716 // AND(VECTOR_CMP(x,y), constant2)
27717 // constant2 = UNARYOP(constant)
27719 // Early exit if this isn't a vector operation, the operand of the
27720 // unary operation isn't a bitwise AND, or if the sizes of the operations
27721 // aren't the same.
27722 EVT VT = N->getValueType(0);
27723 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27724 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27725 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27728 // Now check that the other operand of the AND is a constant. We could
27729 // make the transformation for non-constant splats as well, but it's unclear
27730 // that would be a benefit as it would not eliminate any operations, just
27731 // perform one more step in scalar code before moving to the vector unit.
27732 if (BuildVectorSDNode *BV =
27733 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27734 // Bail out if the vector isn't a constant.
27735 if (!BV->isConstant())
27738 // Everything checks out. Build up the new and improved node.
27740 EVT IntVT = BV->getValueType(0);
27741 // Create a new constant of the appropriate type for the transformed
27743 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27744 // The AND node needs bitcasts to/from an integer vector type around it.
27745 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27746 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27747 N->getOperand(0)->getOperand(0), MaskConst);
27748 SDValue Res = DAG.getBitcast(VT, NewAnd);
27755 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27756 const X86Subtarget *Subtarget) {
27757 SDValue Op0 = N->getOperand(0);
27758 EVT VT = N->getValueType(0);
27759 EVT InVT = Op0.getValueType();
27760 EVT InSVT = InVT.getScalarType();
27761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27763 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27764 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27765 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27767 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27768 InVT.getVectorNumElements());
27769 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27771 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27772 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27774 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27780 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27781 const X86Subtarget *Subtarget) {
27782 // First try to optimize away the conversion entirely when it's
27783 // conditionally from a constant. Vectors only.
27784 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27787 // Now move on to more general possibilities.
27788 SDValue Op0 = N->getOperand(0);
27789 EVT VT = N->getValueType(0);
27790 EVT InVT = Op0.getValueType();
27791 EVT InSVT = InVT.getScalarType();
27793 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27794 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27795 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27797 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27798 InVT.getVectorNumElements());
27799 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27800 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27803 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27804 // a 32-bit target where SSE doesn't support i64->FP operations.
27805 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27806 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27807 EVT LdVT = Ld->getValueType(0);
27809 // This transformation is not supported if the result type is f16
27810 if (VT == MVT::f16)
27813 if (!Ld->isVolatile() && !VT.isVector() &&
27814 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27815 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27816 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27817 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27818 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27825 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27826 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27827 X86TargetLowering::DAGCombinerInfo &DCI) {
27828 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27829 // the result is either zero or one (depending on the input carry bit).
27830 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27831 if (X86::isZeroNode(N->getOperand(0)) &&
27832 X86::isZeroNode(N->getOperand(1)) &&
27833 // We don't have a good way to replace an EFLAGS use, so only do this when
27835 SDValue(N, 1).use_empty()) {
27837 EVT VT = N->getValueType(0);
27838 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27839 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27840 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27841 DAG.getConstant(X86::COND_B, DL,
27844 DAG.getConstant(1, DL, VT));
27845 return DCI.CombineTo(N, Res1, CarryOut);
27851 // fold (add Y, (sete X, 0)) -> adc 0, Y
27852 // (add Y, (setne X, 0)) -> sbb -1, Y
27853 // (sub (sete X, 0), Y) -> sbb 0, Y
27854 // (sub (setne X, 0), Y) -> adc -1, Y
27855 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27858 // Look through ZExts.
27859 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27860 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27863 SDValue SetCC = Ext.getOperand(0);
27864 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27867 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27868 if (CC != X86::COND_E && CC != X86::COND_NE)
27871 SDValue Cmp = SetCC.getOperand(1);
27872 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27873 !X86::isZeroNode(Cmp.getOperand(1)) ||
27874 !Cmp.getOperand(0).getValueType().isInteger())
27877 SDValue CmpOp0 = Cmp.getOperand(0);
27878 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27879 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27881 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27882 if (CC == X86::COND_NE)
27883 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27884 DL, OtherVal.getValueType(), OtherVal,
27885 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27887 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27888 DL, OtherVal.getValueType(), OtherVal,
27889 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27892 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27893 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27894 const X86Subtarget *Subtarget) {
27895 EVT VT = N->getValueType(0);
27896 SDValue Op0 = N->getOperand(0);
27897 SDValue Op1 = N->getOperand(1);
27899 // Try to synthesize horizontal adds from adds of shuffles.
27900 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27901 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27902 isHorizontalBinOp(Op0, Op1, true))
27903 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27905 return OptimizeConditionalInDecrement(N, DAG);
27908 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27909 const X86Subtarget *Subtarget) {
27910 SDValue Op0 = N->getOperand(0);
27911 SDValue Op1 = N->getOperand(1);
27913 // X86 can't encode an immediate LHS of a sub. See if we can push the
27914 // negation into a preceding instruction.
27915 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27916 // If the RHS of the sub is a XOR with one use and a constant, invert the
27917 // immediate. Then add one to the LHS of the sub so we can turn
27918 // X-Y -> X+~Y+1, saving one register.
27919 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27920 isa<ConstantSDNode>(Op1.getOperand(1))) {
27921 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27922 EVT VT = Op0.getValueType();
27923 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27925 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27926 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27927 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27931 // Try to synthesize horizontal adds from adds of shuffles.
27932 EVT VT = N->getValueType(0);
27933 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27934 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27935 isHorizontalBinOp(Op0, Op1, true))
27936 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27938 return OptimizeConditionalInDecrement(N, DAG);
27941 /// performVZEXTCombine - Performs build vector combines
27942 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27943 TargetLowering::DAGCombinerInfo &DCI,
27944 const X86Subtarget *Subtarget) {
27946 MVT VT = N->getSimpleValueType(0);
27947 SDValue Op = N->getOperand(0);
27948 MVT OpVT = Op.getSimpleValueType();
27949 MVT OpEltVT = OpVT.getVectorElementType();
27950 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27952 // (vzext (bitcast (vzext (x)) -> (vzext x)
27954 while (V.getOpcode() == ISD::BITCAST)
27955 V = V.getOperand(0);
27957 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27958 MVT InnerVT = V.getSimpleValueType();
27959 MVT InnerEltVT = InnerVT.getVectorElementType();
27961 // If the element sizes match exactly, we can just do one larger vzext. This
27962 // is always an exact type match as vzext operates on integer types.
27963 if (OpEltVT == InnerEltVT) {
27964 assert(OpVT == InnerVT && "Types must match for vzext!");
27965 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27968 // The only other way we can combine them is if only a single element of the
27969 // inner vzext is used in the input to the outer vzext.
27970 if (InnerEltVT.getSizeInBits() < InputBits)
27973 // In this case, the inner vzext is completely dead because we're going to
27974 // only look at bits inside of the low element. Just do the outer vzext on
27975 // a bitcast of the input to the inner.
27976 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27979 // Check if we can bypass extracting and re-inserting an element of an input
27980 // vector. Essentially:
27981 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27982 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27983 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27984 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27985 SDValue ExtractedV = V.getOperand(0);
27986 SDValue OrigV = ExtractedV.getOperand(0);
27987 if (isNullConstant(ExtractedV.getOperand(1))) {
27988 MVT OrigVT = OrigV.getSimpleValueType();
27989 // Extract a subvector if necessary...
27990 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27991 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27992 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27993 OrigVT.getVectorNumElements() / Ratio);
27994 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27995 DAG.getIntPtrConstant(0, DL));
27997 Op = DAG.getBitcast(OpVT, OrigV);
27998 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
28005 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
28006 DAGCombinerInfo &DCI) const {
28007 SelectionDAG &DAG = DCI.DAG;
28008 switch (N->getOpcode()) {
28010 case ISD::EXTRACT_VECTOR_ELT:
28011 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
28014 case X86ISD::SHRUNKBLEND:
28015 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
28016 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
28017 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
28018 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
28019 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
28020 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
28021 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
28024 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
28025 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
28026 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
28027 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
28028 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
28029 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
28030 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
28031 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
28032 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
28033 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
28034 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
28035 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
28036 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
28037 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
28039 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
28041 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
28043 case ISD::FMAXNUM: return performFMinNumFMaxNumCombine(N, DAG,
28045 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
28046 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
28047 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
28048 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
28049 case ISD::ANY_EXTEND:
28050 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
28051 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
28052 case ISD::SIGN_EXTEND_INREG:
28053 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
28054 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
28055 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
28056 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
28057 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
28058 case X86ISD::SHUFP: // Handle all target specific shuffles
28059 case X86ISD::PALIGNR:
28060 case X86ISD::BLENDI:
28061 case X86ISD::UNPCKH:
28062 case X86ISD::UNPCKL:
28063 case X86ISD::MOVHLPS:
28064 case X86ISD::MOVLHPS:
28065 case X86ISD::PSHUFB:
28066 case X86ISD::PSHUFD:
28067 case X86ISD::PSHUFHW:
28068 case X86ISD::PSHUFLW:
28069 case X86ISD::MOVSS:
28070 case X86ISD::MOVSD:
28071 case X86ISD::VPERMILPI:
28072 case X86ISD::VPERM2X128:
28073 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
28074 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
28076 case ISD::MSCATTER: return PerformGatherScatterCombine(N, DAG);
28082 /// isTypeDesirableForOp - Return true if the target has native support for
28083 /// the specified value type and it is 'desirable' to use the type for the
28084 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
28085 /// instruction encodings are longer and some i16 instructions are slow.
28086 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28087 if (!isTypeLegal(VT))
28089 if (VT != MVT::i16)
28096 case ISD::SIGN_EXTEND:
28097 case ISD::ZERO_EXTEND:
28098 case ISD::ANY_EXTEND:
28111 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28112 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28113 /// we don't adjust the stack we clobber the first frame index.
28114 /// See X86InstrInfo::copyPhysReg.
28115 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28116 MachineFunction *MF) const {
28117 const MachineRegisterInfo &MRI = MF->getRegInfo();
28119 return any_of(MRI.reg_instructions(X86::EFLAGS),
28120 [](const MachineInstr &RI) { return RI.isCopy(); });
28123 /// IsDesirableToPromoteOp - This method query the target whether it is
28124 /// beneficial for dag combiner to promote the specified node. If true, it
28125 /// should return the desired promotion type by reference.
28126 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28127 EVT VT = Op.getValueType();
28128 if (VT != MVT::i16)
28131 bool Promote = false;
28132 bool Commute = false;
28133 switch (Op.getOpcode()) {
28136 LoadSDNode *LD = cast<LoadSDNode>(Op);
28137 // If the non-extending load has a single use and it's not live out, then it
28138 // might be folded.
28139 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28140 Op.hasOneUse()*/) {
28141 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28142 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28143 // The only case where we'd want to promote LOAD (rather then it being
28144 // promoted as an operand is when it's only use is liveout.
28145 if (UI->getOpcode() != ISD::CopyToReg)
28152 case ISD::SIGN_EXTEND:
28153 case ISD::ZERO_EXTEND:
28154 case ISD::ANY_EXTEND:
28159 SDValue N0 = Op.getOperand(0);
28160 // Look out for (store (shl (load), x)).
28161 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28174 SDValue N0 = Op.getOperand(0);
28175 SDValue N1 = Op.getOperand(1);
28176 if (!Commute && MayFoldLoad(N1))
28178 // Avoid disabling potential load folding opportunities.
28179 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28181 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28191 //===----------------------------------------------------------------------===//
28192 // X86 Inline Assembly Support
28193 //===----------------------------------------------------------------------===//
28195 // Helper to match a string separated by whitespace.
28196 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28197 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28199 for (StringRef Piece : Pieces) {
28200 if (!S.startswith(Piece)) // Check if the piece matches.
28203 S = S.substr(Piece.size());
28204 StringRef::size_type Pos = S.find_first_not_of(" \t");
28205 if (Pos == 0) // We matched a prefix.
28214 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28216 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28217 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28218 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28219 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28221 if (AsmPieces.size() == 3)
28223 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28230 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28231 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28233 std::string AsmStr = IA->getAsmString();
28235 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28236 if (!Ty || Ty->getBitWidth() % 16 != 0)
28239 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28240 SmallVector<StringRef, 4> AsmPieces;
28241 SplitString(AsmStr, AsmPieces, ";\n");
28243 switch (AsmPieces.size()) {
28244 default: return false;
28246 // FIXME: this should verify that we are targeting a 486 or better. If not,
28247 // we will turn this bswap into something that will be lowered to logical
28248 // ops instead of emitting the bswap asm. For now, we don't support 486 or
28249 // lower so don't worry about this.
28251 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28252 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28253 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28254 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28255 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28256 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28257 // No need to check constraints, nothing other than the equivalent of
28258 // "=r,0" would be valid here.
28259 return IntrinsicLowering::LowerToByteSwap(CI);
28262 // rorw $$8, ${0:w} --> llvm.bswap.i16
28263 if (CI->getType()->isIntegerTy(16) &&
28264 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28265 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28266 matchAsm(AsmPieces[0], {"rolw", "$$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);
28276 if (CI->getType()->isIntegerTy(32) &&
28277 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28278 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28279 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28280 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28282 StringRef ConstraintsStr = IA->getConstraintString();
28283 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28284 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28285 if (clobbersFlagRegisters(AsmPieces))
28286 return IntrinsicLowering::LowerToByteSwap(CI);
28289 if (CI->getType()->isIntegerTy(64)) {
28290 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28291 if (Constraints.size() >= 2 &&
28292 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28293 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28294 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
28295 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28296 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28297 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28298 return IntrinsicLowering::LowerToByteSwap(CI);
28306 /// getConstraintType - Given a constraint letter, return the type of
28307 /// constraint it is for this target.
28308 X86TargetLowering::ConstraintType
28309 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28310 if (Constraint.size() == 1) {
28311 switch (Constraint[0]) {
28322 return C_RegisterClass;
28346 return TargetLowering::getConstraintType(Constraint);
28349 /// Examine constraint type and operand type and determine a weight value.
28350 /// This object must already have been set up with the operand type
28351 /// and the current alternative constraint selected.
28352 TargetLowering::ConstraintWeight
28353 X86TargetLowering::getSingleConstraintMatchWeight(
28354 AsmOperandInfo &info, const char *constraint) const {
28355 ConstraintWeight weight = CW_Invalid;
28356 Value *CallOperandVal = info.CallOperandVal;
28357 // If we don't have a value, we can't do a match,
28358 // but allow it at the lowest weight.
28359 if (!CallOperandVal)
28361 Type *type = CallOperandVal->getType();
28362 // Look at the constraint type.
28363 switch (*constraint) {
28365 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28376 if (CallOperandVal->getType()->isIntegerTy())
28377 weight = CW_SpecificReg;
28382 if (type->isFloatingPointTy())
28383 weight = CW_SpecificReg;
28386 if (type->isX86_MMXTy() && Subtarget->hasMMX())
28387 weight = CW_SpecificReg;
28391 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28392 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28393 weight = CW_Register;
28396 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28397 if (C->getZExtValue() <= 31)
28398 weight = CW_Constant;
28402 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28403 if (C->getZExtValue() <= 63)
28404 weight = CW_Constant;
28408 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28409 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28410 weight = CW_Constant;
28414 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28415 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28416 weight = CW_Constant;
28420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28421 if (C->getZExtValue() <= 3)
28422 weight = CW_Constant;
28426 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28427 if (C->getZExtValue() <= 0xff)
28428 weight = CW_Constant;
28433 if (isa<ConstantFP>(CallOperandVal)) {
28434 weight = CW_Constant;
28438 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28439 if ((C->getSExtValue() >= -0x80000000LL) &&
28440 (C->getSExtValue() <= 0x7fffffffLL))
28441 weight = CW_Constant;
28445 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28446 if (C->getZExtValue() <= 0xffffffff)
28447 weight = CW_Constant;
28454 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28455 /// with another that has more specific requirements based on the type of the
28456 /// corresponding operand.
28457 const char *X86TargetLowering::
28458 LowerXConstraint(EVT ConstraintVT) const {
28459 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28460 // 'f' like normal targets.
28461 if (ConstraintVT.isFloatingPoint()) {
28462 if (Subtarget->hasSSE2())
28464 if (Subtarget->hasSSE1())
28468 return TargetLowering::LowerXConstraint(ConstraintVT);
28471 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28472 /// vector. If it is invalid, don't add anything to Ops.
28473 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28474 std::string &Constraint,
28475 std::vector<SDValue>&Ops,
28476 SelectionDAG &DAG) const {
28479 // Only support length 1 constraints for now.
28480 if (Constraint.length() > 1) return;
28482 char ConstraintLetter = Constraint[0];
28483 switch (ConstraintLetter) {
28486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28487 if (C->getZExtValue() <= 31) {
28488 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28489 Op.getValueType());
28495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28496 if (C->getZExtValue() <= 63) {
28497 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28498 Op.getValueType());
28504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28505 if (isInt<8>(C->getSExtValue())) {
28506 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28507 Op.getValueType());
28513 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28514 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28515 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28516 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28517 Op.getValueType());
28523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28524 if (C->getZExtValue() <= 3) {
28525 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28526 Op.getValueType());
28532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28533 if (C->getZExtValue() <= 255) {
28534 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28535 Op.getValueType());
28541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28542 if (C->getZExtValue() <= 127) {
28543 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28544 Op.getValueType());
28550 // 32-bit signed value
28551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28552 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28553 C->getSExtValue())) {
28554 // Widen to 64 bits here to get it sign extended.
28555 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28558 // FIXME gcc accepts some relocatable values here too, but only in certain
28559 // memory models; it's complicated.
28564 // 32-bit unsigned value
28565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28566 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28567 C->getZExtValue())) {
28568 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28569 Op.getValueType());
28573 // FIXME gcc accepts some relocatable values here too, but only in certain
28574 // memory models; it's complicated.
28578 // Literal immediates are always ok.
28579 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28580 // Widen to 64 bits here to get it sign extended.
28581 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28585 // In any sort of PIC mode addresses need to be computed at runtime by
28586 // adding in a register or some sort of table lookup. These can't
28587 // be used as immediates.
28588 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28591 // If we are in non-pic codegen mode, we allow the address of a global (with
28592 // an optional displacement) to be used with 'i'.
28593 GlobalAddressSDNode *GA = nullptr;
28594 int64_t Offset = 0;
28596 // Match either (GA), (GA+C), (GA+C1+C2), etc.
28598 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28599 Offset += GA->getOffset();
28601 } else if (Op.getOpcode() == ISD::ADD) {
28602 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28603 Offset += C->getZExtValue();
28604 Op = Op.getOperand(0);
28607 } else if (Op.getOpcode() == ISD::SUB) {
28608 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28609 Offset += -C->getZExtValue();
28610 Op = Op.getOperand(0);
28615 // Otherwise, this isn't something we can handle, reject it.
28619 const GlobalValue *GV = GA->getGlobal();
28620 // If we require an extra load to get this address, as in PIC mode, we
28621 // can't accept it.
28622 if (isGlobalStubReference(
28623 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28626 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28627 GA->getValueType(0), Offset);
28632 if (Result.getNode()) {
28633 Ops.push_back(Result);
28636 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28639 std::pair<unsigned, const TargetRegisterClass *>
28640 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28641 StringRef Constraint,
28643 // First, see if this is a constraint that directly corresponds to an LLVM
28645 if (Constraint.size() == 1) {
28646 // GCC Constraint Letters
28647 switch (Constraint[0]) {
28649 // TODO: Slight differences here in allocation order and leaving
28650 // RIP in the class. Do they matter any more here than they do
28651 // in the normal allocation?
28652 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28653 if (Subtarget->is64Bit()) {
28654 if (VT == MVT::i32 || VT == MVT::f32)
28655 return std::make_pair(0U, &X86::GR32RegClass);
28656 if (VT == MVT::i16)
28657 return std::make_pair(0U, &X86::GR16RegClass);
28658 if (VT == MVT::i8 || VT == MVT::i1)
28659 return std::make_pair(0U, &X86::GR8RegClass);
28660 if (VT == MVT::i64 || VT == MVT::f64)
28661 return std::make_pair(0U, &X86::GR64RegClass);
28664 // 32-bit fallthrough
28665 case 'Q': // Q_REGS
28666 if (VT == MVT::i32 || VT == MVT::f32)
28667 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28668 if (VT == MVT::i16)
28669 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28670 if (VT == MVT::i8 || VT == MVT::i1)
28671 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28672 if (VT == MVT::i64)
28673 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28675 case 'r': // GENERAL_REGS
28676 case 'l': // INDEX_REGS
28677 if (VT == MVT::i8 || VT == MVT::i1)
28678 return std::make_pair(0U, &X86::GR8RegClass);
28679 if (VT == MVT::i16)
28680 return std::make_pair(0U, &X86::GR16RegClass);
28681 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28682 return std::make_pair(0U, &X86::GR32RegClass);
28683 return std::make_pair(0U, &X86::GR64RegClass);
28684 case 'R': // LEGACY_REGS
28685 if (VT == MVT::i8 || VT == MVT::i1)
28686 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28687 if (VT == MVT::i16)
28688 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28689 if (VT == MVT::i32 || !Subtarget->is64Bit())
28690 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28691 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28692 case 'f': // FP Stack registers.
28693 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28694 // value to the correct fpstack register class.
28695 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28696 return std::make_pair(0U, &X86::RFP32RegClass);
28697 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28698 return std::make_pair(0U, &X86::RFP64RegClass);
28699 return std::make_pair(0U, &X86::RFP80RegClass);
28700 case 'y': // MMX_REGS if MMX allowed.
28701 if (!Subtarget->hasMMX()) break;
28702 return std::make_pair(0U, &X86::VR64RegClass);
28703 case 'Y': // SSE_REGS if SSE2 allowed
28704 if (!Subtarget->hasSSE2()) break;
28706 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28707 if (!Subtarget->hasSSE1()) break;
28709 switch (VT.SimpleTy) {
28711 // Scalar SSE types.
28714 return std::make_pair(0U, &X86::FR32RegClass);
28717 return std::make_pair(0U, &X86::FR64RegClass);
28718 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28726 return std::make_pair(0U, &X86::VR128RegClass);
28734 return std::make_pair(0U, &X86::VR256RegClass);
28739 return std::make_pair(0U, &X86::VR512RegClass);
28745 // Use the default implementation in TargetLowering to convert the register
28746 // constraint into a member of a register class.
28747 std::pair<unsigned, const TargetRegisterClass*> Res;
28748 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28750 // Not found as a standard register?
28752 // Map st(0) -> st(7) -> ST0
28753 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28754 tolower(Constraint[1]) == 's' &&
28755 tolower(Constraint[2]) == 't' &&
28756 Constraint[3] == '(' &&
28757 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28758 Constraint[5] == ')' &&
28759 Constraint[6] == '}') {
28761 Res.first = X86::FP0+Constraint[4]-'0';
28762 Res.second = &X86::RFP80RegClass;
28766 // GCC allows "st(0)" to be called just plain "st".
28767 if (StringRef("{st}").equals_lower(Constraint)) {
28768 Res.first = X86::FP0;
28769 Res.second = &X86::RFP80RegClass;
28774 if (StringRef("{flags}").equals_lower(Constraint)) {
28775 Res.first = X86::EFLAGS;
28776 Res.second = &X86::CCRRegClass;
28780 // 'A' means EAX + EDX.
28781 if (Constraint == "A") {
28782 Res.first = X86::EAX;
28783 Res.second = &X86::GR32_ADRegClass;
28789 // Otherwise, check to see if this is a register class of the wrong value
28790 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28791 // turn into {ax},{dx}.
28792 // MVT::Other is used to specify clobber names.
28793 if (Res.second->hasType(VT) || VT == MVT::Other)
28794 return Res; // Correct type already, nothing to do.
28796 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28797 // return "eax". This should even work for things like getting 64bit integer
28798 // registers when given an f64 type.
28799 const TargetRegisterClass *Class = Res.second;
28800 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28801 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28802 unsigned Size = VT.getSizeInBits();
28803 if (Size == 1) Size = 8;
28804 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28806 Res.first = DestReg;
28807 Res.second = Size == 8 ? &X86::GR8RegClass
28808 : Size == 16 ? &X86::GR16RegClass
28809 : Size == 32 ? &X86::GR32RegClass
28810 : &X86::GR64RegClass;
28811 assert(Res.second->contains(Res.first) && "Register in register class");
28813 // No register found/type mismatch.
28815 Res.second = nullptr;
28817 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28818 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28819 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28820 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28821 Class == &X86::VR512RegClass) {
28822 // Handle references to XMM physical registers that got mapped into the
28823 // wrong class. This can happen with constraints like {xmm0} where the
28824 // target independent register mapper will just pick the first match it can
28825 // find, ignoring the required type.
28827 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28828 if (VT == MVT::f32 || VT == MVT::i32)
28829 Res.second = &X86::FR32RegClass;
28830 else if (VT == MVT::f64 || VT == MVT::i64)
28831 Res.second = &X86::FR64RegClass;
28832 else if (X86::VR128RegClass.hasType(VT))
28833 Res.second = &X86::VR128RegClass;
28834 else if (X86::VR256RegClass.hasType(VT))
28835 Res.second = &X86::VR256RegClass;
28836 else if (X86::VR512RegClass.hasType(VT))
28837 Res.second = &X86::VR512RegClass;
28839 // Type mismatch and not a clobber: Return an error;
28841 Res.second = nullptr;
28848 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28849 const AddrMode &AM, Type *Ty,
28850 unsigned AS) const {
28851 // Scaling factors are not free at all.
28852 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28853 // will take 2 allocations in the out of order engine instead of 1
28854 // for plain addressing mode, i.e. inst (reg1).
28856 // vaddps (%rsi,%drx), %ymm0, %ymm1
28857 // Requires two allocations (one for the load, one for the computation)
28859 // vaddps (%rsi), %ymm0, %ymm1
28860 // Requires just 1 allocation, i.e., freeing allocations for other operations
28861 // and having less micro operations to execute.
28863 // For some X86 architectures, this is even worse because for instance for
28864 // stores, the complex addressing mode forces the instruction to use the
28865 // "load" ports instead of the dedicated "store" port.
28866 // E.g., on Haswell:
28867 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28868 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28869 if (isLegalAddressingMode(DL, AM, Ty, AS))
28870 // Scale represents reg2 * scale, thus account for 1
28871 // as soon as we use a second register.
28872 return AM.Scale != 0;
28876 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28877 // Integer division on x86 is expensive. However, when aggressively optimizing
28878 // for code size, we prefer to use a div instruction, as it is usually smaller
28879 // than the alternative sequence.
28880 // The exception to this is vector division. Since x86 doesn't have vector
28881 // integer division, leaving the division as-is is a loss even in terms of
28882 // size, because it will have to be scalarized, while the alternative code
28883 // sequence can be performed in vector form.
28884 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28885 Attribute::MinSize);
28886 return OptSize && !VT.isVector();
28889 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
28890 if (!Subtarget->is64Bit())
28893 // Update IsSplitCSR in X86MachineFunctionInfo.
28894 X86MachineFunctionInfo *AFI =
28895 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
28896 AFI->setIsSplitCSR(true);
28899 void X86TargetLowering::insertCopiesSplitCSR(
28900 MachineBasicBlock *Entry,
28901 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
28902 const X86RegisterInfo *TRI = Subtarget->getRegisterInfo();
28903 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
28907 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
28908 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
28909 for (const MCPhysReg *I = IStart; *I; ++I) {
28910 const TargetRegisterClass *RC = nullptr;
28911 if (X86::GR64RegClass.contains(*I))
28912 RC = &X86::GR64RegClass;
28914 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
28916 unsigned NewVR = MRI->createVirtualRegister(RC);
28917 // Create copy from CSR to a virtual register.
28918 // FIXME: this currently does not emit CFI pseudo-instructions, it works
28919 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
28920 // nounwind. If we want to generalize this later, we may need to emit
28921 // CFI pseudo-instructions.
28922 assert(Entry->getParent()->getFunction()->hasFnAttribute(
28923 Attribute::NoUnwind) &&
28924 "Function should be nounwind in insertCopiesSplitCSR!");
28925 Entry->addLiveIn(*I);
28926 BuildMI(*Entry, Entry->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),
28930 for (auto *Exit : Exits)
28931 BuildMI(*Exit, Exit->begin(), DebugLoc(), TII->get(TargetOpcode::COPY),