1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 static cl::opt<int> ReciprocalEstimateRefinementSteps(
71 "x86-recip-refinement-steps", cl::init(1),
72 cl::desc("Specify the number of Newton-Raphson iterations applied to the "
73 "result of the hardware reciprocal estimate instruction."),
76 // Forward declarations.
77 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
80 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
81 const X86Subtarget &STI)
82 : TargetLowering(TM), Subtarget(&STI) {
83 X86ScalarSSEf64 = Subtarget->hasSSE2();
84 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 // Set up the TargetLowering object.
88 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
90 // X86 is weird. It always uses i8 for shift amounts and setcc results.
91 setBooleanContents(ZeroOrOneBooleanContent);
92 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
93 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
95 // For 64-bit, since we have so many registers, use the ILP scheduler.
96 // For 32-bit, use the register pressure specific scheduling.
97 // For Atom, always use ILP scheduling.
98 if (Subtarget->isAtom())
99 setSchedulingPreference(Sched::ILP);
100 else if (Subtarget->is64Bit())
101 setSchedulingPreference(Sched::ILP);
103 setSchedulingPreference(Sched::RegPressure);
104 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
105 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
107 // Bypass expensive divides on Atom when compiling with O2.
108 if (TM.getOptLevel() >= CodeGenOpt::Default) {
109 if (Subtarget->hasSlowDivide32())
110 addBypassSlowDiv(32, 8);
111 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
112 addBypassSlowDiv(64, 16);
115 if (Subtarget->isTargetKnownWindowsMSVC()) {
116 // Setup Windows compiler runtime calls.
117 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
118 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
119 setLibcallName(RTLIB::SREM_I64, "_allrem");
120 setLibcallName(RTLIB::UREM_I64, "_aullrem");
121 setLibcallName(RTLIB::MUL_I64, "_allmul");
122 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
123 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
124 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
125 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
126 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
128 // The _ftol2 runtime function has an unusual calling conv, which
129 // is modeled by a special pseudo-instruction.
130 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
131 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
132 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
133 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
136 if (Subtarget->isTargetDarwin()) {
137 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
138 setUseUnderscoreSetJmp(false);
139 setUseUnderscoreLongJmp(false);
140 } else if (Subtarget->isTargetWindowsGNU()) {
141 // MS runtime is weird: it exports _setjmp, but longjmp!
142 setUseUnderscoreSetJmp(true);
143 setUseUnderscoreLongJmp(false);
145 setUseUnderscoreSetJmp(true);
146 setUseUnderscoreLongJmp(true);
149 // Set up the register classes.
150 addRegisterClass(MVT::i8, &X86::GR8RegClass);
151 addRegisterClass(MVT::i16, &X86::GR16RegClass);
152 addRegisterClass(MVT::i32, &X86::GR32RegClass);
153 if (Subtarget->is64Bit())
154 addRegisterClass(MVT::i64, &X86::GR64RegClass);
156 for (MVT VT : MVT::integer_valuetypes())
157 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
159 // We don't accept any truncstore of integer registers.
160 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
162 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
163 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
164 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
165 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
167 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
169 // SETOEQ and SETUNE require checking two conditions.
170 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
171 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
172 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
173 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
174 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
175 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
177 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
179 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
180 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
181 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
183 if (Subtarget->is64Bit()) {
184 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
185 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
186 } else if (!TM.Options.UseSoftFloat) {
187 // We have an algorithm for SSE2->double, and we turn this into a
188 // 64-bit FILD followed by conditional FADD for other targets.
189 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
190 // We have an algorithm for SSE2, and we turn this into a 64-bit
191 // FILD for other targets.
192 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
195 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
197 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
200 if (!TM.Options.UseSoftFloat) {
201 // SSE has no i16 to fp conversion, only i32
202 if (X86ScalarSSEf32) {
203 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
204 // f32 and f64 cases are Legal, f80 case is not
205 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
207 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
211 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
215 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
216 // are Legal, f80 is custom lowered.
217 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
218 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
220 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
222 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
225 if (X86ScalarSSEf32) {
226 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
227 // f32 and f64 cases are Legal, f80 case is not
228 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
230 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
231 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
234 // Handle FP_TO_UINT by promoting the destination to a larger signed
236 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
237 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
240 if (Subtarget->is64Bit()) {
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
243 } else if (!TM.Options.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 SSE3 we can use fisttpll to convert to a signed i64; without
252 // SSE, we're stuck with a fistpll.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 if (isTargetFTOL()) {
257 // Use the _ftol2 runtime function, which has a pseudo-instruction
258 // to handle its weird calling convention.
259 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
262 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
263 if (!X86ScalarSSEf64) {
264 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
265 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
266 if (Subtarget->is64Bit()) {
267 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
268 // Without SSE, i64->f64 goes through memory.
269 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
273 // Scalar integer divide and remainder are lowered to use operations that
274 // produce two results, to match the available instructions. This exposes
275 // the two-result form to trivial CSE, which is able to combine x/y and x%y
276 // into a single instruction.
278 // Scalar integer multiply-high is also lowered to use two-result
279 // operations, to match the available instructions. However, plain multiply
280 // (low) operations are left as Legal, as there are single-result
281 // instructions for this in x86. Using the two-result multiply instructions
282 // when both high and low results are needed must be arranged by dagcombine.
283 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
285 setOperationAction(ISD::MULHS, VT, Expand);
286 setOperationAction(ISD::MULHU, VT, Expand);
287 setOperationAction(ISD::SDIV, VT, Expand);
288 setOperationAction(ISD::UDIV, VT, Expand);
289 setOperationAction(ISD::SREM, VT, Expand);
290 setOperationAction(ISD::UREM, VT, Expand);
292 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
293 setOperationAction(ISD::ADDC, VT, Custom);
294 setOperationAction(ISD::ADDE, VT, Custom);
295 setOperationAction(ISD::SUBC, VT, Custom);
296 setOperationAction(ISD::SUBE, VT, Custom);
299 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
300 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
301 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
302 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
303 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
305 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
306 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
307 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
313 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
314 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
315 if (Subtarget->is64Bit())
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
318 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
319 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
320 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
321 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->is64Bit()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
502 // TargetInfo::X86_64ABIBuiltinVaList
503 setOperationAction(ISD::VAARG , MVT::Other, Custom);
504 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
506 // TargetInfo::CharPtrBuiltinVaList
507 setOperationAction(ISD::VAARG , MVT::Other, Expand);
508 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
511 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
512 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
514 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
516 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
520 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
521 // f32 and f64 use SSE.
522 // Set up the FP register classes.
523 addRegisterClass(MVT::f32, &X86::FR32RegClass);
524 addRegisterClass(MVT::f64, &X86::FR64RegClass);
526 // Use ANDPD to simulate FABS.
527 setOperationAction(ISD::FABS , MVT::f64, Custom);
528 setOperationAction(ISD::FABS , MVT::f32, Custom);
530 // Use XORP to simulate FNEG.
531 setOperationAction(ISD::FNEG , MVT::f64, Custom);
532 setOperationAction(ISD::FNEG , MVT::f32, Custom);
534 // Use ANDPD and ORPD to simulate FCOPYSIGN.
535 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
538 // Lower this to FGETSIGNx86 plus an AND.
539 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
542 // We don't support sin/cos/fmod
543 setOperationAction(ISD::FSIN , MVT::f64, Expand);
544 setOperationAction(ISD::FCOS , MVT::f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546 setOperationAction(ISD::FSIN , MVT::f32, Expand);
547 setOperationAction(ISD::FCOS , MVT::f32, Expand);
548 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
550 // Expand FP immediates into loads from the stack, except for the special
552 addLegalFPImmediate(APFloat(+0.0)); // xorpd
553 addLegalFPImmediate(APFloat(+0.0f)); // xorps
554 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
555 // Use SSE for f32, x87 for f64.
556 // Set up the FP register classes.
557 addRegisterClass(MVT::f32, &X86::FR32RegClass);
558 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
560 // Use ANDPS to simulate FABS.
561 setOperationAction(ISD::FABS , MVT::f32, Custom);
563 // Use XORP to simulate FNEG.
564 setOperationAction(ISD::FNEG , MVT::f32, Custom);
566 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
568 // Use ANDPS and ORPS to simulate FCOPYSIGN.
569 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572 // We don't support sin/cos/fmod
573 setOperationAction(ISD::FSIN , MVT::f32, Expand);
574 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
577 // Special cases we handle for FP constants.
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 addLegalFPImmediate(APFloat(+0.0)); // FLD0
580 addLegalFPImmediate(APFloat(+1.0)); // FLD1
581 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
584 if (!TM.Options.UnsafeFPMath) {
585 setOperationAction(ISD::FSIN , MVT::f64, Expand);
586 setOperationAction(ISD::FCOS , MVT::f64, Expand);
587 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
589 } else if (!TM.Options.UseSoftFloat) {
590 // f32 and f64 in x87.
591 // Set up the FP register classes.
592 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
595 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
596 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
600 if (!TM.Options.UnsafeFPMath) {
601 setOperationAction(ISD::FSIN , MVT::f64, Expand);
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f64, Expand);
604 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
608 addLegalFPImmediate(APFloat(+0.0)); // FLD0
609 addLegalFPImmediate(APFloat(+1.0)); // FLD1
610 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
618 // We don't support FMA.
619 setOperationAction(ISD::FMA, MVT::f64, Expand);
620 setOperationAction(ISD::FMA, MVT::f32, Expand);
622 // Long double always uses X87.
623 if (!TM.Options.UseSoftFloat) {
624 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
626 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
628 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629 addLegalFPImmediate(TmpFlt); // FLD0
631 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
634 APFloat TmpFlt2(+1.0);
635 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
637 addLegalFPImmediate(TmpFlt2); // FLD1
638 TmpFlt2.changeSign();
639 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
642 if (!TM.Options.UnsafeFPMath) {
643 setOperationAction(ISD::FSIN , MVT::f80, Expand);
644 setOperationAction(ISD::FCOS , MVT::f80, Expand);
645 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
648 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
650 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651 setOperationAction(ISD::FRINT, MVT::f80, Expand);
652 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653 setOperationAction(ISD::FMA, MVT::f80, Expand);
656 // Always use a library call for pow.
657 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
659 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
661 setOperationAction(ISD::FLOG, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP, MVT::f80, Expand);
665 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
669 // First set operation action for all vector types to either promote
670 // (for widening) or expand (for scalarization). Then we will selectively
671 // turn on ones that can be effectively codegen'd.
672 for (MVT VT : MVT::vector_valuetypes()) {
673 setOperationAction(ISD::ADD , VT, Expand);
674 setOperationAction(ISD::SUB , VT, Expand);
675 setOperationAction(ISD::FADD, VT, Expand);
676 setOperationAction(ISD::FNEG, VT, Expand);
677 setOperationAction(ISD::FSUB, VT, Expand);
678 setOperationAction(ISD::MUL , VT, Expand);
679 setOperationAction(ISD::FMUL, VT, Expand);
680 setOperationAction(ISD::SDIV, VT, Expand);
681 setOperationAction(ISD::UDIV, VT, Expand);
682 setOperationAction(ISD::FDIV, VT, Expand);
683 setOperationAction(ISD::SREM, VT, Expand);
684 setOperationAction(ISD::UREM, VT, Expand);
685 setOperationAction(ISD::LOAD, VT, Expand);
686 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691 setOperationAction(ISD::FABS, VT, Expand);
692 setOperationAction(ISD::FSIN, VT, Expand);
693 setOperationAction(ISD::FSINCOS, VT, Expand);
694 setOperationAction(ISD::FCOS, VT, Expand);
695 setOperationAction(ISD::FSINCOS, VT, Expand);
696 setOperationAction(ISD::FREM, VT, Expand);
697 setOperationAction(ISD::FMA, VT, Expand);
698 setOperationAction(ISD::FPOWI, VT, Expand);
699 setOperationAction(ISD::FSQRT, VT, Expand);
700 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701 setOperationAction(ISD::FFLOOR, VT, Expand);
702 setOperationAction(ISD::FCEIL, VT, Expand);
703 setOperationAction(ISD::FTRUNC, VT, Expand);
704 setOperationAction(ISD::FRINT, VT, Expand);
705 setOperationAction(ISD::FNEARBYINT, VT, Expand);
706 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707 setOperationAction(ISD::MULHS, VT, Expand);
708 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709 setOperationAction(ISD::MULHU, VT, Expand);
710 setOperationAction(ISD::SDIVREM, VT, Expand);
711 setOperationAction(ISD::UDIVREM, VT, Expand);
712 setOperationAction(ISD::FPOW, VT, Expand);
713 setOperationAction(ISD::CTPOP, VT, Expand);
714 setOperationAction(ISD::CTTZ, VT, Expand);
715 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716 setOperationAction(ISD::CTLZ, VT, Expand);
717 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718 setOperationAction(ISD::SHL, VT, Expand);
719 setOperationAction(ISD::SRA, VT, Expand);
720 setOperationAction(ISD::SRL, VT, Expand);
721 setOperationAction(ISD::ROTL, VT, Expand);
722 setOperationAction(ISD::ROTR, VT, Expand);
723 setOperationAction(ISD::BSWAP, VT, Expand);
724 setOperationAction(ISD::SETCC, VT, Expand);
725 setOperationAction(ISD::FLOG, VT, Expand);
726 setOperationAction(ISD::FLOG2, VT, Expand);
727 setOperationAction(ISD::FLOG10, VT, Expand);
728 setOperationAction(ISD::FEXP, VT, Expand);
729 setOperationAction(ISD::FEXP2, VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735 setOperationAction(ISD::TRUNCATE, VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739 setOperationAction(ISD::VSELECT, VT, Expand);
740 setOperationAction(ISD::SELECT_CC, VT, Expand);
741 for (MVT InnerVT : MVT::vector_valuetypes()) {
742 setTruncStoreAction(InnerVT, VT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
747 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748 // types, we have to deal with them whether we ask for Expansion or not.
749 // Setting Expand causes its own optimisation problems though, so leave
751 if (VT.getVectorElementType() == MVT::i1)
752 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
756 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
757 // with -msoft-float, disable use of MMX as well.
758 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
759 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
760 // No operations on x86mmx supported, everything uses intrinsics.
763 // MMX-sized vectors (other than x86mmx) are expected to be expanded
764 // into smaller operations.
765 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
766 setOperationAction(ISD::MULHS, MMXTy, Expand);
767 setOperationAction(ISD::AND, MMXTy, Expand);
768 setOperationAction(ISD::OR, MMXTy, Expand);
769 setOperationAction(ISD::XOR, MMXTy, Expand);
770 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
771 setOperationAction(ISD::SELECT, MMXTy, Expand);
772 setOperationAction(ISD::BITCAST, MMXTy, Expand);
774 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
776 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
777 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
779 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
780 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
781 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
782 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
783 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
784 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
785 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
786 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
787 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
788 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
789 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
791 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
792 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
795 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
796 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
798 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
799 // registers cannot be used even for integer operations.
800 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
801 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
802 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
803 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
805 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
806 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
807 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
808 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
809 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
810 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
811 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
812 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
813 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
814 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
815 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
816 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
817 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
818 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
819 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
821 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
822 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
823 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
824 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
825 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
826 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
827 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
829 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
830 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 // Only provide customized ctpop vector bit twiddling for vector types we
841 // know to perform better than using the popcnt instructions on each vector
842 // element. If popcnt isn't supported, always provide the custom version.
843 if (!Subtarget->hasPOPCNT()) {
844 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
845 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
848 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
849 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
850 MVT VT = (MVT::SimpleValueType)i;
851 // Do not attempt to custom lower non-power-of-2 vectors
852 if (!isPowerOf2_32(VT.getVectorNumElements()))
854 // Do not attempt to custom lower non-128-bit vectors
855 if (!VT.is128BitVector())
857 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
858 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
859 setOperationAction(ISD::VSELECT, VT, Custom);
860 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
863 // We support custom legalizing of sext and anyext loads for specific
864 // memory vector types which we can load as a scalar (or sequence of
865 // scalars) and extend in-register to a legal 128-bit vector type. For sext
866 // loads these must work with a single scalar load.
867 for (MVT VT : MVT::integer_vector_valuetypes()) {
868 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
869 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
870 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
871 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
879 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
880 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
881 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
882 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
883 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
884 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
885 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
886 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888 if (Subtarget->is64Bit()) {
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
890 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
893 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
894 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895 MVT VT = (MVT::SimpleValueType)i;
897 // Do not attempt to promote non-128-bit vectors
898 if (!VT.is128BitVector())
901 setOperationAction(ISD::AND, VT, Promote);
902 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
903 setOperationAction(ISD::OR, VT, Promote);
904 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
905 setOperationAction(ISD::XOR, VT, Promote);
906 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
907 setOperationAction(ISD::LOAD, VT, Promote);
908 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
909 setOperationAction(ISD::SELECT, VT, Promote);
910 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
913 // Custom lower v2i64 and v2f64 selects.
914 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
915 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
916 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
917 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
919 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
920 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
923 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
924 // As there is no 64-bit GPR available, we need build a special custom
925 // sequence to convert from v2i32 to v2f32.
926 if (!Subtarget->is64Bit())
927 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
929 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
930 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
932 for (MVT VT : MVT::fp_vector_valuetypes())
933 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
935 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
936 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
937 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
940 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
941 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
942 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
943 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
944 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
945 setOperationAction(ISD::FRINT, RoundedTy, Legal);
946 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
949 // FIXME: Do we need to handle scalar-to-vector here?
950 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
952 // We directly match byte blends in the backend as they match the VSELECT
954 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
956 // SSE41 brings specific instructions for doing vector sign extend even in
957 // cases where we don't have SRA.
958 for (MVT VT : MVT::integer_vector_valuetypes()) {
959 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
960 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
961 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
964 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
965 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
966 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
967 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
968 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
969 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
970 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
972 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
973 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
974 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
975 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
976 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
977 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979 // i8 and i16 vectors are custom because the source register and source
980 // source memory operand types are not the same width. f32 vectors are
981 // custom since the immediate controlling the insert encodes additional
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
984 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
993 // FIXME: these should be Legal, but that's only for the case where
994 // the index is constant. For now custom expand to deal with that.
995 if (Subtarget->is64Bit()) {
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1001 if (Subtarget->hasSSE2()) {
1002 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1003 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1005 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1006 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1008 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1009 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1011 // In the customized shift lowering, the legal cases in AVX2 will be
1013 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1014 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1016 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1017 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1019 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1022 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1023 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1024 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1025 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1026 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1027 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1028 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1030 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1031 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1032 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1034 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1035 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1036 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1037 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1038 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1039 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1040 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1041 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1042 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1043 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1045 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1047 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1058 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1060 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1061 // even though v8i16 is a legal type.
1062 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1063 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1064 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1066 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1067 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1068 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1070 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1071 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1073 for (MVT VT : MVT::fp_vector_valuetypes())
1074 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1076 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1077 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1079 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1083 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1085 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1086 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1087 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1088 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1090 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1091 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1092 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1094 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1095 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1096 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1097 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1098 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1099 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1100 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1101 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1102 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1103 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1104 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1105 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1107 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1108 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1109 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1110 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1111 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1112 setOperationAction(ISD::FMA, MVT::f32, Legal);
1113 setOperationAction(ISD::FMA, MVT::f64, Legal);
1116 if (Subtarget->hasInt256()) {
1117 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1118 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1119 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1120 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1122 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1123 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1124 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1125 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1127 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1128 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1129 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1130 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1132 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1133 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1134 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1135 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1137 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1138 // when we have a 256bit-wide blend with immediate.
1139 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1141 // Only provide customized ctpop vector bit twiddling for vector types we
1142 // know to perform better than using the popcnt instructions on each
1143 // vector element. If popcnt isn't supported, always provide the custom
1145 if (!Subtarget->hasPOPCNT())
1146 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1148 // Custom CTPOP always performs better on natively supported v8i32
1149 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1151 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1152 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1153 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1154 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1155 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1156 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1157 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1159 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1160 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1161 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1162 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1163 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1164 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1166 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1167 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1168 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1169 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1171 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1172 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1173 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1174 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1176 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1177 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1178 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1182 // In the customized shift lowering, the legal cases in AVX2 will be
1184 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1185 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1187 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1188 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1190 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1192 // Custom lower several nodes for 256-bit types.
1193 for (MVT VT : MVT::vector_valuetypes()) {
1194 if (VT.getScalarSizeInBits() >= 32) {
1195 setOperationAction(ISD::MLOAD, VT, Legal);
1196 setOperationAction(ISD::MSTORE, VT, Legal);
1198 // Extract subvector is special because the value type
1199 // (result) is 128-bit but the source is 256-bit wide.
1200 if (VT.is128BitVector()) {
1201 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1203 // Do not attempt to custom lower other non-256-bit vectors
1204 if (!VT.is256BitVector())
1207 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1208 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1209 setOperationAction(ISD::VSELECT, VT, Custom);
1210 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1211 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1212 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1213 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1214 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1217 if (Subtarget->hasInt256())
1218 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1221 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1222 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1223 MVT VT = (MVT::SimpleValueType)i;
1225 // Do not attempt to promote non-256-bit vectors
1226 if (!VT.is256BitVector())
1229 setOperationAction(ISD::AND, VT, Promote);
1230 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1231 setOperationAction(ISD::OR, VT, Promote);
1232 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1233 setOperationAction(ISD::XOR, VT, Promote);
1234 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1235 setOperationAction(ISD::LOAD, VT, Promote);
1236 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1237 setOperationAction(ISD::SELECT, VT, Promote);
1238 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1242 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1243 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1244 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1245 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1246 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1248 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1249 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1250 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1252 for (MVT VT : MVT::fp_vector_valuetypes())
1253 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1255 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1256 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1257 setOperationAction(ISD::XOR, MVT::i1, Legal);
1258 setOperationAction(ISD::OR, MVT::i1, Legal);
1259 setOperationAction(ISD::AND, MVT::i1, Legal);
1260 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1261 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1262 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1263 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1264 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1266 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1267 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1268 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1269 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1270 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1271 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1273 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1274 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1275 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1276 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1277 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1278 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1279 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1280 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1282 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1283 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1284 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1285 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1286 if (Subtarget->is64Bit()) {
1287 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1288 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1289 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1290 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1292 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1293 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1294 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1295 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1296 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1297 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1298 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1299 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1300 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1301 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1302 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1303 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1304 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1305 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1307 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1308 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1309 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1310 if (Subtarget->hasDQI()) {
1311 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1312 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1314 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1315 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1316 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1317 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1318 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1319 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1320 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1321 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1322 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1323 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1324 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1325 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1326 if (Subtarget->hasDQI()) {
1327 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1328 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1330 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1331 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1332 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1333 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1335 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1336 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1338 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1341 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1343 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1344 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1345 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1347 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1348 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1350 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1354 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1355 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1356 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1357 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1358 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1359 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1360 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1362 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1363 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1365 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1366 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1368 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1370 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1371 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1373 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1374 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1376 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1377 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1379 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1380 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1381 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1382 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1383 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1384 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1386 if (Subtarget->hasCDI()) {
1387 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1388 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1390 if (Subtarget->hasDQI()) {
1391 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1392 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1393 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1395 // Custom lower several nodes.
1396 for (MVT VT : MVT::vector_valuetypes()) {
1397 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1398 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1399 setOperationAction(ISD::MGATHER, VT, Custom);
1400 setOperationAction(ISD::MSCATTER, VT, Custom);
1402 // Extract subvector is special because the value type
1403 // (result) is 256/128-bit but the source is 512-bit wide.
1404 if (VT.is128BitVector() || VT.is256BitVector()) {
1405 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1407 if (VT.getVectorElementType() == MVT::i1)
1408 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1410 // Do not attempt to custom lower other non-512-bit vectors
1411 if (!VT.is512BitVector())
1414 if (EltSize >= 32) {
1415 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1416 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1417 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1418 setOperationAction(ISD::VSELECT, VT, Legal);
1419 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1420 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1421 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1422 setOperationAction(ISD::MLOAD, VT, Legal);
1423 setOperationAction(ISD::MSTORE, VT, Legal);
1426 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1427 MVT VT = (MVT::SimpleValueType)i;
1429 // Do not attempt to promote non-512-bit vectors.
1430 if (!VT.is512BitVector())
1433 setOperationAction(ISD::SELECT, VT, Promote);
1434 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1438 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1439 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1440 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1442 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1443 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1445 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1446 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1447 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1448 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1449 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1450 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1451 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1452 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1453 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1454 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1455 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1456 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1457 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1459 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1460 const MVT VT = (MVT::SimpleValueType)i;
1462 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1464 // Do not attempt to promote non-512-bit vectors.
1465 if (!VT.is512BitVector())
1469 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1470 setOperationAction(ISD::VSELECT, VT, Legal);
1475 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1476 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1477 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1479 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1480 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1481 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1482 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1483 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1484 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1486 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1487 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1488 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1489 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1490 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1491 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1494 // We want to custom lower some of our intrinsics.
1495 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1496 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1497 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1498 if (!Subtarget->is64Bit())
1499 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1501 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1502 // handle type legalization for these operations here.
1504 // FIXME: We really should do custom legalization for addition and
1505 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1506 // than generic legalization for 64-bit multiplication-with-overflow, though.
1507 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1508 // Add/Sub/Mul with overflow operations are custom lowered.
1510 setOperationAction(ISD::SADDO, VT, Custom);
1511 setOperationAction(ISD::UADDO, VT, Custom);
1512 setOperationAction(ISD::SSUBO, VT, Custom);
1513 setOperationAction(ISD::USUBO, VT, Custom);
1514 setOperationAction(ISD::SMULO, VT, Custom);
1515 setOperationAction(ISD::UMULO, VT, Custom);
1519 if (!Subtarget->is64Bit()) {
1520 // These libcalls are not available in 32-bit.
1521 setLibcallName(RTLIB::SHL_I128, nullptr);
1522 setLibcallName(RTLIB::SRL_I128, nullptr);
1523 setLibcallName(RTLIB::SRA_I128, nullptr);
1526 // Combine sin / cos into one node or libcall if possible.
1527 if (Subtarget->hasSinCos()) {
1528 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1529 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1530 if (Subtarget->isTargetDarwin()) {
1531 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1532 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1533 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1534 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1538 if (Subtarget->isTargetWin64()) {
1539 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1540 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1541 setOperationAction(ISD::SREM, MVT::i128, Custom);
1542 setOperationAction(ISD::UREM, MVT::i128, Custom);
1543 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1544 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1547 // We have target-specific dag combine patterns for the following nodes:
1548 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1549 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1550 setTargetDAGCombine(ISD::BITCAST);
1551 setTargetDAGCombine(ISD::VSELECT);
1552 setTargetDAGCombine(ISD::SELECT);
1553 setTargetDAGCombine(ISD::SHL);
1554 setTargetDAGCombine(ISD::SRA);
1555 setTargetDAGCombine(ISD::SRL);
1556 setTargetDAGCombine(ISD::OR);
1557 setTargetDAGCombine(ISD::AND);
1558 setTargetDAGCombine(ISD::ADD);
1559 setTargetDAGCombine(ISD::FADD);
1560 setTargetDAGCombine(ISD::FSUB);
1561 setTargetDAGCombine(ISD::FMA);
1562 setTargetDAGCombine(ISD::SUB);
1563 setTargetDAGCombine(ISD::LOAD);
1564 setTargetDAGCombine(ISD::MLOAD);
1565 setTargetDAGCombine(ISD::STORE);
1566 setTargetDAGCombine(ISD::MSTORE);
1567 setTargetDAGCombine(ISD::ZERO_EXTEND);
1568 setTargetDAGCombine(ISD::ANY_EXTEND);
1569 setTargetDAGCombine(ISD::SIGN_EXTEND);
1570 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1571 setTargetDAGCombine(ISD::TRUNCATE);
1572 setTargetDAGCombine(ISD::SINT_TO_FP);
1573 setTargetDAGCombine(ISD::SETCC);
1574 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1575 setTargetDAGCombine(ISD::BUILD_VECTOR);
1576 setTargetDAGCombine(ISD::MUL);
1577 setTargetDAGCombine(ISD::XOR);
1579 computeRegisterProperties(Subtarget->getRegisterInfo());
1581 // On Darwin, -Os means optimize for size without hurting performance,
1582 // do not reduce the limit.
1583 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1584 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1585 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1586 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1587 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1588 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1589 setPrefLoopAlignment(4); // 2^4 bytes.
1591 // Predictable cmov don't hurt on atom because it's in-order.
1592 PredictableSelectIsExpensive = !Subtarget->isAtom();
1593 EnableExtLdPromotion = true;
1594 setPrefFunctionAlignment(4); // 2^4 bytes.
1596 verifyIntrinsicTables();
1599 // This has so far only been implemented for 64-bit MachO.
1600 bool X86TargetLowering::useLoadStackGuardNode() const {
1601 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1604 TargetLoweringBase::LegalizeTypeAction
1605 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1606 if (ExperimentalVectorWideningLegalization &&
1607 VT.getVectorNumElements() != 1 &&
1608 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1609 return TypeWidenVector;
1611 return TargetLoweringBase::getPreferredVectorAction(VT);
1614 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1616 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1618 const unsigned NumElts = VT.getVectorNumElements();
1619 const EVT EltVT = VT.getVectorElementType();
1620 if (VT.is512BitVector()) {
1621 if (Subtarget->hasAVX512())
1622 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1623 EltVT == MVT::f32 || EltVT == MVT::f64)
1625 case 8: return MVT::v8i1;
1626 case 16: return MVT::v16i1;
1628 if (Subtarget->hasBWI())
1629 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1631 case 32: return MVT::v32i1;
1632 case 64: return MVT::v64i1;
1636 if (VT.is256BitVector() || VT.is128BitVector()) {
1637 if (Subtarget->hasVLX())
1638 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1639 EltVT == MVT::f32 || EltVT == MVT::f64)
1641 case 2: return MVT::v2i1;
1642 case 4: return MVT::v4i1;
1643 case 8: return MVT::v8i1;
1645 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1646 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1648 case 8: return MVT::v8i1;
1649 case 16: return MVT::v16i1;
1650 case 32: return MVT::v32i1;
1654 return VT.changeVectorElementTypeToInteger();
1657 /// Helper for getByValTypeAlignment to determine
1658 /// the desired ByVal argument alignment.
1659 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1662 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1663 if (VTy->getBitWidth() == 128)
1665 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1666 unsigned EltAlign = 0;
1667 getMaxByValAlign(ATy->getElementType(), EltAlign);
1668 if (EltAlign > MaxAlign)
1669 MaxAlign = EltAlign;
1670 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1671 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1672 unsigned EltAlign = 0;
1673 getMaxByValAlign(STy->getElementType(i), EltAlign);
1674 if (EltAlign > MaxAlign)
1675 MaxAlign = EltAlign;
1682 /// Return the desired alignment for ByVal aggregate
1683 /// function arguments in the caller parameter area. For X86, aggregates
1684 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1685 /// are at 4-byte boundaries.
1686 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1687 if (Subtarget->is64Bit()) {
1688 // Max of 8 and alignment of type.
1689 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1696 if (Subtarget->hasSSE1())
1697 getMaxByValAlign(Ty, Align);
1701 /// Returns the target specific optimal type for load
1702 /// and store operations as a result of memset, memcpy, and memmove
1703 /// lowering. If DstAlign is zero that means it's safe to destination
1704 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1705 /// means there isn't a need to check it against alignment requirement,
1706 /// probably because the source does not need to be loaded. If 'IsMemset' is
1707 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1708 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1709 /// source is constant so it does not need to be loaded.
1710 /// It returns EVT::Other if the type should be determined using generic
1711 /// target-independent logic.
1713 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1714 unsigned DstAlign, unsigned SrcAlign,
1715 bool IsMemset, bool ZeroMemset,
1717 MachineFunction &MF) const {
1718 const Function *F = MF.getFunction();
1719 if ((!IsMemset || ZeroMemset) &&
1720 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1722 (Subtarget->isUnalignedMemAccessFast() ||
1723 ((DstAlign == 0 || DstAlign >= 16) &&
1724 (SrcAlign == 0 || SrcAlign >= 16)))) {
1726 if (Subtarget->hasInt256())
1728 if (Subtarget->hasFp256())
1731 if (Subtarget->hasSSE2())
1733 if (Subtarget->hasSSE1())
1735 } else if (!MemcpyStrSrc && Size >= 8 &&
1736 !Subtarget->is64Bit() &&
1737 Subtarget->hasSSE2()) {
1738 // Do not use f64 to lower memcpy if source is string constant. It's
1739 // better to use i32 to avoid the loads.
1743 if (Subtarget->is64Bit() && Size >= 8)
1748 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1750 return X86ScalarSSEf32;
1751 else if (VT == MVT::f64)
1752 return X86ScalarSSEf64;
1757 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1762 *Fast = Subtarget->isUnalignedMemAccessFast();
1766 /// Return the entry encoding for a jump table in the
1767 /// current function. The returned value is a member of the
1768 /// MachineJumpTableInfo::JTEntryKind enum.
1769 unsigned X86TargetLowering::getJumpTableEncoding() const {
1770 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1772 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1773 Subtarget->isPICStyleGOT())
1774 return MachineJumpTableInfo::EK_Custom32;
1776 // Otherwise, use the normal jump table encoding heuristics.
1777 return TargetLowering::getJumpTableEncoding();
1781 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1782 const MachineBasicBlock *MBB,
1783 unsigned uid,MCContext &Ctx) const{
1784 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1785 Subtarget->isPICStyleGOT());
1786 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1788 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1789 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1792 /// Returns relocation base for the given PIC jumptable.
1793 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1794 SelectionDAG &DAG) const {
1795 if (!Subtarget->is64Bit())
1796 // This doesn't have SDLoc associated with it, but is not really the
1797 // same as a Register.
1798 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1802 /// This returns the relocation base for the given PIC jumptable,
1803 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1804 const MCExpr *X86TargetLowering::
1805 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1806 MCContext &Ctx) const {
1807 // X86-64 uses RIP relative addressing based on the jump table label.
1808 if (Subtarget->isPICStyleRIPRel())
1809 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1811 // Otherwise, the reference is relative to the PIC base.
1812 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1815 std::pair<const TargetRegisterClass *, uint8_t>
1816 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1818 const TargetRegisterClass *RRC = nullptr;
1820 switch (VT.SimpleTy) {
1822 return TargetLowering::findRepresentativeClass(TRI, VT);
1823 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1824 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1827 RRC = &X86::VR64RegClass;
1829 case MVT::f32: case MVT::f64:
1830 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1831 case MVT::v4f32: case MVT::v2f64:
1832 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1834 RRC = &X86::VR128RegClass;
1837 return std::make_pair(RRC, Cost);
1840 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1841 unsigned &Offset) const {
1842 if (!Subtarget->isTargetLinux())
1845 if (Subtarget->is64Bit()) {
1846 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1848 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1860 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1861 unsigned DestAS) const {
1862 assert(SrcAS != DestAS && "Expected different address spaces!");
1864 return SrcAS < 256 && DestAS < 256;
1867 //===----------------------------------------------------------------------===//
1868 // Return Value Calling Convention Implementation
1869 //===----------------------------------------------------------------------===//
1871 #include "X86GenCallingConv.inc"
1874 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1875 MachineFunction &MF, bool isVarArg,
1876 const SmallVectorImpl<ISD::OutputArg> &Outs,
1877 LLVMContext &Context) const {
1878 SmallVector<CCValAssign, 16> RVLocs;
1879 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1880 return CCInfo.CheckReturn(Outs, RetCC_X86);
1883 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1884 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1889 X86TargetLowering::LowerReturn(SDValue Chain,
1890 CallingConv::ID CallConv, bool isVarArg,
1891 const SmallVectorImpl<ISD::OutputArg> &Outs,
1892 const SmallVectorImpl<SDValue> &OutVals,
1893 SDLoc dl, SelectionDAG &DAG) const {
1894 MachineFunction &MF = DAG.getMachineFunction();
1895 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1897 SmallVector<CCValAssign, 16> RVLocs;
1898 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1899 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1902 SmallVector<SDValue, 6> RetOps;
1903 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1904 // Operand #1 = Bytes To Pop
1905 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
1908 // Copy the result values into the output registers.
1909 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1910 CCValAssign &VA = RVLocs[i];
1911 assert(VA.isRegLoc() && "Can only return in registers!");
1912 SDValue ValToCopy = OutVals[i];
1913 EVT ValVT = ValToCopy.getValueType();
1915 // Promote values to the appropriate types.
1916 if (VA.getLocInfo() == CCValAssign::SExt)
1917 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1918 else if (VA.getLocInfo() == CCValAssign::ZExt)
1919 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1920 else if (VA.getLocInfo() == CCValAssign::AExt) {
1921 if (ValVT.getScalarType() == MVT::i1)
1922 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1924 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1926 else if (VA.getLocInfo() == CCValAssign::BCvt)
1927 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1929 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1930 "Unexpected FP-extend for return value.");
1932 // If this is x86-64, and we disabled SSE, we can't return FP values,
1933 // or SSE or MMX vectors.
1934 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1935 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1936 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1937 report_fatal_error("SSE register return with SSE disabled");
1939 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1940 // llvm-gcc has never done it right and no one has noticed, so this
1941 // should be OK for now.
1942 if (ValVT == MVT::f64 &&
1943 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1944 report_fatal_error("SSE2 register return with SSE2 disabled");
1946 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1947 // the RET instruction and handled by the FP Stackifier.
1948 if (VA.getLocReg() == X86::FP0 ||
1949 VA.getLocReg() == X86::FP1) {
1950 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1951 // change the value to the FP stack register class.
1952 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1953 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1954 RetOps.push_back(ValToCopy);
1955 // Don't emit a copytoreg.
1959 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1960 // which is returned in RAX / RDX.
1961 if (Subtarget->is64Bit()) {
1962 if (ValVT == MVT::x86mmx) {
1963 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1964 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1965 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1967 // If we don't have SSE2 available, convert to v4f32 so the generated
1968 // register is legal.
1969 if (!Subtarget->hasSSE2())
1970 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1975 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1976 Flag = Chain.getValue(1);
1977 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1980 // The x86-64 ABIs require that for returning structs by value we copy
1981 // the sret argument into %rax/%eax (depending on ABI) for the return.
1982 // Win32 requires us to put the sret argument to %eax as well.
1983 // We saved the argument into a virtual register in the entry block,
1984 // so now we copy the value out and into %rax/%eax.
1986 // Checking Function.hasStructRetAttr() here is insufficient because the IR
1987 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
1988 // false, then an sret argument may be implicitly inserted in the SelDAG. In
1989 // either case FuncInfo->setSRetReturnReg() will have been called.
1990 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
1991 assert((Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) &&
1992 "No need for an sret register");
1993 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
1996 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1997 X86::RAX : X86::EAX;
1998 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1999 Flag = Chain.getValue(1);
2001 // RAX/EAX now acts like a return value.
2002 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2005 RetOps[0] = Chain; // Update chain.
2007 // Add the flag if we have it.
2009 RetOps.push_back(Flag);
2011 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2014 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2015 if (N->getNumValues() != 1)
2017 if (!N->hasNUsesOfValue(1, 0))
2020 SDValue TCChain = Chain;
2021 SDNode *Copy = *N->use_begin();
2022 if (Copy->getOpcode() == ISD::CopyToReg) {
2023 // If the copy has a glue operand, we conservatively assume it isn't safe to
2024 // perform a tail call.
2025 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2027 TCChain = Copy->getOperand(0);
2028 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2031 bool HasRet = false;
2032 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2034 if (UI->getOpcode() != X86ISD::RET_FLAG)
2036 // If we are returning more than one value, we can definitely
2037 // not make a tail call see PR19530
2038 if (UI->getNumOperands() > 4)
2040 if (UI->getNumOperands() == 4 &&
2041 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2054 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2055 ISD::NodeType ExtendKind) const {
2057 // TODO: Is this also valid on 32-bit?
2058 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2059 ReturnMVT = MVT::i8;
2061 ReturnMVT = MVT::i32;
2063 EVT MinVT = getRegisterType(Context, ReturnMVT);
2064 return VT.bitsLT(MinVT) ? MinVT : VT;
2067 /// Lower the result values of a call into the
2068 /// appropriate copies out of appropriate physical registers.
2071 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2072 CallingConv::ID CallConv, bool isVarArg,
2073 const SmallVectorImpl<ISD::InputArg> &Ins,
2074 SDLoc dl, SelectionDAG &DAG,
2075 SmallVectorImpl<SDValue> &InVals) const {
2077 // Assign locations to each value returned by this call.
2078 SmallVector<CCValAssign, 16> RVLocs;
2079 bool Is64Bit = Subtarget->is64Bit();
2080 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2082 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2084 // Copy all of the result registers out of their specified physreg.
2085 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2086 CCValAssign &VA = RVLocs[i];
2087 EVT CopyVT = VA.getLocVT();
2089 // If this is x86-64, and we disabled SSE, we can't return FP values
2090 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2091 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2092 report_fatal_error("SSE register return with SSE disabled");
2095 // If we prefer to use the value in xmm registers, copy it out as f80 and
2096 // use a truncate to move it from fp stack reg to xmm reg.
2097 bool RoundAfterCopy = false;
2098 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2099 isScalarFPTypeInSSEReg(VA.getValVT())) {
2101 RoundAfterCopy = (CopyVT != VA.getLocVT());
2104 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2105 CopyVT, InFlag).getValue(1);
2106 SDValue Val = Chain.getValue(0);
2109 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2110 // This truncation won't change the value.
2111 DAG.getIntPtrConstant(1, dl));
2113 InFlag = Chain.getValue(2);
2114 InVals.push_back(Val);
2120 //===----------------------------------------------------------------------===//
2121 // C & StdCall & Fast Calling Convention implementation
2122 //===----------------------------------------------------------------------===//
2123 // StdCall calling convention seems to be standard for many Windows' API
2124 // routines and around. It differs from C calling convention just a little:
2125 // callee should clean up the stack, not caller. Symbols should be also
2126 // decorated in some fancy way :) It doesn't support any vector arguments.
2127 // For info on fast calling convention see Fast Calling Convention (tail call)
2128 // implementation LowerX86_32FastCCCallTo.
2130 /// CallIsStructReturn - Determines whether a call uses struct return
2132 enum StructReturnType {
2137 static StructReturnType
2138 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2140 return NotStructReturn;
2142 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2143 if (!Flags.isSRet())
2144 return NotStructReturn;
2145 if (Flags.isInReg())
2146 return RegStructReturn;
2147 return StackStructReturn;
2150 /// Determines whether a function uses struct return semantics.
2151 static StructReturnType
2152 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2154 return NotStructReturn;
2156 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2157 if (!Flags.isSRet())
2158 return NotStructReturn;
2159 if (Flags.isInReg())
2160 return RegStructReturn;
2161 return StackStructReturn;
2164 /// Make a copy of an aggregate at address specified by "Src" to address
2165 /// "Dst" with size and alignment information specified by the specific
2166 /// parameter attribute. The copy will be passed as a byval function parameter.
2168 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2169 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2171 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2173 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2174 /*isVolatile*/false, /*AlwaysInline=*/true,
2175 /*isTailCall*/false,
2176 MachinePointerInfo(), MachinePointerInfo());
2179 /// Return true if the calling convention is one that
2180 /// supports tail call optimization.
2181 static bool IsTailCallConvention(CallingConv::ID CC) {
2182 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2183 CC == CallingConv::HiPE);
2186 /// \brief Return true if the calling convention is a C calling convention.
2187 static bool IsCCallConvention(CallingConv::ID CC) {
2188 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2189 CC == CallingConv::X86_64_SysV);
2192 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2193 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2197 CallingConv::ID CalleeCC = CS.getCallingConv();
2198 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2204 /// Return true if the function is being made into
2205 /// a tailcall target by changing its ABI.
2206 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2207 bool GuaranteedTailCallOpt) {
2208 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2212 X86TargetLowering::LowerMemArgument(SDValue Chain,
2213 CallingConv::ID CallConv,
2214 const SmallVectorImpl<ISD::InputArg> &Ins,
2215 SDLoc dl, SelectionDAG &DAG,
2216 const CCValAssign &VA,
2217 MachineFrameInfo *MFI,
2219 // Create the nodes corresponding to a load from this parameter slot.
2220 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2221 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2222 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2223 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2226 // If value is passed by pointer we have address passed instead of the value
2228 if (VA.getLocInfo() == CCValAssign::Indirect)
2229 ValVT = VA.getLocVT();
2231 ValVT = VA.getValVT();
2233 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2234 // changed with more analysis.
2235 // In case of tail call optimization mark all arguments mutable. Since they
2236 // could be overwritten by lowering of arguments in case of a tail call.
2237 if (Flags.isByVal()) {
2238 unsigned Bytes = Flags.getByValSize();
2239 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2240 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2241 return DAG.getFrameIndex(FI, getPointerTy());
2243 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2244 VA.getLocMemOffset(), isImmutable);
2245 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2246 return DAG.getLoad(ValVT, dl, Chain, FIN,
2247 MachinePointerInfo::getFixedStack(FI),
2248 false, false, false, 0);
2252 // FIXME: Get this from tablegen.
2253 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2254 const X86Subtarget *Subtarget) {
2255 assert(Subtarget->is64Bit());
2257 if (Subtarget->isCallingConvWin64(CallConv)) {
2258 static const MCPhysReg GPR64ArgRegsWin64[] = {
2259 X86::RCX, X86::RDX, X86::R8, X86::R9
2261 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2264 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2265 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2267 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2270 // FIXME: Get this from tablegen.
2271 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2272 CallingConv::ID CallConv,
2273 const X86Subtarget *Subtarget) {
2274 assert(Subtarget->is64Bit());
2275 if (Subtarget->isCallingConvWin64(CallConv)) {
2276 // The XMM registers which might contain var arg parameters are shadowed
2277 // in their paired GPR. So we only need to save the GPR to their home
2279 // TODO: __vectorcall will change this.
2283 const Function *Fn = MF.getFunction();
2284 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2285 bool isSoftFloat = MF.getTarget().Options.UseSoftFloat;
2286 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2287 "SSE register cannot be used when SSE is disabled!");
2288 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2289 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2293 static const MCPhysReg XMMArgRegs64Bit[] = {
2294 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2295 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2297 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2301 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2302 CallingConv::ID CallConv,
2304 const SmallVectorImpl<ISD::InputArg> &Ins,
2307 SmallVectorImpl<SDValue> &InVals)
2309 MachineFunction &MF = DAG.getMachineFunction();
2310 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2311 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2313 const Function* Fn = MF.getFunction();
2314 if (Fn->hasExternalLinkage() &&
2315 Subtarget->isTargetCygMing() &&
2316 Fn->getName() == "main")
2317 FuncInfo->setForceFramePointer(true);
2319 MachineFrameInfo *MFI = MF.getFrameInfo();
2320 bool Is64Bit = Subtarget->is64Bit();
2321 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2323 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2324 "Var args not supported with calling convention fastcc, ghc or hipe");
2326 // Assign locations to all of the incoming arguments.
2327 SmallVector<CCValAssign, 16> ArgLocs;
2328 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2330 // Allocate shadow area for Win64
2332 CCInfo.AllocateStack(32, 8);
2334 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2336 unsigned LastVal = ~0U;
2338 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339 CCValAssign &VA = ArgLocs[i];
2340 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2342 assert(VA.getValNo() != LastVal &&
2343 "Don't support value assigned to multiple locs yet");
2345 LastVal = VA.getValNo();
2347 if (VA.isRegLoc()) {
2348 EVT RegVT = VA.getLocVT();
2349 const TargetRegisterClass *RC;
2350 if (RegVT == MVT::i32)
2351 RC = &X86::GR32RegClass;
2352 else if (Is64Bit && RegVT == MVT::i64)
2353 RC = &X86::GR64RegClass;
2354 else if (RegVT == MVT::f32)
2355 RC = &X86::FR32RegClass;
2356 else if (RegVT == MVT::f64)
2357 RC = &X86::FR64RegClass;
2358 else if (RegVT.is512BitVector())
2359 RC = &X86::VR512RegClass;
2360 else if (RegVT.is256BitVector())
2361 RC = &X86::VR256RegClass;
2362 else if (RegVT.is128BitVector())
2363 RC = &X86::VR128RegClass;
2364 else if (RegVT == MVT::x86mmx)
2365 RC = &X86::VR64RegClass;
2366 else if (RegVT == MVT::i1)
2367 RC = &X86::VK1RegClass;
2368 else if (RegVT == MVT::v8i1)
2369 RC = &X86::VK8RegClass;
2370 else if (RegVT == MVT::v16i1)
2371 RC = &X86::VK16RegClass;
2372 else if (RegVT == MVT::v32i1)
2373 RC = &X86::VK32RegClass;
2374 else if (RegVT == MVT::v64i1)
2375 RC = &X86::VK64RegClass;
2377 llvm_unreachable("Unknown argument type!");
2379 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2380 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2382 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2383 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2385 if (VA.getLocInfo() == CCValAssign::SExt)
2386 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2387 DAG.getValueType(VA.getValVT()));
2388 else if (VA.getLocInfo() == CCValAssign::ZExt)
2389 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2390 DAG.getValueType(VA.getValVT()));
2391 else if (VA.getLocInfo() == CCValAssign::BCvt)
2392 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2394 if (VA.isExtInLoc()) {
2395 // Handle MMX values passed in XMM regs.
2396 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2397 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2399 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2402 assert(VA.isMemLoc());
2403 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2406 // If value is passed via pointer - do a load.
2407 if (VA.getLocInfo() == CCValAssign::Indirect)
2408 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2409 MachinePointerInfo(), false, false, false, 0);
2411 InVals.push_back(ArgValue);
2414 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416 // The x86-64 ABIs require that for returning structs by value we copy
2417 // the sret argument into %rax/%eax (depending on ABI) for the return.
2418 // Win32 requires us to put the sret argument to %eax as well.
2419 // Save the argument into a virtual register so that we can access it
2420 // from the return points.
2421 if (Ins[i].Flags.isSRet()) {
2422 unsigned Reg = FuncInfo->getSRetReturnReg();
2424 MVT PtrTy = getPointerTy();
2425 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2426 FuncInfo->setSRetReturnReg(Reg);
2428 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2429 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2435 unsigned StackSize = CCInfo.getNextStackOffset();
2436 // Align stack specially for tail calls.
2437 if (FuncIsMadeTailCallSafe(CallConv,
2438 MF.getTarget().Options.GuaranteedTailCallOpt))
2439 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2441 // If the function takes variable number of arguments, make a frame index for
2442 // the start of the first vararg value... for expansion of llvm.va_start. We
2443 // can skip this if there are no va_start calls.
2444 if (MFI->hasVAStart() &&
2445 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2446 CallConv != CallingConv::X86_ThisCall))) {
2447 FuncInfo->setVarArgsFrameIndex(
2448 MFI->CreateFixedObject(1, StackSize, true));
2451 MachineModuleInfo &MMI = MF.getMMI();
2452 const Function *WinEHParent = nullptr;
2453 if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2454 WinEHParent = MMI.getWinEHParent(Fn);
2455 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2456 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2458 // Figure out if XMM registers are in use.
2459 assert(!(MF.getTarget().Options.UseSoftFloat &&
2460 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2461 "SSE register cannot be used when SSE is disabled!");
2463 // 64-bit calling conventions support varargs and register parameters, so we
2464 // have to do extra work to spill them in the prologue.
2465 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2466 // Find the first unallocated argument registers.
2467 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2468 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2469 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2470 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2471 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2472 "SSE register cannot be used when SSE is disabled!");
2474 // Gather all the live in physical registers.
2475 SmallVector<SDValue, 6> LiveGPRs;
2476 SmallVector<SDValue, 8> LiveXMMRegs;
2478 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2479 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2481 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2483 if (!ArgXMMs.empty()) {
2484 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2485 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2486 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2487 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2488 LiveXMMRegs.push_back(
2489 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2494 // Get to the caller-allocated home save location. Add 8 to account
2495 // for the return address.
2496 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2497 FuncInfo->setRegSaveFrameIndex(
2498 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2499 // Fixup to set vararg frame on shadow area (4 x i64).
2501 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2503 // For X86-64, if there are vararg parameters that are passed via
2504 // registers, then we must store them to their spots on the stack so
2505 // they may be loaded by deferencing the result of va_next.
2506 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2507 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2508 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2509 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2512 // Store the integer parameter registers.
2513 SmallVector<SDValue, 8> MemOps;
2514 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2516 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2517 for (SDValue Val : LiveGPRs) {
2518 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2519 DAG.getIntPtrConstant(Offset, dl));
2521 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2522 MachinePointerInfo::getFixedStack(
2523 FuncInfo->getRegSaveFrameIndex(), Offset),
2525 MemOps.push_back(Store);
2529 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2530 // Now store the XMM (fp + vector) parameter registers.
2531 SmallVector<SDValue, 12> SaveXMMOps;
2532 SaveXMMOps.push_back(Chain);
2533 SaveXMMOps.push_back(ALVal);
2534 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2535 FuncInfo->getRegSaveFrameIndex(), dl));
2536 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2537 FuncInfo->getVarArgsFPOffset(), dl));
2538 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2540 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2541 MVT::Other, SaveXMMOps));
2544 if (!MemOps.empty())
2545 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2546 } else if (IsWinEHOutlined) {
2547 // Get to the caller-allocated home save location. Add 8 to account
2548 // for the return address.
2549 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2550 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2551 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2553 MMI.getWinEHFuncInfo(Fn)
2554 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2555 FuncInfo->getRegSaveFrameIndex();
2557 // Store the second integer parameter (rdx) into rsp+16 relative to the
2558 // stack pointer at the entry of the function.
2560 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2561 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2562 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2563 Chain = DAG.getStore(
2564 Val.getValue(1), dl, Val, RSFIN,
2565 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2566 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2569 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2570 // Find the largest legal vector type.
2571 MVT VecVT = MVT::Other;
2572 // FIXME: Only some x86_32 calling conventions support AVX512.
2573 if (Subtarget->hasAVX512() &&
2574 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2575 CallConv == CallingConv::Intel_OCL_BI)))
2576 VecVT = MVT::v16f32;
2577 else if (Subtarget->hasAVX())
2579 else if (Subtarget->hasSSE2())
2582 // We forward some GPRs and some vector types.
2583 SmallVector<MVT, 2> RegParmTypes;
2584 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2585 RegParmTypes.push_back(IntVT);
2586 if (VecVT != MVT::Other)
2587 RegParmTypes.push_back(VecVT);
2589 // Compute the set of forwarded registers. The rest are scratch.
2590 SmallVectorImpl<ForwardedRegister> &Forwards =
2591 FuncInfo->getForwardedMustTailRegParms();
2592 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2594 // Conservatively forward AL on x86_64, since it might be used for varargs.
2595 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2596 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2597 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2600 // Copy all forwards from physical to virtual registers.
2601 for (ForwardedRegister &F : Forwards) {
2602 // FIXME: Can we use a less constrained schedule?
2603 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2604 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2605 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2609 // Some CCs need callee pop.
2610 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2611 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2612 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2614 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2615 // If this is an sret function, the return should pop the hidden pointer.
2616 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2617 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2618 argsAreStructReturn(Ins) == StackStructReturn)
2619 FuncInfo->setBytesToPopOnReturn(4);
2623 // RegSaveFrameIndex is X86-64 only.
2624 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2625 if (CallConv == CallingConv::X86_FastCall ||
2626 CallConv == CallingConv::X86_ThisCall)
2627 // fastcc functions can't have varargs.
2628 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2631 FuncInfo->setArgumentStackSize(StackSize);
2633 if (IsWinEHParent) {
2634 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2635 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2636 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2637 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2638 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2639 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2640 /*isVolatile=*/true,
2641 /*isNonTemporal=*/false, /*Alignment=*/0);
2648 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2649 SDValue StackPtr, SDValue Arg,
2650 SDLoc dl, SelectionDAG &DAG,
2651 const CCValAssign &VA,
2652 ISD::ArgFlagsTy Flags) const {
2653 unsigned LocMemOffset = VA.getLocMemOffset();
2654 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2655 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2656 if (Flags.isByVal())
2657 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2659 return DAG.getStore(Chain, dl, Arg, PtrOff,
2660 MachinePointerInfo::getStack(LocMemOffset),
2664 /// Emit a load of return address if tail call
2665 /// optimization is performed and it is required.
2667 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2668 SDValue &OutRetAddr, SDValue Chain,
2669 bool IsTailCall, bool Is64Bit,
2670 int FPDiff, SDLoc dl) const {
2671 // Adjust the Return address stack slot.
2672 EVT VT = getPointerTy();
2673 OutRetAddr = getReturnAddressFrameIndex(DAG);
2675 // Load the "old" Return address.
2676 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2677 false, false, false, 0);
2678 return SDValue(OutRetAddr.getNode(), 1);
2681 /// Emit a store of the return address if tail call
2682 /// optimization is performed and it is required (FPDiff!=0).
2683 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2684 SDValue Chain, SDValue RetAddrFrIdx,
2685 EVT PtrVT, unsigned SlotSize,
2686 int FPDiff, SDLoc dl) {
2687 // Store the return address to the appropriate stack slot.
2688 if (!FPDiff) return Chain;
2689 // Calculate the new stack slot for the return address.
2690 int NewReturnAddrFI =
2691 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2693 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2694 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2695 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2701 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2702 SmallVectorImpl<SDValue> &InVals) const {
2703 SelectionDAG &DAG = CLI.DAG;
2705 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2706 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2707 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2708 SDValue Chain = CLI.Chain;
2709 SDValue Callee = CLI.Callee;
2710 CallingConv::ID CallConv = CLI.CallConv;
2711 bool &isTailCall = CLI.IsTailCall;
2712 bool isVarArg = CLI.IsVarArg;
2714 MachineFunction &MF = DAG.getMachineFunction();
2715 bool Is64Bit = Subtarget->is64Bit();
2716 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2717 StructReturnType SR = callIsStructReturn(Outs);
2718 bool IsSibcall = false;
2719 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2721 if (MF.getTarget().Options.DisableTailCalls)
2724 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2726 // Force this to be a tail call. The verifier rules are enough to ensure
2727 // that we can lower this successfully without moving the return address
2730 } else if (isTailCall) {
2731 // Check if it's really possible to do a tail call.
2732 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2733 isVarArg, SR != NotStructReturn,
2734 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2735 Outs, OutVals, Ins, DAG);
2737 // Sibcalls are automatically detected tailcalls which do not require
2739 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2746 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2747 "Var args not supported with calling convention fastcc, ghc or hipe");
2749 // Analyze operands of the call, assigning locations to each operand.
2750 SmallVector<CCValAssign, 16> ArgLocs;
2751 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2753 // Allocate shadow area for Win64
2755 CCInfo.AllocateStack(32, 8);
2757 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2759 // Get a count of how many bytes are to be pushed on the stack.
2760 unsigned NumBytes = CCInfo.getNextStackOffset();
2762 // This is a sibcall. The memory operands are available in caller's
2763 // own caller's stack.
2765 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2766 IsTailCallConvention(CallConv))
2767 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2770 if (isTailCall && !IsSibcall && !IsMustTail) {
2771 // Lower arguments at fp - stackoffset + fpdiff.
2772 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2774 FPDiff = NumBytesCallerPushed - NumBytes;
2776 // Set the delta of movement of the returnaddr stackslot.
2777 // But only set if delta is greater than previous delta.
2778 if (FPDiff < X86Info->getTCReturnAddrDelta())
2779 X86Info->setTCReturnAddrDelta(FPDiff);
2782 unsigned NumBytesToPush = NumBytes;
2783 unsigned NumBytesToPop = NumBytes;
2785 // If we have an inalloca argument, all stack space has already been allocated
2786 // for us and be right at the top of the stack. We don't support multiple
2787 // arguments passed in memory when using inalloca.
2788 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2790 if (!ArgLocs.back().isMemLoc())
2791 report_fatal_error("cannot use inalloca attribute on a register "
2793 if (ArgLocs.back().getLocMemOffset() != 0)
2794 report_fatal_error("any parameter with the inalloca attribute must be "
2795 "the only memory argument");
2799 Chain = DAG.getCALLSEQ_START(
2800 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2802 SDValue RetAddrFrIdx;
2803 // Load return address for tail calls.
2804 if (isTailCall && FPDiff)
2805 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2806 Is64Bit, FPDiff, dl);
2808 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2809 SmallVector<SDValue, 8> MemOpChains;
2812 // Walk the register/memloc assignments, inserting copies/loads. In the case
2813 // of tail call optimization arguments are handle later.
2814 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2815 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2816 // Skip inalloca arguments, they have already been written.
2817 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2818 if (Flags.isInAlloca())
2821 CCValAssign &VA = ArgLocs[i];
2822 EVT RegVT = VA.getLocVT();
2823 SDValue Arg = OutVals[i];
2824 bool isByVal = Flags.isByVal();
2826 // Promote the value if needed.
2827 switch (VA.getLocInfo()) {
2828 default: llvm_unreachable("Unknown loc info!");
2829 case CCValAssign::Full: break;
2830 case CCValAssign::SExt:
2831 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2833 case CCValAssign::ZExt:
2834 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2836 case CCValAssign::AExt:
2837 if (Arg.getValueType().getScalarType() == MVT::i1)
2838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2839 else if (RegVT.is128BitVector()) {
2840 // Special case: passing MMX values in XMM registers.
2841 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2842 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2843 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2845 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2847 case CCValAssign::BCvt:
2848 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2850 case CCValAssign::Indirect: {
2851 // Store the argument.
2852 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2853 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2854 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2855 MachinePointerInfo::getFixedStack(FI),
2862 if (VA.isRegLoc()) {
2863 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2864 if (isVarArg && IsWin64) {
2865 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2866 // shadow reg if callee is a varargs function.
2867 unsigned ShadowReg = 0;
2868 switch (VA.getLocReg()) {
2869 case X86::XMM0: ShadowReg = X86::RCX; break;
2870 case X86::XMM1: ShadowReg = X86::RDX; break;
2871 case X86::XMM2: ShadowReg = X86::R8; break;
2872 case X86::XMM3: ShadowReg = X86::R9; break;
2875 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2877 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2878 assert(VA.isMemLoc());
2879 if (!StackPtr.getNode())
2880 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2882 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2883 dl, DAG, VA, Flags));
2887 if (!MemOpChains.empty())
2888 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2890 if (Subtarget->isPICStyleGOT()) {
2891 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2894 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2895 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2897 // If we are tail calling and generating PIC/GOT style code load the
2898 // address of the callee into ECX. The value in ecx is used as target of
2899 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2900 // for tail calls on PIC/GOT architectures. Normally we would just put the
2901 // address of GOT into ebx and then call target@PLT. But for tail calls
2902 // ebx would be restored (since ebx is callee saved) before jumping to the
2905 // Note: The actual moving to ECX is done further down.
2906 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2907 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2908 !G->getGlobal()->hasProtectedVisibility())
2909 Callee = LowerGlobalAddress(Callee, DAG);
2910 else if (isa<ExternalSymbolSDNode>(Callee))
2911 Callee = LowerExternalSymbol(Callee, DAG);
2915 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2916 // From AMD64 ABI document:
2917 // For calls that may call functions that use varargs or stdargs
2918 // (prototype-less calls or calls to functions containing ellipsis (...) in
2919 // the declaration) %al is used as hidden argument to specify the number
2920 // of SSE registers used. The contents of %al do not need to match exactly
2921 // the number of registers, but must be an ubound on the number of SSE
2922 // registers used and is in the range 0 - 8 inclusive.
2924 // Count the number of XMM registers allocated.
2925 static const MCPhysReg XMMArgRegs[] = {
2926 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2927 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2929 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
2930 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2931 && "SSE registers cannot be used when SSE is disabled");
2933 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2934 DAG.getConstant(NumXMMRegs, dl,
2938 if (isVarArg && IsMustTail) {
2939 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2940 for (const auto &F : Forwards) {
2941 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2942 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2946 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2947 // don't need this because the eligibility check rejects calls that require
2948 // shuffling arguments passed in memory.
2949 if (!IsSibcall && isTailCall) {
2950 // Force all the incoming stack arguments to be loaded from the stack
2951 // before any new outgoing arguments are stored to the stack, because the
2952 // outgoing stack slots may alias the incoming argument stack slots, and
2953 // the alias isn't otherwise explicit. This is slightly more conservative
2954 // than necessary, because it means that each store effectively depends
2955 // on every argument instead of just those arguments it would clobber.
2956 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2958 SmallVector<SDValue, 8> MemOpChains2;
2961 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2962 CCValAssign &VA = ArgLocs[i];
2965 assert(VA.isMemLoc());
2966 SDValue Arg = OutVals[i];
2967 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2968 // Skip inalloca arguments. They don't require any work.
2969 if (Flags.isInAlloca())
2971 // Create frame index.
2972 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2973 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2974 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2975 FIN = DAG.getFrameIndex(FI, getPointerTy());
2977 if (Flags.isByVal()) {
2978 // Copy relative to framepointer.
2979 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
2980 if (!StackPtr.getNode())
2981 StackPtr = DAG.getCopyFromReg(Chain, dl,
2982 RegInfo->getStackRegister(),
2984 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2986 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2990 // Store relative to framepointer.
2991 MemOpChains2.push_back(
2992 DAG.getStore(ArgChain, dl, Arg, FIN,
2993 MachinePointerInfo::getFixedStack(FI),
2998 if (!MemOpChains2.empty())
2999 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3001 // Store the return address to the appropriate stack slot.
3002 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3003 getPointerTy(), RegInfo->getSlotSize(),
3007 // Build a sequence of copy-to-reg nodes chained together with token chain
3008 // and flag operands which copy the outgoing args into registers.
3010 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3011 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3012 RegsToPass[i].second, InFlag);
3013 InFlag = Chain.getValue(1);
3016 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3017 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3018 // In the 64-bit large code model, we have to make all calls
3019 // through a register, since the call instruction's 32-bit
3020 // pc-relative offset may not be large enough to hold the whole
3022 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3023 // If the callee is a GlobalAddress node (quite common, every direct call
3024 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3026 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3028 // We should use extra load for direct calls to dllimported functions in
3030 const GlobalValue *GV = G->getGlobal();
3031 if (!GV->hasDLLImportStorageClass()) {
3032 unsigned char OpFlags = 0;
3033 bool ExtraLoad = false;
3034 unsigned WrapperKind = ISD::DELETED_NODE;
3036 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3037 // external symbols most go through the PLT in PIC mode. If the symbol
3038 // has hidden or protected visibility, or if it is static or local, then
3039 // we don't need to use the PLT - we can directly call it.
3040 if (Subtarget->isTargetELF() &&
3041 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3042 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3043 OpFlags = X86II::MO_PLT;
3044 } else if (Subtarget->isPICStyleStubAny() &&
3045 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3046 (!Subtarget->getTargetTriple().isMacOSX() ||
3047 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3048 // PC-relative references to external symbols should go through $stub,
3049 // unless we're building with the leopard linker or later, which
3050 // automatically synthesizes these stubs.
3051 OpFlags = X86II::MO_DARWIN_STUB;
3052 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3053 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3054 // If the function is marked as non-lazy, generate an indirect call
3055 // which loads from the GOT directly. This avoids runtime overhead
3056 // at the cost of eager binding (and one extra byte of encoding).
3057 OpFlags = X86II::MO_GOTPCREL;
3058 WrapperKind = X86ISD::WrapperRIP;
3062 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3063 G->getOffset(), OpFlags);
3065 // Add a wrapper if needed.
3066 if (WrapperKind != ISD::DELETED_NODE)
3067 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3068 // Add extra indirection if needed.
3070 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3071 MachinePointerInfo::getGOT(),
3072 false, false, false, 0);
3074 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3075 unsigned char OpFlags = 0;
3077 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3078 // external symbols should go through the PLT.
3079 if (Subtarget->isTargetELF() &&
3080 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3081 OpFlags = X86II::MO_PLT;
3082 } else if (Subtarget->isPICStyleStubAny() &&
3083 (!Subtarget->getTargetTriple().isMacOSX() ||
3084 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3085 // PC-relative references to external symbols should go through $stub,
3086 // unless we're building with the leopard linker or later, which
3087 // automatically synthesizes these stubs.
3088 OpFlags = X86II::MO_DARWIN_STUB;
3091 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3093 } else if (Subtarget->isTarget64BitILP32() &&
3094 Callee->getValueType(0) == MVT::i32) {
3095 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3096 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3099 // Returns a chain & a flag for retval copy to use.
3100 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3101 SmallVector<SDValue, 8> Ops;
3103 if (!IsSibcall && isTailCall) {
3104 Chain = DAG.getCALLSEQ_END(Chain,
3105 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3106 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3107 InFlag = Chain.getValue(1);
3110 Ops.push_back(Chain);
3111 Ops.push_back(Callee);
3114 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3116 // Add argument registers to the end of the list so that they are known live
3118 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3119 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3120 RegsToPass[i].second.getValueType()));
3122 // Add a register mask operand representing the call-preserved registers.
3123 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3124 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3125 assert(Mask && "Missing call preserved mask for calling convention");
3126 Ops.push_back(DAG.getRegisterMask(Mask));
3128 if (InFlag.getNode())
3129 Ops.push_back(InFlag);
3133 //// If this is the first return lowered for this function, add the regs
3134 //// to the liveout set for the function.
3135 // This isn't right, although it's probably harmless on x86; liveouts
3136 // should be computed from returns not tail calls. Consider a void
3137 // function making a tail call to a function returning int.
3138 MF.getFrameInfo()->setHasTailCall();
3139 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3142 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3143 InFlag = Chain.getValue(1);
3145 // Create the CALLSEQ_END node.
3146 unsigned NumBytesForCalleeToPop;
3147 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3148 DAG.getTarget().Options.GuaranteedTailCallOpt))
3149 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3150 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3151 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3152 SR == StackStructReturn)
3153 // If this is a call to a struct-return function, the callee
3154 // pops the hidden struct pointer, so we have to push it back.
3155 // This is common for Darwin/X86, Linux & Mingw32 targets.
3156 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3157 NumBytesForCalleeToPop = 4;
3159 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3161 // Returns a flag for retval copy to use.
3163 Chain = DAG.getCALLSEQ_END(Chain,
3164 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3165 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3168 InFlag = Chain.getValue(1);
3171 // Handle result values, copying them out of physregs into vregs that we
3173 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3174 Ins, dl, DAG, InVals);
3177 //===----------------------------------------------------------------------===//
3178 // Fast Calling Convention (tail call) implementation
3179 //===----------------------------------------------------------------------===//
3181 // Like std call, callee cleans arguments, convention except that ECX is
3182 // reserved for storing the tail called function address. Only 2 registers are
3183 // free for argument passing (inreg). Tail call optimization is performed
3185 // * tailcallopt is enabled
3186 // * caller/callee are fastcc
3187 // On X86_64 architecture with GOT-style position independent code only local
3188 // (within module) calls are supported at the moment.
3189 // To keep the stack aligned according to platform abi the function
3190 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3191 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3192 // If a tail called function callee has more arguments than the caller the
3193 // caller needs to make sure that there is room to move the RETADDR to. This is
3194 // achieved by reserving an area the size of the argument delta right after the
3195 // original RETADDR, but before the saved framepointer or the spilled registers
3196 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3208 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3209 /// for a 16 byte align requirement.
3211 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3212 SelectionDAG& DAG) const {
3213 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3214 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3215 unsigned StackAlignment = TFI.getStackAlignment();
3216 uint64_t AlignMask = StackAlignment - 1;
3217 int64_t Offset = StackSize;
3218 unsigned SlotSize = RegInfo->getSlotSize();
3219 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3220 // Number smaller than 12 so just add the difference.
3221 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3223 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3224 Offset = ((~AlignMask) & Offset) + StackAlignment +
3225 (StackAlignment-SlotSize);
3230 /// MatchingStackOffset - Return true if the given stack call argument is
3231 /// already available in the same position (relatively) of the caller's
3232 /// incoming argument stack.
3234 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3235 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3236 const X86InstrInfo *TII) {
3237 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3239 if (Arg.getOpcode() == ISD::CopyFromReg) {
3240 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3241 if (!TargetRegisterInfo::isVirtualRegister(VR))
3243 MachineInstr *Def = MRI->getVRegDef(VR);
3246 if (!Flags.isByVal()) {
3247 if (!TII->isLoadFromStackSlot(Def, FI))
3250 unsigned Opcode = Def->getOpcode();
3251 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3252 Opcode == X86::LEA64_32r) &&
3253 Def->getOperand(1).isFI()) {
3254 FI = Def->getOperand(1).getIndex();
3255 Bytes = Flags.getByValSize();
3259 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3260 if (Flags.isByVal())
3261 // ByVal argument is passed in as a pointer but it's now being
3262 // dereferenced. e.g.
3263 // define @foo(%struct.X* %A) {
3264 // tail call @bar(%struct.X* byval %A)
3267 SDValue Ptr = Ld->getBasePtr();
3268 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3271 FI = FINode->getIndex();
3272 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3273 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3274 FI = FINode->getIndex();
3275 Bytes = Flags.getByValSize();
3279 assert(FI != INT_MAX);
3280 if (!MFI->isFixedObjectIndex(FI))
3282 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3285 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3286 /// for tail call optimization. Targets which want to do tail call
3287 /// optimization should implement this function.
3289 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3290 CallingConv::ID CalleeCC,
3292 bool isCalleeStructRet,
3293 bool isCallerStructRet,
3295 const SmallVectorImpl<ISD::OutputArg> &Outs,
3296 const SmallVectorImpl<SDValue> &OutVals,
3297 const SmallVectorImpl<ISD::InputArg> &Ins,
3298 SelectionDAG &DAG) const {
3299 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3302 // If -tailcallopt is specified, make fastcc functions tail-callable.
3303 const MachineFunction &MF = DAG.getMachineFunction();
3304 const Function *CallerF = MF.getFunction();
3306 // If the function return type is x86_fp80 and the callee return type is not,
3307 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3308 // perform a tailcall optimization here.
3309 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3312 CallingConv::ID CallerCC = CallerF->getCallingConv();
3313 bool CCMatch = CallerCC == CalleeCC;
3314 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3315 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3317 // Win64 functions have extra shadow space for argument homing. Don't do the
3318 // sibcall if the caller and callee have mismatched expectations for this
3320 if (IsCalleeWin64 != IsCallerWin64)
3323 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3324 if (IsTailCallConvention(CalleeCC) && CCMatch)
3329 // Look for obvious safe cases to perform tail call optimization that do not
3330 // require ABI changes. This is what gcc calls sibcall.
3332 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3333 // emit a special epilogue.
3334 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3335 if (RegInfo->needsStackRealignment(MF))
3338 // Also avoid sibcall optimization if either caller or callee uses struct
3339 // return semantics.
3340 if (isCalleeStructRet || isCallerStructRet)
3343 // An stdcall/thiscall caller is expected to clean up its arguments; the
3344 // callee isn't going to do that.
3345 // FIXME: this is more restrictive than needed. We could produce a tailcall
3346 // when the stack adjustment matches. For example, with a thiscall that takes
3347 // only one argument.
3348 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3349 CallerCC == CallingConv::X86_ThisCall))
3352 // Do not sibcall optimize vararg calls unless all arguments are passed via
3354 if (isVarArg && !Outs.empty()) {
3356 // Optimizing for varargs on Win64 is unlikely to be safe without
3357 // additional testing.
3358 if (IsCalleeWin64 || IsCallerWin64)
3361 SmallVector<CCValAssign, 16> ArgLocs;
3362 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3365 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3366 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3367 if (!ArgLocs[i].isRegLoc())
3371 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3372 // stack. Therefore, if it's not used by the call it is not safe to optimize
3373 // this into a sibcall.
3374 bool Unused = false;
3375 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3382 SmallVector<CCValAssign, 16> RVLocs;
3383 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3385 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3386 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3387 CCValAssign &VA = RVLocs[i];
3388 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3393 // If the calling conventions do not match, then we'd better make sure the
3394 // results are returned in the same way as what the caller expects.
3396 SmallVector<CCValAssign, 16> RVLocs1;
3397 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3399 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3401 SmallVector<CCValAssign, 16> RVLocs2;
3402 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3404 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3406 if (RVLocs1.size() != RVLocs2.size())
3408 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3409 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3411 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3413 if (RVLocs1[i].isRegLoc()) {
3414 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3417 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3423 // If the callee takes no arguments then go on to check the results of the
3425 if (!Outs.empty()) {
3426 // Check if stack adjustment is needed. For now, do not do this if any
3427 // argument is passed on the stack.
3428 SmallVector<CCValAssign, 16> ArgLocs;
3429 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3432 // Allocate shadow area for Win64
3434 CCInfo.AllocateStack(32, 8);
3436 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3437 if (CCInfo.getNextStackOffset()) {
3438 MachineFunction &MF = DAG.getMachineFunction();
3439 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3442 // Check if the arguments are already laid out in the right way as
3443 // the caller's fixed stack objects.
3444 MachineFrameInfo *MFI = MF.getFrameInfo();
3445 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3446 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3447 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3448 CCValAssign &VA = ArgLocs[i];
3449 SDValue Arg = OutVals[i];
3450 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3451 if (VA.getLocInfo() == CCValAssign::Indirect)
3453 if (!VA.isRegLoc()) {
3454 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3461 // If the tailcall address may be in a register, then make sure it's
3462 // possible to register allocate for it. In 32-bit, the call address can
3463 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3464 // callee-saved registers are restored. These happen to be the same
3465 // registers used to pass 'inreg' arguments so watch out for those.
3466 if (!Subtarget->is64Bit() &&
3467 ((!isa<GlobalAddressSDNode>(Callee) &&
3468 !isa<ExternalSymbolSDNode>(Callee)) ||
3469 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3470 unsigned NumInRegs = 0;
3471 // In PIC we need an extra register to formulate the address computation
3473 unsigned MaxInRegs =
3474 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3476 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3477 CCValAssign &VA = ArgLocs[i];
3480 unsigned Reg = VA.getLocReg();
3483 case X86::EAX: case X86::EDX: case X86::ECX:
3484 if (++NumInRegs == MaxInRegs)
3496 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3497 const TargetLibraryInfo *libInfo) const {
3498 return X86::createFastISel(funcInfo, libInfo);
3501 //===----------------------------------------------------------------------===//
3502 // Other Lowering Hooks
3503 //===----------------------------------------------------------------------===//
3505 static bool MayFoldLoad(SDValue Op) {
3506 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3509 static bool MayFoldIntoStore(SDValue Op) {
3510 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3513 static bool isTargetShuffle(unsigned Opcode) {
3515 default: return false;
3516 case X86ISD::BLENDI:
3517 case X86ISD::PSHUFB:
3518 case X86ISD::PSHUFD:
3519 case X86ISD::PSHUFHW:
3520 case X86ISD::PSHUFLW:
3522 case X86ISD::PALIGNR:
3523 case X86ISD::MOVLHPS:
3524 case X86ISD::MOVLHPD:
3525 case X86ISD::MOVHLPS:
3526 case X86ISD::MOVLPS:
3527 case X86ISD::MOVLPD:
3528 case X86ISD::MOVSHDUP:
3529 case X86ISD::MOVSLDUP:
3530 case X86ISD::MOVDDUP:
3533 case X86ISD::UNPCKL:
3534 case X86ISD::UNPCKH:
3535 case X86ISD::VPERMILPI:
3536 case X86ISD::VPERM2X128:
3537 case X86ISD::VPERMI:
3542 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3543 SDValue V1, unsigned TargetMask,
3544 SelectionDAG &DAG) {
3546 default: llvm_unreachable("Unknown x86 shuffle node");
3547 case X86ISD::PSHUFD:
3548 case X86ISD::PSHUFHW:
3549 case X86ISD::PSHUFLW:
3550 case X86ISD::VPERMILPI:
3551 case X86ISD::VPERMI:
3552 return DAG.getNode(Opc, dl, VT, V1,
3553 DAG.getConstant(TargetMask, dl, MVT::i8));
3557 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3558 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3560 default: llvm_unreachable("Unknown x86 shuffle node");
3561 case X86ISD::MOVLHPS:
3562 case X86ISD::MOVLHPD:
3563 case X86ISD::MOVHLPS:
3564 case X86ISD::MOVLPS:
3565 case X86ISD::MOVLPD:
3568 case X86ISD::UNPCKL:
3569 case X86ISD::UNPCKH:
3570 return DAG.getNode(Opc, dl, VT, V1, V2);
3574 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3575 MachineFunction &MF = DAG.getMachineFunction();
3576 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3577 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3578 int ReturnAddrIndex = FuncInfo->getRAIndex();
3580 if (ReturnAddrIndex == 0) {
3581 // Set up a frame object for the return address.
3582 unsigned SlotSize = RegInfo->getSlotSize();
3583 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3586 FuncInfo->setRAIndex(ReturnAddrIndex);
3589 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3592 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3593 bool hasSymbolicDisplacement) {
3594 // Offset should fit into 32 bit immediate field.
3595 if (!isInt<32>(Offset))
3598 // If we don't have a symbolic displacement - we don't have any extra
3600 if (!hasSymbolicDisplacement)
3603 // FIXME: Some tweaks might be needed for medium code model.
3604 if (M != CodeModel::Small && M != CodeModel::Kernel)
3607 // For small code model we assume that latest object is 16MB before end of 31
3608 // bits boundary. We may also accept pretty large negative constants knowing
3609 // that all objects are in the positive half of address space.
3610 if (M == CodeModel::Small && Offset < 16*1024*1024)
3613 // For kernel code model we know that all object resist in the negative half
3614 // of 32bits address space. We may not accept negative offsets, since they may
3615 // be just off and we may accept pretty large positive ones.
3616 if (M == CodeModel::Kernel && Offset >= 0)
3622 /// isCalleePop - Determines whether the callee is required to pop its
3623 /// own arguments. Callee pop is necessary to support tail calls.
3624 bool X86::isCalleePop(CallingConv::ID CallingConv,
3625 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3626 switch (CallingConv) {
3629 case CallingConv::X86_StdCall:
3630 case CallingConv::X86_FastCall:
3631 case CallingConv::X86_ThisCall:
3633 case CallingConv::Fast:
3634 case CallingConv::GHC:
3635 case CallingConv::HiPE:
3642 /// \brief Return true if the condition is an unsigned comparison operation.
3643 static bool isX86CCUnsigned(unsigned X86CC) {
3645 default: llvm_unreachable("Invalid integer condition!");
3646 case X86::COND_E: return true;
3647 case X86::COND_G: return false;
3648 case X86::COND_GE: return false;
3649 case X86::COND_L: return false;
3650 case X86::COND_LE: return false;
3651 case X86::COND_NE: return true;
3652 case X86::COND_B: return true;
3653 case X86::COND_A: return true;
3654 case X86::COND_BE: return true;
3655 case X86::COND_AE: return true;
3657 llvm_unreachable("covered switch fell through?!");
3660 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3661 /// specific condition code, returning the condition code and the LHS/RHS of the
3662 /// comparison to make.
3663 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3664 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3666 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3667 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3668 // X > -1 -> X == 0, jump !sign.
3669 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3670 return X86::COND_NS;
3672 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3673 // X < 0 -> X == 0, jump on sign.
3676 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3678 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3679 return X86::COND_LE;
3683 switch (SetCCOpcode) {
3684 default: llvm_unreachable("Invalid integer condition!");
3685 case ISD::SETEQ: return X86::COND_E;
3686 case ISD::SETGT: return X86::COND_G;
3687 case ISD::SETGE: return X86::COND_GE;
3688 case ISD::SETLT: return X86::COND_L;
3689 case ISD::SETLE: return X86::COND_LE;
3690 case ISD::SETNE: return X86::COND_NE;
3691 case ISD::SETULT: return X86::COND_B;
3692 case ISD::SETUGT: return X86::COND_A;
3693 case ISD::SETULE: return X86::COND_BE;
3694 case ISD::SETUGE: return X86::COND_AE;
3698 // First determine if it is required or is profitable to flip the operands.
3700 // If LHS is a foldable load, but RHS is not, flip the condition.
3701 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3702 !ISD::isNON_EXTLoad(RHS.getNode())) {
3703 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3704 std::swap(LHS, RHS);
3707 switch (SetCCOpcode) {
3713 std::swap(LHS, RHS);
3717 // On a floating point condition, the flags are set as follows:
3719 // 0 | 0 | 0 | X > Y
3720 // 0 | 0 | 1 | X < Y
3721 // 1 | 0 | 0 | X == Y
3722 // 1 | 1 | 1 | unordered
3723 switch (SetCCOpcode) {
3724 default: llvm_unreachable("Condcode should be pre-legalized away");
3726 case ISD::SETEQ: return X86::COND_E;
3727 case ISD::SETOLT: // flipped
3729 case ISD::SETGT: return X86::COND_A;
3730 case ISD::SETOLE: // flipped
3732 case ISD::SETGE: return X86::COND_AE;
3733 case ISD::SETUGT: // flipped
3735 case ISD::SETLT: return X86::COND_B;
3736 case ISD::SETUGE: // flipped
3738 case ISD::SETLE: return X86::COND_BE;
3740 case ISD::SETNE: return X86::COND_NE;
3741 case ISD::SETUO: return X86::COND_P;
3742 case ISD::SETO: return X86::COND_NP;
3744 case ISD::SETUNE: return X86::COND_INVALID;
3748 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3749 /// code. Current x86 isa includes the following FP cmov instructions:
3750 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3751 static bool hasFPCMov(unsigned X86CC) {
3767 /// isFPImmLegal - Returns true if the target can instruction select the
3768 /// specified FP immediate natively. If false, the legalizer will
3769 /// materialize the FP immediate as a load from a constant pool.
3770 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3771 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3772 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3778 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3779 ISD::LoadExtType ExtTy,
3781 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3782 // relocation target a movq or addq instruction: don't let the load shrink.
3783 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3784 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3785 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3786 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3790 /// \brief Returns true if it is beneficial to convert a load of a constant
3791 /// to just the constant itself.
3792 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3794 assert(Ty->isIntegerTy());
3796 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3797 if (BitSize == 0 || BitSize > 64)
3802 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3803 unsigned Index) const {
3804 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3807 return (Index == 0 || Index == ResVT.getVectorNumElements());
3810 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3811 // Speculate cttz only if we can directly use TZCNT.
3812 return Subtarget->hasBMI();
3815 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3816 // Speculate ctlz only if we can directly use LZCNT.
3817 return Subtarget->hasLZCNT();
3820 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3821 /// the specified range (L, H].
3822 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3823 return (Val < 0) || (Val >= Low && Val < Hi);
3826 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3827 /// specified value.
3828 static bool isUndefOrEqual(int Val, int CmpVal) {
3829 return (Val < 0 || Val == CmpVal);
3832 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3833 /// from position Pos and ending in Pos+Size, falls within the specified
3834 /// sequential range (Low, Low+Size]. or is undef.
3835 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3836 unsigned Pos, unsigned Size, int Low) {
3837 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3838 if (!isUndefOrEqual(Mask[i], Low))
3843 /// isVEXTRACTIndex - Return true if the specified
3844 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3845 /// suitable for instruction that extract 128 or 256 bit vectors
3846 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3847 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3848 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3851 // The index should be aligned on a vecWidth-bit boundary.
3853 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3855 MVT VT = N->getSimpleValueType(0);
3856 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3857 bool Result = (Index * ElSize) % vecWidth == 0;
3862 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3863 /// operand specifies a subvector insert that is suitable for input to
3864 /// insertion of 128 or 256-bit subvectors
3865 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3866 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3867 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3869 // The index should be aligned on a vecWidth-bit boundary.
3871 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3873 MVT VT = N->getSimpleValueType(0);
3874 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3875 bool Result = (Index * ElSize) % vecWidth == 0;
3880 bool X86::isVINSERT128Index(SDNode *N) {
3881 return isVINSERTIndex(N, 128);
3884 bool X86::isVINSERT256Index(SDNode *N) {
3885 return isVINSERTIndex(N, 256);
3888 bool X86::isVEXTRACT128Index(SDNode *N) {
3889 return isVEXTRACTIndex(N, 128);
3892 bool X86::isVEXTRACT256Index(SDNode *N) {
3893 return isVEXTRACTIndex(N, 256);
3896 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
3897 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3898 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3899 llvm_unreachable("Illegal extract subvector for VEXTRACT");
3902 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3904 MVT VecVT = N->getOperand(0).getSimpleValueType();
3905 MVT ElVT = VecVT.getVectorElementType();
3907 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3908 return Index / NumElemsPerChunk;
3911 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
3912 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
3913 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3914 llvm_unreachable("Illegal insert subvector for VINSERT");
3917 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3919 MVT VecVT = N->getSimpleValueType(0);
3920 MVT ElVT = VecVT.getVectorElementType();
3922 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
3923 return Index / NumElemsPerChunk;
3926 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
3927 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3928 /// and VINSERTI128 instructions.
3929 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
3930 return getExtractVEXTRACTImmediate(N, 128);
3933 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
3934 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
3935 /// and VINSERTI64x4 instructions.
3936 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
3937 return getExtractVEXTRACTImmediate(N, 256);
3940 /// getInsertVINSERT128Immediate - Return the appropriate immediate
3941 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3942 /// and VINSERTI128 instructions.
3943 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
3944 return getInsertVINSERTImmediate(N, 128);
3947 /// getInsertVINSERT256Immediate - Return the appropriate immediate
3948 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
3949 /// and VINSERTI64x4 instructions.
3950 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
3951 return getInsertVINSERTImmediate(N, 256);
3954 /// isZero - Returns true if Elt is a constant integer zero
3955 static bool isZero(SDValue V) {
3956 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
3957 return C && C->isNullValue();
3960 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3962 bool X86::isZeroNode(SDValue Elt) {
3965 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
3966 return CFP->getValueAPF().isPosZero();
3970 /// getZeroVector - Returns a vector of specified type with all zero elements.
3972 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
3973 SelectionDAG &DAG, SDLoc dl) {
3974 assert(VT.isVector() && "Expected a vector type");
3976 // Always build SSE zero vectors as <4 x i32> bitcasted
3977 // to their dest type. This ensures they get CSE'd.
3979 if (VT.is128BitVector()) { // SSE
3980 if (Subtarget->hasSSE2()) { // SSE2
3981 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3982 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3984 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3985 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3987 } else if (VT.is256BitVector()) { // AVX
3988 if (Subtarget->hasInt256()) { // AVX2
3989 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
3990 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3991 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
3993 // 256-bit logic and arithmetic instructions in AVX are all
3994 // floating-point, no support for integer ops. Emit fp zeroed vectors.
3995 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
3996 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3997 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
3999 } else if (VT.is512BitVector()) { // AVX-512
4000 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4001 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4002 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4003 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4004 } else if (VT.getScalarType() == MVT::i1) {
4006 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4007 && "Unexpected vector type");
4008 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4009 && "Unexpected vector type");
4010 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4011 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4012 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4014 llvm_unreachable("Unexpected vector type");
4016 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4019 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4020 SelectionDAG &DAG, SDLoc dl,
4021 unsigned vectorWidth) {
4022 assert((vectorWidth == 128 || vectorWidth == 256) &&
4023 "Unsupported vector width");
4024 EVT VT = Vec.getValueType();
4025 EVT ElVT = VT.getVectorElementType();
4026 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4027 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4028 VT.getVectorNumElements()/Factor);
4030 // Extract from UNDEF is UNDEF.
4031 if (Vec.getOpcode() == ISD::UNDEF)
4032 return DAG.getUNDEF(ResultVT);
4034 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4035 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4037 // This is the index of the first element of the vectorWidth-bit chunk
4039 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4042 // If the input is a buildvector just emit a smaller one.
4043 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4044 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4045 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4048 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4049 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4052 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4053 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4054 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4055 /// instructions or a simple subregister reference. Idx is an index in the
4056 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4057 /// lowering EXTRACT_VECTOR_ELT operations easier.
4058 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4059 SelectionDAG &DAG, SDLoc dl) {
4060 assert((Vec.getValueType().is256BitVector() ||
4061 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4062 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4065 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4066 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4067 SelectionDAG &DAG, SDLoc dl) {
4068 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4069 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4072 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4073 unsigned IdxVal, SelectionDAG &DAG,
4074 SDLoc dl, unsigned vectorWidth) {
4075 assert((vectorWidth == 128 || vectorWidth == 256) &&
4076 "Unsupported vector width");
4077 // Inserting UNDEF is Result
4078 if (Vec.getOpcode() == ISD::UNDEF)
4080 EVT VT = Vec.getValueType();
4081 EVT ElVT = VT.getVectorElementType();
4082 EVT ResultVT = Result.getValueType();
4084 // Insert the relevant vectorWidth bits.
4085 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4087 // This is the index of the first element of the vectorWidth-bit chunk
4089 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4092 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4093 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4096 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4097 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4098 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4099 /// simple superregister reference. Idx is an index in the 128 bits
4100 /// we want. It need not be aligned to a 128-bit boundary. That makes
4101 /// lowering INSERT_VECTOR_ELT operations easier.
4102 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4103 SelectionDAG &DAG, SDLoc dl) {
4104 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4106 // For insertion into the zero index (low half) of a 256-bit vector, it is
4107 // more efficient to generate a blend with immediate instead of an insert*128.
4108 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4109 // extend the subvector to the size of the result vector. Make sure that
4110 // we are not recursing on that node by checking for undef here.
4111 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4112 Result.getOpcode() != ISD::UNDEF) {
4113 EVT ResultVT = Result.getValueType();
4114 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4115 SDValue Undef = DAG.getUNDEF(ResultVT);
4116 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4119 // The blend instruction, and therefore its mask, depend on the data type.
4120 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4121 if (ScalarType.isFloatingPoint()) {
4122 // Choose either vblendps (float) or vblendpd (double).
4123 unsigned ScalarSize = ScalarType.getSizeInBits();
4124 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4125 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4126 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4127 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4130 const X86Subtarget &Subtarget =
4131 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4133 // AVX2 is needed for 256-bit integer blend support.
4134 // Integers must be cast to 32-bit because there is only vpblendd;
4135 // vpblendw can't be used for this because it has a handicapped mask.
4137 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4138 // is still more efficient than using the wrong domain vinsertf128 that
4139 // will be created by InsertSubVector().
4140 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4142 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4143 Vec256 = DAG.getNode(ISD::BITCAST, dl, CastVT, Vec256);
4144 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4145 return DAG.getNode(ISD::BITCAST, dl, ResultVT, Vec256);
4148 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4151 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4152 SelectionDAG &DAG, SDLoc dl) {
4153 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4154 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4157 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4158 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4159 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4160 /// large BUILD_VECTORS.
4161 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4162 unsigned NumElems, SelectionDAG &DAG,
4164 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4165 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4168 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4169 unsigned NumElems, SelectionDAG &DAG,
4171 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4172 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4175 /// getOnesVector - Returns a vector of specified type with all bits set.
4176 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4177 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4178 /// Then bitcast to their original type, ensuring they get CSE'd.
4179 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4181 assert(VT.isVector() && "Expected a vector type");
4183 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4185 if (VT.is256BitVector()) {
4186 if (HasInt256) { // AVX2
4187 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4188 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4190 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4191 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4193 } else if (VT.is128BitVector()) {
4194 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4196 llvm_unreachable("Unexpected vector type");
4198 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4201 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4202 /// operation of specified width.
4203 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4205 unsigned NumElems = VT.getVectorNumElements();
4206 SmallVector<int, 8> Mask;
4207 Mask.push_back(NumElems);
4208 for (unsigned i = 1; i != NumElems; ++i)
4210 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4213 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4214 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4216 unsigned NumElems = VT.getVectorNumElements();
4217 SmallVector<int, 8> Mask;
4218 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4220 Mask.push_back(i + NumElems);
4222 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4225 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4226 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4228 unsigned NumElems = VT.getVectorNumElements();
4229 SmallVector<int, 8> Mask;
4230 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4231 Mask.push_back(i + Half);
4232 Mask.push_back(i + NumElems + Half);
4234 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4237 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4238 /// vector of zero or undef vector. This produces a shuffle where the low
4239 /// element of V2 is swizzled into the zero/undef vector, landing at element
4240 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4241 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4243 const X86Subtarget *Subtarget,
4244 SelectionDAG &DAG) {
4245 MVT VT = V2.getSimpleValueType();
4247 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4248 unsigned NumElems = VT.getVectorNumElements();
4249 SmallVector<int, 16> MaskVec;
4250 for (unsigned i = 0; i != NumElems; ++i)
4251 // If this is the insertion idx, put the low elt of V2 here.
4252 MaskVec.push_back(i == Idx ? NumElems : i);
4253 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4256 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4257 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4258 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4259 /// shuffles which use a single input multiple times, and in those cases it will
4260 /// adjust the mask to only have indices within that single input.
4261 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4262 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4263 unsigned NumElems = VT.getVectorNumElements();
4267 bool IsFakeUnary = false;
4268 switch(N->getOpcode()) {
4269 case X86ISD::BLENDI:
4270 ImmN = N->getOperand(N->getNumOperands()-1);
4271 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4274 ImmN = N->getOperand(N->getNumOperands()-1);
4275 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4276 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4278 case X86ISD::UNPCKH:
4279 DecodeUNPCKHMask(VT, Mask);
4280 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4282 case X86ISD::UNPCKL:
4283 DecodeUNPCKLMask(VT, Mask);
4284 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4286 case X86ISD::MOVHLPS:
4287 DecodeMOVHLPSMask(NumElems, Mask);
4288 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4290 case X86ISD::MOVLHPS:
4291 DecodeMOVLHPSMask(NumElems, Mask);
4292 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4294 case X86ISD::PALIGNR:
4295 ImmN = N->getOperand(N->getNumOperands()-1);
4296 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4298 case X86ISD::PSHUFD:
4299 case X86ISD::VPERMILPI:
4300 ImmN = N->getOperand(N->getNumOperands()-1);
4301 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4304 case X86ISD::PSHUFHW:
4305 ImmN = N->getOperand(N->getNumOperands()-1);
4306 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4309 case X86ISD::PSHUFLW:
4310 ImmN = N->getOperand(N->getNumOperands()-1);
4311 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4314 case X86ISD::PSHUFB: {
4316 SDValue MaskNode = N->getOperand(1);
4317 while (MaskNode->getOpcode() == ISD::BITCAST)
4318 MaskNode = MaskNode->getOperand(0);
4320 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4321 // If we have a build-vector, then things are easy.
4322 EVT VT = MaskNode.getValueType();
4323 assert(VT.isVector() &&
4324 "Can't produce a non-vector with a build_vector!");
4325 if (!VT.isInteger())
4328 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4330 SmallVector<uint64_t, 32> RawMask;
4331 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4332 SDValue Op = MaskNode->getOperand(i);
4333 if (Op->getOpcode() == ISD::UNDEF) {
4334 RawMask.push_back((uint64_t)SM_SentinelUndef);
4337 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4340 APInt MaskElement = CN->getAPIntValue();
4342 // We now have to decode the element which could be any integer size and
4343 // extract each byte of it.
4344 for (int j = 0; j < NumBytesPerElement; ++j) {
4345 // Note that this is x86 and so always little endian: the low byte is
4346 // the first byte of the mask.
4347 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4348 MaskElement = MaskElement.lshr(8);
4351 DecodePSHUFBMask(RawMask, Mask);
4355 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4359 SDValue Ptr = MaskLoad->getBasePtr();
4360 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4361 Ptr->getOpcode() == X86ISD::WrapperRIP)
4362 Ptr = Ptr->getOperand(0);
4364 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4365 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4368 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4369 DecodePSHUFBMask(C, Mask);
4377 case X86ISD::VPERMI:
4378 ImmN = N->getOperand(N->getNumOperands()-1);
4379 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4384 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4386 case X86ISD::VPERM2X128:
4387 ImmN = N->getOperand(N->getNumOperands()-1);
4388 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4389 if (Mask.empty()) return false;
4391 case X86ISD::MOVSLDUP:
4392 DecodeMOVSLDUPMask(VT, Mask);
4395 case X86ISD::MOVSHDUP:
4396 DecodeMOVSHDUPMask(VT, Mask);
4399 case X86ISD::MOVDDUP:
4400 DecodeMOVDDUPMask(VT, Mask);
4403 case X86ISD::MOVLHPD:
4404 case X86ISD::MOVLPD:
4405 case X86ISD::MOVLPS:
4406 // Not yet implemented
4408 default: llvm_unreachable("unknown target shuffle node");
4411 // If we have a fake unary shuffle, the shuffle mask is spread across two
4412 // inputs that are actually the same node. Re-map the mask to always point
4413 // into the first input.
4416 if (M >= (int)Mask.size())
4422 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4423 /// element of the result of the vector shuffle.
4424 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4427 return SDValue(); // Limit search depth.
4429 SDValue V = SDValue(N, 0);
4430 EVT VT = V.getValueType();
4431 unsigned Opcode = V.getOpcode();
4433 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4434 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4435 int Elt = SV->getMaskElt(Index);
4438 return DAG.getUNDEF(VT.getVectorElementType());
4440 unsigned NumElems = VT.getVectorNumElements();
4441 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4442 : SV->getOperand(1);
4443 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4446 // Recurse into target specific vector shuffles to find scalars.
4447 if (isTargetShuffle(Opcode)) {
4448 MVT ShufVT = V.getSimpleValueType();
4449 unsigned NumElems = ShufVT.getVectorNumElements();
4450 SmallVector<int, 16> ShuffleMask;
4453 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4456 int Elt = ShuffleMask[Index];
4458 return DAG.getUNDEF(ShufVT.getVectorElementType());
4460 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4462 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4466 // Actual nodes that may contain scalar elements
4467 if (Opcode == ISD::BITCAST) {
4468 V = V.getOperand(0);
4469 EVT SrcVT = V.getValueType();
4470 unsigned NumElems = VT.getVectorNumElements();
4472 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4476 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4477 return (Index == 0) ? V.getOperand(0)
4478 : DAG.getUNDEF(VT.getVectorElementType());
4480 if (V.getOpcode() == ISD::BUILD_VECTOR)
4481 return V.getOperand(Index);
4486 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4488 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4489 unsigned NumNonZero, unsigned NumZero,
4491 const X86Subtarget* Subtarget,
4492 const TargetLowering &TLI) {
4500 // SSE4.1 - use PINSRB to insert each byte directly.
4501 if (Subtarget->hasSSE41()) {
4502 for (unsigned i = 0; i < 16; ++i) {
4503 bool isNonZero = (NonZeros & (1 << i)) != 0;
4507 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4509 V = DAG.getUNDEF(MVT::v16i8);
4512 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4513 MVT::v16i8, V, Op.getOperand(i),
4514 DAG.getIntPtrConstant(i, dl));
4521 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4522 for (unsigned i = 0; i < 16; ++i) {
4523 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4524 if (ThisIsNonZero && First) {
4526 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4528 V = DAG.getUNDEF(MVT::v8i16);
4533 SDValue ThisElt, LastElt;
4534 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4535 if (LastIsNonZero) {
4536 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4537 MVT::i16, Op.getOperand(i-1));
4539 if (ThisIsNonZero) {
4540 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4541 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4542 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4544 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4548 if (ThisElt.getNode())
4549 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4550 DAG.getIntPtrConstant(i/2, dl));
4554 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4557 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4559 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4560 unsigned NumNonZero, unsigned NumZero,
4562 const X86Subtarget* Subtarget,
4563 const TargetLowering &TLI) {
4570 for (unsigned i = 0; i < 8; ++i) {
4571 bool isNonZero = (NonZeros & (1 << i)) != 0;
4575 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4577 V = DAG.getUNDEF(MVT::v8i16);
4580 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4581 MVT::v8i16, V, Op.getOperand(i),
4582 DAG.getIntPtrConstant(i, dl));
4589 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4590 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4591 const X86Subtarget *Subtarget,
4592 const TargetLowering &TLI) {
4593 // Find all zeroable elements.
4594 std::bitset<4> Zeroable;
4595 for (int i=0; i < 4; ++i) {
4596 SDValue Elt = Op->getOperand(i);
4597 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4599 assert(Zeroable.size() - Zeroable.count() > 1 &&
4600 "We expect at least two non-zero elements!");
4602 // We only know how to deal with build_vector nodes where elements are either
4603 // zeroable or extract_vector_elt with constant index.
4604 SDValue FirstNonZero;
4605 unsigned FirstNonZeroIdx;
4606 for (unsigned i=0; i < 4; ++i) {
4609 SDValue Elt = Op->getOperand(i);
4610 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4611 !isa<ConstantSDNode>(Elt.getOperand(1)))
4613 // Make sure that this node is extracting from a 128-bit vector.
4614 MVT VT = Elt.getOperand(0).getSimpleValueType();
4615 if (!VT.is128BitVector())
4617 if (!FirstNonZero.getNode()) {
4619 FirstNonZeroIdx = i;
4623 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4624 SDValue V1 = FirstNonZero.getOperand(0);
4625 MVT VT = V1.getSimpleValueType();
4627 // See if this build_vector can be lowered as a blend with zero.
4629 unsigned EltMaskIdx, EltIdx;
4631 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4632 if (Zeroable[EltIdx]) {
4633 // The zero vector will be on the right hand side.
4634 Mask[EltIdx] = EltIdx+4;
4638 Elt = Op->getOperand(EltIdx);
4639 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4640 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4641 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4643 Mask[EltIdx] = EltIdx;
4647 // Let the shuffle legalizer deal with blend operations.
4648 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4649 if (V1.getSimpleValueType() != VT)
4650 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4651 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4654 // See if we can lower this build_vector to a INSERTPS.
4655 if (!Subtarget->hasSSE41())
4658 SDValue V2 = Elt.getOperand(0);
4659 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4662 bool CanFold = true;
4663 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4667 SDValue Current = Op->getOperand(i);
4668 SDValue SrcVector = Current->getOperand(0);
4671 CanFold = SrcVector == V1 &&
4672 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4678 assert(V1.getNode() && "Expected at least two non-zero elements!");
4679 if (V1.getSimpleValueType() != MVT::v4f32)
4680 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4681 if (V2.getSimpleValueType() != MVT::v4f32)
4682 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4684 // Ok, we can emit an INSERTPS instruction.
4685 unsigned ZMask = Zeroable.to_ulong();
4687 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4688 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4690 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4691 DAG.getIntPtrConstant(InsertPSMask, DL));
4692 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
4695 /// Return a vector logical shift node.
4696 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4697 unsigned NumBits, SelectionDAG &DAG,
4698 const TargetLowering &TLI, SDLoc dl) {
4699 assert(VT.is128BitVector() && "Unknown type for VShift");
4700 MVT ShVT = MVT::v2i64;
4701 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4702 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4703 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4704 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4705 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4706 return DAG.getNode(ISD::BITCAST, dl, VT,
4707 DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4711 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4713 // Check if the scalar load can be widened into a vector load. And if
4714 // the address is "base + cst" see if the cst can be "absorbed" into
4715 // the shuffle mask.
4716 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4717 SDValue Ptr = LD->getBasePtr();
4718 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4720 EVT PVT = LD->getValueType(0);
4721 if (PVT != MVT::i32 && PVT != MVT::f32)
4726 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4727 FI = FINode->getIndex();
4729 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4730 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4731 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4732 Offset = Ptr.getConstantOperandVal(1);
4733 Ptr = Ptr.getOperand(0);
4738 // FIXME: 256-bit vector instructions don't require a strict alignment,
4739 // improve this code to support it better.
4740 unsigned RequiredAlign = VT.getSizeInBits()/8;
4741 SDValue Chain = LD->getChain();
4742 // Make sure the stack object alignment is at least 16 or 32.
4743 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4744 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4745 if (MFI->isFixedObjectIndex(FI)) {
4746 // Can't change the alignment. FIXME: It's possible to compute
4747 // the exact stack offset and reference FI + adjust offset instead.
4748 // If someone *really* cares about this. That's the way to implement it.
4751 MFI->setObjectAlignment(FI, RequiredAlign);
4755 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4756 // Ptr + (Offset & ~15).
4759 if ((Offset % RequiredAlign) & 3)
4761 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4764 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4765 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4768 int EltNo = (Offset - StartOffset) >> 2;
4769 unsigned NumElems = VT.getVectorNumElements();
4771 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4772 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4773 LD->getPointerInfo().getWithOffset(StartOffset),
4774 false, false, false, 0);
4776 SmallVector<int, 8> Mask(NumElems, EltNo);
4778 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4784 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4785 /// elements can be replaced by a single large load which has the same value as
4786 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4788 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4790 /// FIXME: we'd also like to handle the case where the last elements are zero
4791 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4792 /// There's even a handy isZeroNode for that purpose.
4793 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4794 SDLoc &DL, SelectionDAG &DAG,
4795 bool isAfterLegalize) {
4796 unsigned NumElems = Elts.size();
4798 LoadSDNode *LDBase = nullptr;
4799 unsigned LastLoadedElt = -1U;
4801 // For each element in the initializer, see if we've found a load or an undef.
4802 // If we don't find an initial load element, or later load elements are
4803 // non-consecutive, bail out.
4804 for (unsigned i = 0; i < NumElems; ++i) {
4805 SDValue Elt = Elts[i];
4806 // Look through a bitcast.
4807 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4808 Elt = Elt.getOperand(0);
4809 if (!Elt.getNode() ||
4810 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4813 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4815 LDBase = cast<LoadSDNode>(Elt.getNode());
4819 if (Elt.getOpcode() == ISD::UNDEF)
4822 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4823 EVT LdVT = Elt.getValueType();
4824 // Each loaded element must be the correct fractional portion of the
4825 // requested vector load.
4826 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4828 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4833 // If we have found an entire vector of loads and undefs, then return a large
4834 // load of the entire vector width starting at the base pointer. If we found
4835 // consecutive loads for the low half, generate a vzext_load node.
4836 if (LastLoadedElt == NumElems - 1) {
4837 assert(LDBase && "Did not find base load for merging consecutive loads");
4838 EVT EltVT = LDBase->getValueType(0);
4839 // Ensure that the input vector size for the merged loads matches the
4840 // cumulative size of the input elements.
4841 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4844 if (isAfterLegalize &&
4845 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4848 SDValue NewLd = SDValue();
4850 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4851 LDBase->getPointerInfo(), LDBase->isVolatile(),
4852 LDBase->isNonTemporal(), LDBase->isInvariant(),
4853 LDBase->getAlignment());
4855 if (LDBase->hasAnyUseOfValue(1)) {
4856 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4858 SDValue(NewLd.getNode(), 1));
4859 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4860 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4861 SDValue(NewLd.getNode(), 1));
4867 //TODO: The code below fires only for for loading the low v2i32 / v2f32
4868 //of a v4i32 / v4f32. It's probably worth generalizing.
4869 EVT EltVT = VT.getVectorElementType();
4870 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4871 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4872 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4873 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4875 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4876 LDBase->getPointerInfo(),
4877 LDBase->getAlignment(),
4878 false/*isVolatile*/, true/*ReadMem*/,
4881 // Make sure the newly-created LOAD is in the same position as LDBase in
4882 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4883 // update uses of LDBase's output chain to use the TokenFactor.
4884 if (LDBase->hasAnyUseOfValue(1)) {
4885 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4886 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4887 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4888 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4889 SDValue(ResNode.getNode(), 1));
4892 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4897 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4898 /// to generate a splat value for the following cases:
4899 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4900 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4901 /// a scalar load, or a constant.
4902 /// The VBROADCAST node is returned when a pattern is found,
4903 /// or SDValue() otherwise.
4904 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
4905 SelectionDAG &DAG) {
4906 // VBROADCAST requires AVX.
4907 // TODO: Splats could be generated for non-AVX CPUs using SSE
4908 // instructions, but there's less potential gain for only 128-bit vectors.
4909 if (!Subtarget->hasAVX())
4912 MVT VT = Op.getSimpleValueType();
4915 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4916 "Unsupported vector type for broadcast.");
4921 switch (Op.getOpcode()) {
4923 // Unknown pattern found.
4926 case ISD::BUILD_VECTOR: {
4927 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
4928 BitVector UndefElements;
4929 SDValue Splat = BVOp->getSplatValue(&UndefElements);
4931 // We need a splat of a single value to use broadcast, and it doesn't
4932 // make any sense if the value is only in one element of the vector.
4933 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
4937 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4938 Ld.getOpcode() == ISD::ConstantFP);
4940 // Make sure that all of the users of a non-constant load are from the
4941 // BUILD_VECTOR node.
4942 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
4947 case ISD::VECTOR_SHUFFLE: {
4948 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4950 // Shuffles must have a splat mask where the first element is
4952 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4955 SDValue Sc = Op.getOperand(0);
4956 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4957 Sc.getOpcode() != ISD::BUILD_VECTOR) {
4959 if (!Subtarget->hasInt256())
4962 // Use the register form of the broadcast instruction available on AVX2.
4963 if (VT.getSizeInBits() >= 256)
4964 Sc = Extract128BitVector(Sc, 0, DAG, dl);
4965 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
4968 Ld = Sc.getOperand(0);
4969 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970 Ld.getOpcode() == ISD::ConstantFP);
4972 // The scalar_to_vector node and the suspected
4973 // load node must have exactly one user.
4974 // Constants may have multiple users.
4976 // AVX-512 has register version of the broadcast
4977 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
4978 Ld.getValueType().getSizeInBits() >= 32;
4979 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
4986 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4987 bool IsGE256 = (VT.getSizeInBits() >= 256);
4989 // When optimizing for size, generate up to 5 extra bytes for a broadcast
4990 // instruction to save 8 or more bytes of constant pool data.
4991 // TODO: If multiple splats are generated to load the same constant,
4992 // it may be detrimental to overall size. There needs to be a way to detect
4993 // that condition to know if this is truly a size win.
4994 const Function *F = DAG.getMachineFunction().getFunction();
4995 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
4997 // Handle broadcasting a single constant scalar from the constant pool
4999 // On Sandybridge (no AVX2), it is still better to load a constant vector
5000 // from the constant pool and not to broadcast it from a scalar.
5001 // But override that restriction when optimizing for size.
5002 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5003 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5004 EVT CVT = Ld.getValueType();
5005 assert(!CVT.isVector() && "Must not broadcast a vector type");
5007 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5008 // For size optimization, also splat v2f64 and v2i64, and for size opt
5009 // with AVX2, also splat i8 and i16.
5010 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5011 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5012 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5013 const Constant *C = nullptr;
5014 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5015 C = CI->getConstantIntValue();
5016 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5017 C = CF->getConstantFPValue();
5019 assert(C && "Invalid constant type");
5021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5022 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5023 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5024 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5025 MachinePointerInfo::getConstantPool(),
5026 false, false, false, Alignment);
5028 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5032 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5034 // Handle AVX2 in-register broadcasts.
5035 if (!IsLoad && Subtarget->hasInt256() &&
5036 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5037 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5039 // The scalar source must be a normal load.
5043 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5044 (Subtarget->hasVLX() && ScalarSize == 64))
5045 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5047 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5048 // double since there is no vbroadcastsd xmm
5049 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5050 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5051 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5054 // Unsupported broadcast.
5058 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5059 /// underlying vector and index.
5061 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5063 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5065 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5066 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5069 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5071 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5073 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5074 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5077 // In this case the vector is the extract_subvector expression and the index
5078 // is 2, as specified by the shuffle.
5079 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5080 SDValue ShuffleVec = SVOp->getOperand(0);
5081 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5082 assert(ShuffleVecVT.getVectorElementType() ==
5083 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5085 int ShuffleIdx = SVOp->getMaskElt(Idx);
5086 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5087 ExtractedFromVec = ShuffleVec;
5093 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5094 MVT VT = Op.getSimpleValueType();
5096 // Skip if insert_vec_elt is not supported.
5097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5098 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5102 unsigned NumElems = Op.getNumOperands();
5106 SmallVector<unsigned, 4> InsertIndices;
5107 SmallVector<int, 8> Mask(NumElems, -1);
5109 for (unsigned i = 0; i != NumElems; ++i) {
5110 unsigned Opc = Op.getOperand(i).getOpcode();
5112 if (Opc == ISD::UNDEF)
5115 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5116 // Quit if more than 1 elements need inserting.
5117 if (InsertIndices.size() > 1)
5120 InsertIndices.push_back(i);
5124 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5125 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5126 // Quit if non-constant index.
5127 if (!isa<ConstantSDNode>(ExtIdx))
5129 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5131 // Quit if extracted from vector of different type.
5132 if (ExtractedFromVec.getValueType() != VT)
5135 if (!VecIn1.getNode())
5136 VecIn1 = ExtractedFromVec;
5137 else if (VecIn1 != ExtractedFromVec) {
5138 if (!VecIn2.getNode())
5139 VecIn2 = ExtractedFromVec;
5140 else if (VecIn2 != ExtractedFromVec)
5141 // Quit if more than 2 vectors to shuffle
5145 if (ExtractedFromVec == VecIn1)
5147 else if (ExtractedFromVec == VecIn2)
5148 Mask[i] = Idx + NumElems;
5151 if (!VecIn1.getNode())
5154 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5155 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5156 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5157 unsigned Idx = InsertIndices[i];
5158 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5159 DAG.getIntPtrConstant(Idx, DL));
5165 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5167 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5169 MVT VT = Op.getSimpleValueType();
5170 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5171 "Unexpected type in LowerBUILD_VECTORvXi1!");
5174 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5175 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5176 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5177 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5180 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5181 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5182 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5183 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5186 bool AllContants = true;
5187 uint64_t Immediate = 0;
5188 int NonConstIdx = -1;
5189 bool IsSplat = true;
5190 unsigned NumNonConsts = 0;
5191 unsigned NumConsts = 0;
5192 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5193 SDValue In = Op.getOperand(idx);
5194 if (In.getOpcode() == ISD::UNDEF)
5196 if (!isa<ConstantSDNode>(In)) {
5197 AllContants = false;
5202 if (cast<ConstantSDNode>(In)->getZExtValue())
5203 Immediate |= (1ULL << idx);
5205 if (In != Op.getOperand(0))
5210 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5211 DAG.getConstant(Immediate, dl, MVT::i16));
5212 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5213 DAG.getIntPtrConstant(0, dl));
5216 if (NumNonConsts == 1 && NonConstIdx != 0) {
5219 SDValue VecAsImm = DAG.getConstant(Immediate, dl,
5220 MVT::getIntegerVT(VT.getSizeInBits()));
5221 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5224 DstVec = DAG.getUNDEF(VT);
5225 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5226 Op.getOperand(NonConstIdx),
5227 DAG.getIntPtrConstant(NonConstIdx, dl));
5229 if (!IsSplat && (NonConstIdx != 0))
5230 llvm_unreachable("Unsupported BUILD_VECTOR operation");
5231 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5234 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5235 DAG.getConstant(-1, dl, SelectVT),
5236 DAG.getConstant(0, dl, SelectVT));
5238 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5239 DAG.getConstant((Immediate | 1), dl, SelectVT),
5240 DAG.getConstant(Immediate, dl, SelectVT));
5241 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5244 /// \brief Return true if \p N implements a horizontal binop and return the
5245 /// operands for the horizontal binop into V0 and V1.
5247 /// This is a helper function of LowerToHorizontalOp().
5248 /// This function checks that the build_vector \p N in input implements a
5249 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5250 /// operation to match.
5251 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5252 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5253 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5256 /// This function only analyzes elements of \p N whose indices are
5257 /// in range [BaseIdx, LastIdx).
5258 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5260 unsigned BaseIdx, unsigned LastIdx,
5261 SDValue &V0, SDValue &V1) {
5262 EVT VT = N->getValueType(0);
5264 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5265 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5266 "Invalid Vector in input!");
5268 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5269 bool CanFold = true;
5270 unsigned ExpectedVExtractIdx = BaseIdx;
5271 unsigned NumElts = LastIdx - BaseIdx;
5272 V0 = DAG.getUNDEF(VT);
5273 V1 = DAG.getUNDEF(VT);
5275 // Check if N implements a horizontal binop.
5276 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5277 SDValue Op = N->getOperand(i + BaseIdx);
5280 if (Op->getOpcode() == ISD::UNDEF) {
5281 // Update the expected vector extract index.
5282 if (i * 2 == NumElts)
5283 ExpectedVExtractIdx = BaseIdx;
5284 ExpectedVExtractIdx += 2;
5288 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5293 SDValue Op0 = Op.getOperand(0);
5294 SDValue Op1 = Op.getOperand(1);
5296 // Try to match the following pattern:
5297 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5298 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5299 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5300 Op0.getOperand(0) == Op1.getOperand(0) &&
5301 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5302 isa<ConstantSDNode>(Op1.getOperand(1)));
5306 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5307 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5309 if (i * 2 < NumElts) {
5310 if (V0.getOpcode() == ISD::UNDEF) {
5311 V0 = Op0.getOperand(0);
5312 if (V0.getValueType() != VT)
5316 if (V1.getOpcode() == ISD::UNDEF) {
5317 V1 = Op0.getOperand(0);
5318 if (V1.getValueType() != VT)
5321 if (i * 2 == NumElts)
5322 ExpectedVExtractIdx = BaseIdx;
5325 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5326 if (I0 == ExpectedVExtractIdx)
5327 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5328 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5329 // Try to match the following dag sequence:
5330 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5331 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5335 ExpectedVExtractIdx += 2;
5341 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5342 /// a concat_vector.
5344 /// This is a helper function of LowerToHorizontalOp().
5345 /// This function expects two 256-bit vectors called V0 and V1.
5346 /// At first, each vector is split into two separate 128-bit vectors.
5347 /// Then, the resulting 128-bit vectors are used to implement two
5348 /// horizontal binary operations.
5350 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5352 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5353 /// the two new horizontal binop.
5354 /// When Mode is set, the first horizontal binop dag node would take as input
5355 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5356 /// horizontal binop dag node would take as input the lower 128-bit of V1
5357 /// and the upper 128-bit of V1.
5359 /// HADD V0_LO, V0_HI
5360 /// HADD V1_LO, V1_HI
5362 /// Otherwise, the first horizontal binop dag node takes as input the lower
5363 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5364 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
5366 /// HADD V0_LO, V1_LO
5367 /// HADD V0_HI, V1_HI
5369 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5370 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5371 /// the upper 128-bits of the result.
5372 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5373 SDLoc DL, SelectionDAG &DAG,
5374 unsigned X86Opcode, bool Mode,
5375 bool isUndefLO, bool isUndefHI) {
5376 EVT VT = V0.getValueType();
5377 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5378 "Invalid nodes in input!");
5380 unsigned NumElts = VT.getVectorNumElements();
5381 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5382 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5383 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5384 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5385 EVT NewVT = V0_LO.getValueType();
5387 SDValue LO = DAG.getUNDEF(NewVT);
5388 SDValue HI = DAG.getUNDEF(NewVT);
5391 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5392 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5393 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5394 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5395 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5397 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5398 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5399 V1_LO->getOpcode() != ISD::UNDEF))
5400 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5402 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5403 V1_HI->getOpcode() != ISD::UNDEF))
5404 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5407 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5410 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5412 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5413 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5414 EVT VT = BV->getValueType(0);
5415 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5416 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5420 unsigned NumElts = VT.getVectorNumElements();
5421 SDValue InVec0 = DAG.getUNDEF(VT);
5422 SDValue InVec1 = DAG.getUNDEF(VT);
5424 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5425 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5427 // Odd-numbered elements in the input build vector are obtained from
5428 // adding two integer/float elements.
5429 // Even-numbered elements in the input build vector are obtained from
5430 // subtracting two integer/float elements.
5431 unsigned ExpectedOpcode = ISD::FSUB;
5432 unsigned NextExpectedOpcode = ISD::FADD;
5433 bool AddFound = false;
5434 bool SubFound = false;
5436 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5437 SDValue Op = BV->getOperand(i);
5439 // Skip 'undef' values.
5440 unsigned Opcode = Op.getOpcode();
5441 if (Opcode == ISD::UNDEF) {
5442 std::swap(ExpectedOpcode, NextExpectedOpcode);
5446 // Early exit if we found an unexpected opcode.
5447 if (Opcode != ExpectedOpcode)
5450 SDValue Op0 = Op.getOperand(0);
5451 SDValue Op1 = Op.getOperand(1);
5453 // Try to match the following pattern:
5454 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5455 // Early exit if we cannot match that sequence.
5456 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5457 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5458 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5459 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5460 Op0.getOperand(1) != Op1.getOperand(1))
5463 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5467 // We found a valid add/sub node. Update the information accordingly.
5473 // Update InVec0 and InVec1.
5474 if (InVec0.getOpcode() == ISD::UNDEF) {
5475 InVec0 = Op0.getOperand(0);
5476 if (InVec0.getValueType() != VT)
5479 if (InVec1.getOpcode() == ISD::UNDEF) {
5480 InVec1 = Op1.getOperand(0);
5481 if (InVec1.getValueType() != VT)
5485 // Make sure that operands in input to each add/sub node always
5486 // come from a same pair of vectors.
5487 if (InVec0 != Op0.getOperand(0)) {
5488 if (ExpectedOpcode == ISD::FSUB)
5491 // FADD is commutable. Try to commute the operands
5492 // and then test again.
5493 std::swap(Op0, Op1);
5494 if (InVec0 != Op0.getOperand(0))
5498 if (InVec1 != Op1.getOperand(0))
5501 // Update the pair of expected opcodes.
5502 std::swap(ExpectedOpcode, NextExpectedOpcode);
5505 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5506 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5507 InVec1.getOpcode() != ISD::UNDEF)
5508 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5513 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5514 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5515 const X86Subtarget *Subtarget,
5516 SelectionDAG &DAG) {
5517 EVT VT = BV->getValueType(0);
5518 unsigned NumElts = VT.getVectorNumElements();
5519 unsigned NumUndefsLO = 0;
5520 unsigned NumUndefsHI = 0;
5521 unsigned Half = NumElts/2;
5523 // Count the number of UNDEF operands in the build_vector in input.
5524 for (unsigned i = 0, e = Half; i != e; ++i)
5525 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5528 for (unsigned i = Half, e = NumElts; i != e; ++i)
5529 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5532 // Early exit if this is either a build_vector of all UNDEFs or all the
5533 // operands but one are UNDEF.
5534 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5538 SDValue InVec0, InVec1;
5539 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5540 // Try to match an SSE3 float HADD/HSUB.
5541 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5542 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5544 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5545 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5546 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5547 // Try to match an SSSE3 integer HADD/HSUB.
5548 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5549 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5551 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5552 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5555 if (!Subtarget->hasAVX())
5558 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5559 // Try to match an AVX horizontal add/sub of packed single/double
5560 // precision floating point values from 256-bit vectors.
5561 SDValue InVec2, InVec3;
5562 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5563 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5564 ((InVec0.getOpcode() == ISD::UNDEF ||
5565 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5566 ((InVec1.getOpcode() == ISD::UNDEF ||
5567 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5568 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5570 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5571 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5572 ((InVec0.getOpcode() == ISD::UNDEF ||
5573 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5574 ((InVec1.getOpcode() == ISD::UNDEF ||
5575 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5576 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5577 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5578 // Try to match an AVX2 horizontal add/sub of signed integers.
5579 SDValue InVec2, InVec3;
5581 bool CanFold = true;
5583 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5584 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5585 ((InVec0.getOpcode() == ISD::UNDEF ||
5586 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5587 ((InVec1.getOpcode() == ISD::UNDEF ||
5588 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5589 X86Opcode = X86ISD::HADD;
5590 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5591 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5592 ((InVec0.getOpcode() == ISD::UNDEF ||
5593 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5594 ((InVec1.getOpcode() == ISD::UNDEF ||
5595 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5596 X86Opcode = X86ISD::HSUB;
5601 // Fold this build_vector into a single horizontal add/sub.
5602 // Do this only if the target has AVX2.
5603 if (Subtarget->hasAVX2())
5604 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5606 // Do not try to expand this build_vector into a pair of horizontal
5607 // add/sub if we can emit a pair of scalar add/sub.
5608 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5611 // Convert this build_vector into a pair of horizontal binop followed by
5613 bool isUndefLO = NumUndefsLO == Half;
5614 bool isUndefHI = NumUndefsHI == Half;
5615 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5616 isUndefLO, isUndefHI);
5620 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5621 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5623 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5624 X86Opcode = X86ISD::HADD;
5625 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5626 X86Opcode = X86ISD::HSUB;
5627 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5628 X86Opcode = X86ISD::FHADD;
5629 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5630 X86Opcode = X86ISD::FHSUB;
5634 // Don't try to expand this build_vector into a pair of horizontal add/sub
5635 // if we can simply emit a pair of scalar add/sub.
5636 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5639 // Convert this build_vector into two horizontal add/sub followed by
5641 bool isUndefLO = NumUndefsLO == Half;
5642 bool isUndefHI = NumUndefsHI == Half;
5643 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5644 isUndefLO, isUndefHI);
5651 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5654 MVT VT = Op.getSimpleValueType();
5655 MVT ExtVT = VT.getVectorElementType();
5656 unsigned NumElems = Op.getNumOperands();
5658 // Generate vectors for predicate vectors.
5659 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5660 return LowerBUILD_VECTORvXi1(Op, DAG);
5662 // Vectors containing all zeros can be matched by pxor and xorps later
5663 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5664 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5665 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5666 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5669 return getZeroVector(VT, Subtarget, DAG, dl);
5672 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5673 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5674 // vpcmpeqd on 256-bit vectors.
5675 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5676 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5679 if (!VT.is512BitVector())
5680 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5683 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5684 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5686 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5687 return HorizontalOp;
5688 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5691 unsigned EVTBits = ExtVT.getSizeInBits();
5693 unsigned NumZero = 0;
5694 unsigned NumNonZero = 0;
5695 unsigned NonZeros = 0;
5696 bool IsAllConstants = true;
5697 SmallSet<SDValue, 8> Values;
5698 for (unsigned i = 0; i < NumElems; ++i) {
5699 SDValue Elt = Op.getOperand(i);
5700 if (Elt.getOpcode() == ISD::UNDEF)
5703 if (Elt.getOpcode() != ISD::Constant &&
5704 Elt.getOpcode() != ISD::ConstantFP)
5705 IsAllConstants = false;
5706 if (X86::isZeroNode(Elt))
5709 NonZeros |= (1 << i);
5714 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5715 if (NumNonZero == 0)
5716 return DAG.getUNDEF(VT);
5718 // Special case for single non-zero, non-undef, element.
5719 if (NumNonZero == 1) {
5720 unsigned Idx = countTrailingZeros(NonZeros);
5721 SDValue Item = Op.getOperand(Idx);
5723 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5724 // the value are obviously zero, truncate the value to i32 and do the
5725 // insertion that way. Only do this if the value is non-constant or if the
5726 // value is a constant being inserted into element 0. It is cheaper to do
5727 // a constant pool load than it is to do a movd + shuffle.
5728 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5729 (!IsAllConstants || Idx == 0)) {
5730 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5732 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5733 EVT VecVT = MVT::v4i32;
5735 // Truncate the value (which may itself be a constant) to i32, and
5736 // convert it to a vector with movd (S2V+shuffle to zero extend).
5737 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5738 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5740 ISD::BITCAST, dl, VT,
5741 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
5745 // If we have a constant or non-constant insertion into the low element of
5746 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5747 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5748 // depending on what the source datatype is.
5751 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5753 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5754 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5755 if (VT.is512BitVector()) {
5756 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5757 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5758 Item, DAG.getIntPtrConstant(0, dl));
5760 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5761 "Expected an SSE value type!");
5762 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5763 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5764 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5767 // We can't directly insert an i8 or i16 into a vector, so zero extend
5769 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5770 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5771 if (VT.is256BitVector()) {
5772 if (Subtarget->hasAVX()) {
5773 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5774 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5776 // Without AVX, we need to extend to a 128-bit vector and then
5777 // insert into the 256-bit vector.
5778 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5779 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5780 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5783 assert(VT.is128BitVector() && "Expected an SSE value type!");
5784 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5785 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5787 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5791 // Is it a vector logical left shift?
5792 if (NumElems == 2 && Idx == 1 &&
5793 X86::isZeroNode(Op.getOperand(0)) &&
5794 !X86::isZeroNode(Op.getOperand(1))) {
5795 unsigned NumBits = VT.getSizeInBits();
5796 return getVShift(true, VT,
5797 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5798 VT, Op.getOperand(1)),
5799 NumBits/2, DAG, *this, dl);
5802 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5805 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5806 // is a non-constant being inserted into an element other than the low one,
5807 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5808 // movd/movss) to move this into the low element, then shuffle it into
5810 if (EVTBits == 32) {
5811 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5812 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5816 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5817 if (Values.size() == 1) {
5818 if (EVTBits == 32) {
5819 // Instead of a shuffle like this:
5820 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5821 // Check if it's possible to issue this instead.
5822 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5823 unsigned Idx = countTrailingZeros(NonZeros);
5824 SDValue Item = Op.getOperand(Idx);
5825 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5826 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5831 // A vector full of immediates; various special cases are already
5832 // handled, so this is best done with a single constant-pool load.
5836 // For AVX-length vectors, see if we can use a vector load to get all of the
5837 // elements, otherwise build the individual 128-bit pieces and use
5838 // shuffles to put them in place.
5839 if (VT.is256BitVector() || VT.is512BitVector()) {
5840 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5842 // Check for a build vector of consecutive loads.
5843 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5846 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5848 // Build both the lower and upper subvector.
5849 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5850 makeArrayRef(&V[0], NumElems/2));
5851 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5852 makeArrayRef(&V[NumElems / 2], NumElems/2));
5854 // Recreate the wider vector with the lower and upper part.
5855 if (VT.is256BitVector())
5856 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5857 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5860 // Let legalizer expand 2-wide build_vectors.
5861 if (EVTBits == 64) {
5862 if (NumNonZero == 1) {
5863 // One half is zero or undef.
5864 unsigned Idx = countTrailingZeros(NonZeros);
5865 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5866 Op.getOperand(Idx));
5867 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5872 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5873 if (EVTBits == 8 && NumElems == 16)
5874 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5878 if (EVTBits == 16 && NumElems == 8)
5879 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5883 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
5884 if (EVTBits == 32 && NumElems == 4)
5885 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
5888 // If element VT is == 32 bits, turn it into a number of shuffles.
5889 SmallVector<SDValue, 8> V(NumElems);
5890 if (NumElems == 4 && NumZero > 0) {
5891 for (unsigned i = 0; i < 4; ++i) {
5892 bool isZero = !(NonZeros & (1 << i));
5894 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5896 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5899 for (unsigned i = 0; i < 2; ++i) {
5900 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5903 V[i] = V[i*2]; // Must be a zero vector.
5906 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5909 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5912 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5917 bool Reverse1 = (NonZeros & 0x3) == 2;
5918 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5922 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5923 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5925 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5928 if (Values.size() > 1 && VT.is128BitVector()) {
5929 // Check for a build vector of consecutive loads.
5930 for (unsigned i = 0; i < NumElems; ++i)
5931 V[i] = Op.getOperand(i);
5933 // Check for elements which are consecutive loads.
5934 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5937 // Check for a build vector from mostly shuffle plus few inserting.
5938 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
5941 // For SSE 4.1, use insertps to put the high elements into the low element.
5942 if (Subtarget->hasSSE41()) {
5944 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5945 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5947 Result = DAG.getUNDEF(VT);
5949 for (unsigned i = 1; i < NumElems; ++i) {
5950 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5951 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5952 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
5957 // Otherwise, expand into a number of unpckl*, start by extending each of
5958 // our (non-undef) elements to the full vector width with the element in the
5959 // bottom slot of the vector (which generates no code for SSE).
5960 for (unsigned i = 0; i < NumElems; ++i) {
5961 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5962 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5964 V[i] = DAG.getUNDEF(VT);
5967 // Next, we iteratively mix elements, e.g. for v4f32:
5968 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5969 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5970 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5971 unsigned EltStride = NumElems >> 1;
5972 while (EltStride != 0) {
5973 for (unsigned i = 0; i < EltStride; ++i) {
5974 // If V[i+EltStride] is undef and this is the first round of mixing,
5975 // then it is safe to just drop this shuffle: V[i] is already in the
5976 // right place, the one element (since it's the first round) being
5977 // inserted as undef can be dropped. This isn't safe for successive
5978 // rounds because they will permute elements within both vectors.
5979 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5980 EltStride == NumElems/2)
5983 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5992 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5993 // to create 256-bit vectors from two other 128-bit ones.
5994 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5996 MVT ResVT = Op.getSimpleValueType();
5998 assert((ResVT.is256BitVector() ||
5999 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6001 SDValue V1 = Op.getOperand(0);
6002 SDValue V2 = Op.getOperand(1);
6003 unsigned NumElems = ResVT.getVectorNumElements();
6004 if (ResVT.is256BitVector())
6005 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6007 if (Op.getNumOperands() == 4) {
6008 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6009 ResVT.getVectorNumElements()/2);
6010 SDValue V3 = Op.getOperand(2);
6011 SDValue V4 = Op.getOperand(3);
6012 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6013 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6015 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6018 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6019 const X86Subtarget *Subtarget,
6020 SelectionDAG & DAG) {
6022 MVT ResVT = Op.getSimpleValueType();
6023 unsigned NumOfOperands = Op.getNumOperands();
6025 assert(isPowerOf2_32(NumOfOperands) &&
6026 "Unexpected number of operands in CONCAT_VECTORS");
6028 if (NumOfOperands > 2) {
6029 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6030 ResVT.getVectorNumElements()/2);
6031 SmallVector<SDValue, 2> Ops;
6032 for (unsigned i = 0; i < NumOfOperands/2; i++)
6033 Ops.push_back(Op.getOperand(i));
6034 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6036 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6037 Ops.push_back(Op.getOperand(i));
6038 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6039 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6042 SDValue V1 = Op.getOperand(0);
6043 SDValue V2 = Op.getOperand(1);
6044 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6045 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6047 if (IsZeroV1 && IsZeroV2)
6048 return getZeroVector(ResVT, Subtarget, DAG, dl);
6050 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6051 SDValue Undef = DAG.getUNDEF(ResVT);
6052 unsigned NumElems = ResVT.getVectorNumElements();
6053 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6055 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6056 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6060 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6061 // Zero the upper bits of V1
6062 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6063 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6066 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6069 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6070 const X86Subtarget *Subtarget,
6071 SelectionDAG &DAG) {
6072 MVT VT = Op.getSimpleValueType();
6073 if (VT.getVectorElementType() == MVT::i1)
6074 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6076 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6077 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6078 Op.getNumOperands() == 4)));
6080 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6081 // from two other 128-bit ones.
6083 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6084 return LowerAVXCONCAT_VECTORS(Op, DAG);
6088 //===----------------------------------------------------------------------===//
6089 // Vector shuffle lowering
6091 // This is an experimental code path for lowering vector shuffles on x86. It is
6092 // designed to handle arbitrary vector shuffles and blends, gracefully
6093 // degrading performance as necessary. It works hard to recognize idiomatic
6094 // shuffles and lower them to optimal instruction patterns without leaving
6095 // a framework that allows reasonably efficient handling of all vector shuffle
6097 //===----------------------------------------------------------------------===//
6099 /// \brief Tiny helper function to identify a no-op mask.
6101 /// This is a somewhat boring predicate function. It checks whether the mask
6102 /// array input, which is assumed to be a single-input shuffle mask of the kind
6103 /// used by the X86 shuffle instructions (not a fully general
6104 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6105 /// in-place shuffle are 'no-op's.
6106 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6107 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6108 if (Mask[i] != -1 && Mask[i] != i)
6113 /// \brief Helper function to classify a mask as a single-input mask.
6115 /// This isn't a generic single-input test because in the vector shuffle
6116 /// lowering we canonicalize single inputs to be the first input operand. This
6117 /// means we can more quickly test for a single input by only checking whether
6118 /// an input from the second operand exists. We also assume that the size of
6119 /// mask corresponds to the size of the input vectors which isn't true in the
6120 /// fully general case.
6121 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6123 if (M >= (int)Mask.size())
6128 /// \brief Test whether there are elements crossing 128-bit lanes in this
6131 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6132 /// and we routinely test for these.
6133 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6134 int LaneSize = 128 / VT.getScalarSizeInBits();
6135 int Size = Mask.size();
6136 for (int i = 0; i < Size; ++i)
6137 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6142 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6144 /// This checks a shuffle mask to see if it is performing the same
6145 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6146 /// that it is also not lane-crossing. It may however involve a blend from the
6147 /// same lane of a second vector.
6149 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6150 /// non-trivial to compute in the face of undef lanes. The representation is
6151 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6152 /// entries from both V1 and V2 inputs to the wider mask.
6154 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6155 SmallVectorImpl<int> &RepeatedMask) {
6156 int LaneSize = 128 / VT.getScalarSizeInBits();
6157 RepeatedMask.resize(LaneSize, -1);
6158 int Size = Mask.size();
6159 for (int i = 0; i < Size; ++i) {
6162 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6163 // This entry crosses lanes, so there is no way to model this shuffle.
6166 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6167 if (RepeatedMask[i % LaneSize] == -1)
6168 // This is the first non-undef entry in this slot of a 128-bit lane.
6169 RepeatedMask[i % LaneSize] =
6170 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6171 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6172 // Found a mismatch with the repeated mask.
6178 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6181 /// This is a fast way to test a shuffle mask against a fixed pattern:
6183 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6185 /// It returns true if the mask is exactly as wide as the argument list, and
6186 /// each element of the mask is either -1 (signifying undef) or the value given
6187 /// in the argument.
6188 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6189 ArrayRef<int> ExpectedMask) {
6190 if (Mask.size() != ExpectedMask.size())
6193 int Size = Mask.size();
6195 // If the values are build vectors, we can look through them to find
6196 // equivalent inputs that make the shuffles equivalent.
6197 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6198 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6200 for (int i = 0; i < Size; ++i)
6201 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6202 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6203 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6204 if (!MaskBV || !ExpectedBV ||
6205 MaskBV->getOperand(Mask[i] % Size) !=
6206 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6213 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6215 /// This helper function produces an 8-bit shuffle immediate corresponding to
6216 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6217 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6220 /// NB: We rely heavily on "undef" masks preserving the input lane.
6221 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6222 SelectionDAG &DAG) {
6223 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6224 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6225 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6226 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6227 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6230 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6231 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6232 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6233 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6234 return DAG.getConstant(Imm, DL, MVT::i8);
6237 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6239 /// This is used as a fallback approach when first class blend instructions are
6240 /// unavailable. Currently it is only suitable for integer vectors, but could
6241 /// be generalized for floating point vectors if desirable.
6242 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6243 SDValue V2, ArrayRef<int> Mask,
6244 SelectionDAG &DAG) {
6245 assert(VT.isInteger() && "Only supports integer vector types!");
6246 MVT EltVT = VT.getScalarType();
6247 int NumEltBits = EltVT.getSizeInBits();
6248 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6249 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6251 SmallVector<SDValue, 16> MaskOps;
6252 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6253 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6254 return SDValue(); // Shuffled input!
6255 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6258 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6259 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6260 // We have to cast V2 around.
6261 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6262 V2 = DAG.getNode(ISD::BITCAST, DL, VT,
6263 DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6264 DAG.getNode(ISD::BITCAST, DL, MaskVT, V1Mask),
6265 DAG.getNode(ISD::BITCAST, DL, MaskVT, V2)));
6266 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6269 /// \brief Try to emit a blend instruction for a shuffle.
6271 /// This doesn't do any checks for the availability of instructions for blending
6272 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6273 /// be matched in the backend with the type given. What it does check for is
6274 /// that the shuffle mask is in fact a blend.
6275 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6276 SDValue V2, ArrayRef<int> Mask,
6277 const X86Subtarget *Subtarget,
6278 SelectionDAG &DAG) {
6279 unsigned BlendMask = 0;
6280 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6281 if (Mask[i] >= Size) {
6282 if (Mask[i] != i + Size)
6283 return SDValue(); // Shuffled V2 input!
6284 BlendMask |= 1u << i;
6287 if (Mask[i] >= 0 && Mask[i] != i)
6288 return SDValue(); // Shuffled V1 input!
6290 switch (VT.SimpleTy) {
6295 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6296 DAG.getConstant(BlendMask, DL, MVT::i8));
6300 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6304 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6305 // that instruction.
6306 if (Subtarget->hasAVX2()) {
6307 // Scale the blend by the number of 32-bit dwords per element.
6308 int Scale = VT.getScalarSizeInBits() / 32;
6310 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6311 if (Mask[i] >= Size)
6312 for (int j = 0; j < Scale; ++j)
6313 BlendMask |= 1u << (i * Scale + j);
6315 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6316 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6317 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6318 return DAG.getNode(ISD::BITCAST, DL, VT,
6319 DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6320 DAG.getConstant(BlendMask, DL, MVT::i8)));
6324 // For integer shuffles we need to expand the mask and cast the inputs to
6325 // v8i16s prior to blending.
6326 int Scale = 8 / VT.getVectorNumElements();
6328 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6329 if (Mask[i] >= Size)
6330 for (int j = 0; j < Scale; ++j)
6331 BlendMask |= 1u << (i * Scale + j);
6333 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
6334 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
6335 return DAG.getNode(ISD::BITCAST, DL, VT,
6336 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6337 DAG.getConstant(BlendMask, DL, MVT::i8)));
6341 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6342 SmallVector<int, 8> RepeatedMask;
6343 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6344 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6345 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6347 for (int i = 0; i < 8; ++i)
6348 if (RepeatedMask[i] >= 16)
6349 BlendMask |= 1u << i;
6350 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6351 DAG.getConstant(BlendMask, DL, MVT::i8));
6357 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6358 "256-bit byte-blends require AVX2 support!");
6360 // Scale the blend by the number of bytes per element.
6361 int Scale = VT.getScalarSizeInBits() / 8;
6363 // This form of blend is always done on bytes. Compute the byte vector
6365 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6367 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6368 // mix of LLVM's code generator and the x86 backend. We tell the code
6369 // generator that boolean values in the elements of an x86 vector register
6370 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6371 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6372 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6373 // of the element (the remaining are ignored) and 0 in that high bit would
6374 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6375 // the LLVM model for boolean values in vector elements gets the relevant
6376 // bit set, it is set backwards and over constrained relative to x86's
6378 SmallVector<SDValue, 32> VSELECTMask;
6379 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6380 for (int j = 0; j < Scale; ++j)
6381 VSELECTMask.push_back(
6382 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6383 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6386 V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
6387 V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
6389 ISD::BITCAST, DL, VT,
6390 DAG.getNode(ISD::VSELECT, DL, BlendVT,
6391 DAG.getNode(ISD::BUILD_VECTOR, DL, BlendVT, VSELECTMask),
6396 llvm_unreachable("Not a supported integer vector type!");
6400 /// \brief Try to lower as a blend of elements from two inputs followed by
6401 /// a single-input permutation.
6403 /// This matches the pattern where we can blend elements from two inputs and
6404 /// then reduce the shuffle to a single-input permutation.
6405 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6408 SelectionDAG &DAG) {
6409 // We build up the blend mask while checking whether a blend is a viable way
6410 // to reduce the shuffle.
6411 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6412 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6414 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6418 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6420 if (BlendMask[Mask[i] % Size] == -1)
6421 BlendMask[Mask[i] % Size] = Mask[i];
6422 else if (BlendMask[Mask[i] % Size] != Mask[i])
6423 return SDValue(); // Can't blend in the needed input!
6425 PermuteMask[i] = Mask[i] % Size;
6428 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6429 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6432 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6433 /// blends and permutes.
6435 /// This matches the extremely common pattern for handling combined
6436 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6437 /// operations. It will try to pick the best arrangement of shuffles and
6439 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6443 SelectionDAG &DAG) {
6444 // Shuffle the input elements into the desired positions in V1 and V2 and
6445 // blend them together.
6446 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6447 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6448 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6449 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6450 if (Mask[i] >= 0 && Mask[i] < Size) {
6451 V1Mask[i] = Mask[i];
6453 } else if (Mask[i] >= Size) {
6454 V2Mask[i] = Mask[i] - Size;
6455 BlendMask[i] = i + Size;
6458 // Try to lower with the simpler initial blend strategy unless one of the
6459 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6460 // shuffle may be able to fold with a load or other benefit. However, when
6461 // we'll have to do 2x as many shuffles in order to achieve this, blending
6462 // first is a better strategy.
6463 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6464 if (SDValue BlendPerm =
6465 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6468 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6469 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6470 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6473 /// \brief Try to lower a vector shuffle as a byte rotation.
6475 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6476 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6477 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6478 /// try to generically lower a vector shuffle through such an pattern. It
6479 /// does not check for the profitability of lowering either as PALIGNR or
6480 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6481 /// This matches shuffle vectors that look like:
6483 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6485 /// Essentially it concatenates V1 and V2, shifts right by some number of
6486 /// elements, and takes the low elements as the result. Note that while this is
6487 /// specified as a *right shift* because x86 is little-endian, it is a *left
6488 /// rotate* of the vector lanes.
6489 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6492 const X86Subtarget *Subtarget,
6493 SelectionDAG &DAG) {
6494 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6496 int NumElts = Mask.size();
6497 int NumLanes = VT.getSizeInBits() / 128;
6498 int NumLaneElts = NumElts / NumLanes;
6500 // We need to detect various ways of spelling a rotation:
6501 // [11, 12, 13, 14, 15, 0, 1, 2]
6502 // [-1, 12, 13, 14, -1, -1, 1, -1]
6503 // [-1, -1, -1, -1, -1, -1, 1, 2]
6504 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6505 // [-1, 4, 5, 6, -1, -1, 9, -1]
6506 // [-1, 4, 5, 6, -1, -1, -1, -1]
6509 for (int l = 0; l < NumElts; l += NumLaneElts) {
6510 for (int i = 0; i < NumLaneElts; ++i) {
6511 if (Mask[l + i] == -1)
6513 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6515 // Get the mod-Size index and lane correct it.
6516 int LaneIdx = (Mask[l + i] % NumElts) - l;
6517 // Make sure it was in this lane.
6518 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6521 // Determine where a rotated vector would have started.
6522 int StartIdx = i - LaneIdx;
6524 // The identity rotation isn't interesting, stop.
6527 // If we found the tail of a vector the rotation must be the missing
6528 // front. If we found the head of a vector, it must be how much of the
6530 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6533 Rotation = CandidateRotation;
6534 else if (Rotation != CandidateRotation)
6535 // The rotations don't match, so we can't match this mask.
6538 // Compute which value this mask is pointing at.
6539 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6541 // Compute which of the two target values this index should be assigned
6542 // to. This reflects whether the high elements are remaining or the low
6543 // elements are remaining.
6544 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6546 // Either set up this value if we've not encountered it before, or check
6547 // that it remains consistent.
6550 else if (TargetV != MaskV)
6551 // This may be a rotation, but it pulls from the inputs in some
6552 // unsupported interleaving.
6557 // Check that we successfully analyzed the mask, and normalize the results.
6558 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6559 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6565 // The actual rotate instruction rotates bytes, so we need to scale the
6566 // rotation based on how many bytes are in the vector lane.
6567 int Scale = 16 / NumLaneElts;
6569 // SSSE3 targets can use the palignr instruction.
6570 if (Subtarget->hasSSSE3()) {
6571 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6572 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6573 Lo = DAG.getNode(ISD::BITCAST, DL, AlignVT, Lo);
6574 Hi = DAG.getNode(ISD::BITCAST, DL, AlignVT, Hi);
6576 return DAG.getNode(ISD::BITCAST, DL, VT,
6577 DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6578 DAG.getConstant(Rotation * Scale, DL,
6582 assert(VT.getSizeInBits() == 128 &&
6583 "Rotate-based lowering only supports 128-bit lowering!");
6584 assert(Mask.size() <= 16 &&
6585 "Can shuffle at most 16 bytes in a 128-bit vector!");
6587 // Default SSE2 implementation
6588 int LoByteShift = 16 - Rotation * Scale;
6589 int HiByteShift = Rotation * Scale;
6591 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6592 Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Lo);
6593 Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Hi);
6595 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6596 DAG.getConstant(LoByteShift, DL, MVT::i8));
6597 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6598 DAG.getConstant(HiByteShift, DL, MVT::i8));
6599 return DAG.getNode(ISD::BITCAST, DL, VT,
6600 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6603 /// \brief Compute whether each element of a shuffle is zeroable.
6605 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6606 /// Either it is an undef element in the shuffle mask, the element of the input
6607 /// referenced is undef, or the element of the input referenced is known to be
6608 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6609 /// as many lanes with this technique as possible to simplify the remaining
6611 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6612 SDValue V1, SDValue V2) {
6613 SmallBitVector Zeroable(Mask.size(), false);
6615 while (V1.getOpcode() == ISD::BITCAST)
6616 V1 = V1->getOperand(0);
6617 while (V2.getOpcode() == ISD::BITCAST)
6618 V2 = V2->getOperand(0);
6620 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6621 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6623 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6625 // Handle the easy cases.
6626 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6631 // If this is an index into a build_vector node (which has the same number
6632 // of elements), dig out the input value and use it.
6633 SDValue V = M < Size ? V1 : V2;
6634 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6637 SDValue Input = V.getOperand(M % Size);
6638 // The UNDEF opcode check really should be dead code here, but not quite
6639 // worth asserting on (it isn't invalid, just unexpected).
6640 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6647 /// \brief Try to emit a bitmask instruction for a shuffle.
6649 /// This handles cases where we can model a blend exactly as a bitmask due to
6650 /// one of the inputs being zeroable.
6651 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6652 SDValue V2, ArrayRef<int> Mask,
6653 SelectionDAG &DAG) {
6654 MVT EltVT = VT.getScalarType();
6655 int NumEltBits = EltVT.getSizeInBits();
6656 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6657 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6658 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6660 if (EltVT.isFloatingPoint()) {
6661 Zero = DAG.getNode(ISD::BITCAST, DL, EltVT, Zero);
6662 AllOnes = DAG.getNode(ISD::BITCAST, DL, EltVT, AllOnes);
6664 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6665 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6667 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6670 if (Mask[i] % Size != i)
6671 return SDValue(); // Not a blend.
6673 V = Mask[i] < Size ? V1 : V2;
6674 else if (V != (Mask[i] < Size ? V1 : V2))
6675 return SDValue(); // Can only let one input through the mask.
6677 VMaskOps[i] = AllOnes;
6680 return SDValue(); // No non-zeroable elements!
6682 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6683 V = DAG.getNode(VT.isFloatingPoint()
6684 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6689 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6691 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6692 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6693 /// matches elements from one of the input vectors shuffled to the left or
6694 /// right with zeroable elements 'shifted in'. It handles both the strictly
6695 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6698 /// PSHL : (little-endian) left bit shift.
6699 /// [ zz, 0, zz, 2 ]
6700 /// [ -1, 4, zz, -1 ]
6701 /// PSRL : (little-endian) right bit shift.
6703 /// [ -1, -1, 7, zz]
6704 /// PSLLDQ : (little-endian) left byte shift
6705 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6706 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6707 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6708 /// PSRLDQ : (little-endian) right byte shift
6709 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6710 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6711 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6712 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6713 SDValue V2, ArrayRef<int> Mask,
6714 SelectionDAG &DAG) {
6715 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6717 int Size = Mask.size();
6718 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6720 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6721 for (int i = 0; i < Size; i += Scale)
6722 for (int j = 0; j < Shift; ++j)
6723 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6729 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6730 for (int i = 0; i != Size; i += Scale) {
6731 unsigned Pos = Left ? i + Shift : i;
6732 unsigned Low = Left ? i : i + Shift;
6733 unsigned Len = Scale - Shift;
6734 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6735 Low + (V == V1 ? 0 : Size)))
6739 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6740 bool ByteShift = ShiftEltBits > 64;
6741 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6742 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6743 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6745 // Normalize the scale for byte shifts to still produce an i64 element
6747 Scale = ByteShift ? Scale / 2 : Scale;
6749 // We need to round trip through the appropriate type for the shift.
6750 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6751 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6752 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6753 "Illegal integer vector type");
6754 V = DAG.getNode(ISD::BITCAST, DL, ShiftVT, V);
6756 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6757 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6758 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6761 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6762 // keep doubling the size of the integer elements up to that. We can
6763 // then shift the elements of the integer vector by whole multiples of
6764 // their width within the elements of the larger integer vector. Test each
6765 // multiple to see if we can find a match with the moved element indices
6766 // and that the shifted in elements are all zeroable.
6767 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6768 for (int Shift = 1; Shift != Scale; ++Shift)
6769 for (bool Left : {true, false})
6770 if (CheckZeros(Shift, Scale, Left))
6771 for (SDValue V : {V1, V2})
6772 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6779 /// \brief Lower a vector shuffle as a zero or any extension.
6781 /// Given a specific number of elements, element bit width, and extension
6782 /// stride, produce either a zero or any extension based on the available
6783 /// features of the subtarget.
6784 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6785 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6786 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6787 assert(Scale > 1 && "Need a scale to extend.");
6788 int NumElements = VT.getVectorNumElements();
6789 int EltBits = VT.getScalarSizeInBits();
6790 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6791 "Only 8, 16, and 32 bit elements can be extended.");
6792 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6794 // Found a valid zext mask! Try various lowering strategies based on the
6795 // input type and available ISA extensions.
6796 if (Subtarget->hasSSE41()) {
6797 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6798 NumElements / Scale);
6799 return DAG.getNode(ISD::BITCAST, DL, VT,
6800 DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6803 // For any extends we can cheat for larger element sizes and use shuffle
6804 // instructions that can fold with a load and/or copy.
6805 if (AnyExt && EltBits == 32) {
6806 int PSHUFDMask[4] = {0, -1, 1, -1};
6808 ISD::BITCAST, DL, VT,
6809 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6810 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6811 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6813 if (AnyExt && EltBits == 16 && Scale > 2) {
6814 int PSHUFDMask[4] = {0, -1, 0, -1};
6815 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6816 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
6817 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6818 int PSHUFHWMask[4] = {1, -1, -1, -1};
6820 ISD::BITCAST, DL, VT,
6821 DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6822 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
6823 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6826 // If this would require more than 2 unpack instructions to expand, use
6827 // pshufb when available. We can only use more than 2 unpack instructions
6828 // when zero extending i8 elements which also makes it easier to use pshufb.
6829 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6830 assert(NumElements == 16 && "Unexpected byte vector width!");
6831 SDValue PSHUFBMask[16];
6832 for (int i = 0; i < 16; ++i)
6834 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6835 InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
6836 return DAG.getNode(ISD::BITCAST, DL, VT,
6837 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6838 DAG.getNode(ISD::BUILD_VECTOR, DL,
6839 MVT::v16i8, PSHUFBMask)));
6842 // Otherwise emit a sequence of unpacks.
6844 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6845 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6846 : getZeroVector(InputVT, Subtarget, DAG, DL);
6847 InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
6848 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6852 } while (Scale > 1);
6853 return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
6856 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6858 /// This routine will try to do everything in its power to cleverly lower
6859 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6860 /// check for the profitability of this lowering, it tries to aggressively
6861 /// match this pattern. It will use all of the micro-architectural details it
6862 /// can to emit an efficient lowering. It handles both blends with all-zero
6863 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6864 /// masking out later).
6866 /// The reason we have dedicated lowering for zext-style shuffles is that they
6867 /// are both incredibly common and often quite performance sensitive.
6868 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
6869 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
6870 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6871 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6873 int Bits = VT.getSizeInBits();
6874 int NumElements = VT.getVectorNumElements();
6875 assert(VT.getScalarSizeInBits() <= 32 &&
6876 "Exceeds 32-bit integer zero extension limit");
6877 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
6879 // Define a helper function to check a particular ext-scale and lower to it if
6881 auto Lower = [&](int Scale) -> SDValue {
6884 for (int i = 0; i < NumElements; ++i) {
6886 continue; // Valid anywhere but doesn't tell us anything.
6887 if (i % Scale != 0) {
6888 // Each of the extended elements need to be zeroable.
6892 // We no longer are in the anyext case.
6897 // Each of the base elements needs to be consecutive indices into the
6898 // same input vector.
6899 SDValue V = Mask[i] < NumElements ? V1 : V2;
6902 else if (InputV != V)
6903 return SDValue(); // Flip-flopping inputs.
6905 if (Mask[i] % NumElements != i / Scale)
6906 return SDValue(); // Non-consecutive strided elements.
6909 // If we fail to find an input, we have a zero-shuffle which should always
6910 // have already been handled.
6911 // FIXME: Maybe handle this here in case during blending we end up with one?
6915 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6916 DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
6919 // The widest scale possible for extending is to a 64-bit integer.
6920 assert(Bits % 64 == 0 &&
6921 "The number of bits in a vector must be divisible by 64 on x86!");
6922 int NumExtElements = Bits / 64;
6924 // Each iteration, try extending the elements half as much, but into twice as
6926 for (; NumExtElements < NumElements; NumExtElements *= 2) {
6927 assert(NumElements % NumExtElements == 0 &&
6928 "The input vector size must be divisible by the extended size.");
6929 if (SDValue V = Lower(NumElements / NumExtElements))
6933 // General extends failed, but 128-bit vectors may be able to use MOVQ.
6937 // Returns one of the source operands if the shuffle can be reduced to a
6938 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
6939 auto CanZExtLowHalf = [&]() {
6940 for (int i = NumElements / 2; i != NumElements; ++i)
6943 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
6945 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
6950 if (SDValue V = CanZExtLowHalf()) {
6951 V = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V);
6952 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
6953 return DAG.getNode(ISD::BITCAST, DL, VT, V);
6956 // No viable ext lowering found.
6960 /// \brief Try to get a scalar value for a specific element of a vector.
6962 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
6963 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
6964 SelectionDAG &DAG) {
6965 MVT VT = V.getSimpleValueType();
6966 MVT EltVT = VT.getVectorElementType();
6967 while (V.getOpcode() == ISD::BITCAST)
6968 V = V.getOperand(0);
6969 // If the bitcasts shift the element size, we can't extract an equivalent
6971 MVT NewVT = V.getSimpleValueType();
6972 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
6975 if (V.getOpcode() == ISD::BUILD_VECTOR ||
6976 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
6977 // Ensure the scalar operand is the same size as the destination.
6978 // FIXME: Add support for scalar truncation where possible.
6979 SDValue S = V.getOperand(Idx);
6980 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
6981 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
6987 /// \brief Helper to test for a load that can be folded with x86 shuffles.
6989 /// This is particularly important because the set of instructions varies
6990 /// significantly based on whether the operand is a load or not.
6991 static bool isShuffleFoldableLoad(SDValue V) {
6992 while (V.getOpcode() == ISD::BITCAST)
6993 V = V.getOperand(0);
6995 return ISD::isNON_EXTLoad(V.getNode());
6998 /// \brief Try to lower insertion of a single element into a zero vector.
7000 /// This is a common pattern that we have especially efficient patterns to lower
7001 /// across all subtarget feature sets.
7002 static SDValue lowerVectorShuffleAsElementInsertion(
7003 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7004 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7005 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7007 MVT EltVT = VT.getVectorElementType();
7009 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7010 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7012 bool IsV1Zeroable = true;
7013 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7014 if (i != V2Index && !Zeroable[i]) {
7015 IsV1Zeroable = false;
7019 // Check for a single input from a SCALAR_TO_VECTOR node.
7020 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7021 // all the smarts here sunk into that routine. However, the current
7022 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7023 // vector shuffle lowering is dead.
7024 if (SDValue V2S = getScalarValueForVectorElement(
7025 V2, Mask[V2Index] - Mask.size(), DAG)) {
7026 // We need to zext the scalar if it is smaller than an i32.
7027 V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7028 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7029 // Using zext to expand a narrow element won't work for non-zero
7034 // Zero-extend directly to i32.
7036 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7038 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7039 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7040 EltVT == MVT::i16) {
7041 // Either not inserting from the low element of the input or the input
7042 // element size is too small to use VZEXT_MOVL to clear the high bits.
7046 if (!IsV1Zeroable) {
7047 // If V1 can't be treated as a zero vector we have fewer options to lower
7048 // this. We can't support integer vectors or non-zero targets cheaply, and
7049 // the V1 elements can't be permuted in any way.
7050 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7051 if (!VT.isFloatingPoint() || V2Index != 0)
7053 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7054 V1Mask[V2Index] = -1;
7055 if (!isNoopShuffleMask(V1Mask))
7057 // This is essentially a special case blend operation, but if we have
7058 // general purpose blend operations, they are always faster. Bail and let
7059 // the rest of the lowering handle these as blends.
7060 if (Subtarget->hasSSE41())
7063 // Otherwise, use MOVSD or MOVSS.
7064 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7065 "Only two types of floating point element types to handle!");
7066 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7070 // This lowering only works for the low element with floating point vectors.
7071 if (VT.isFloatingPoint() && V2Index != 0)
7074 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7076 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7079 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7080 // the desired position. Otherwise it is more efficient to do a vector
7081 // shift left. We know that we can do a vector shift left because all
7082 // the inputs are zero.
7083 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7084 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7085 V2Shuffle[V2Index] = 0;
7086 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7088 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7090 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7092 V2Index * EltVT.getSizeInBits()/8, DL,
7093 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7094 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7100 /// \brief Try to lower broadcast of a single element.
7102 /// For convenience, this code also bundles all of the subtarget feature set
7103 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7104 /// a convenient way to factor it out.
7105 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7107 const X86Subtarget *Subtarget,
7108 SelectionDAG &DAG) {
7109 if (!Subtarget->hasAVX())
7111 if (VT.isInteger() && !Subtarget->hasAVX2())
7114 // Check that the mask is a broadcast.
7115 int BroadcastIdx = -1;
7117 if (M >= 0 && BroadcastIdx == -1)
7119 else if (M >= 0 && M != BroadcastIdx)
7122 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7123 "a sorted mask where the broadcast "
7126 // Go up the chain of (vector) values to find a scalar load that we can
7127 // combine with the broadcast.
7129 switch (V.getOpcode()) {
7130 case ISD::CONCAT_VECTORS: {
7131 int OperandSize = Mask.size() / V.getNumOperands();
7132 V = V.getOperand(BroadcastIdx / OperandSize);
7133 BroadcastIdx %= OperandSize;
7137 case ISD::INSERT_SUBVECTOR: {
7138 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7139 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7143 int BeginIdx = (int)ConstantIdx->getZExtValue();
7145 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7146 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7147 BroadcastIdx -= BeginIdx;
7158 // Check if this is a broadcast of a scalar. We special case lowering
7159 // for scalars so that we can more effectively fold with loads.
7160 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7161 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7162 V = V.getOperand(BroadcastIdx);
7164 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7165 // Only AVX2 has register broadcasts.
7166 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7168 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7169 // We can't broadcast from a vector register without AVX2, and we can only
7170 // broadcast from the zero-element of a vector register.
7174 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7177 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7178 // INSERTPS when the V1 elements are already in the correct locations
7179 // because otherwise we can just always use two SHUFPS instructions which
7180 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7181 // perform INSERTPS if a single V1 element is out of place and all V2
7182 // elements are zeroable.
7183 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7185 SelectionDAG &DAG) {
7186 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7187 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7188 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7189 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7191 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7194 int V1DstIndex = -1;
7195 int V2DstIndex = -1;
7196 bool V1UsedInPlace = false;
7198 for (int i = 0; i < 4; ++i) {
7199 // Synthesize a zero mask from the zeroable elements (includes undefs).
7205 // Flag if we use any V1 inputs in place.
7207 V1UsedInPlace = true;
7211 // We can only insert a single non-zeroable element.
7212 if (V1DstIndex != -1 || V2DstIndex != -1)
7216 // V1 input out of place for insertion.
7219 // V2 input for insertion.
7224 // Don't bother if we have no (non-zeroable) element for insertion.
7225 if (V1DstIndex == -1 && V2DstIndex == -1)
7228 // Determine element insertion src/dst indices. The src index is from the
7229 // start of the inserted vector, not the start of the concatenated vector.
7230 unsigned V2SrcIndex = 0;
7231 if (V1DstIndex != -1) {
7232 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7233 // and don't use the original V2 at all.
7234 V2SrcIndex = Mask[V1DstIndex];
7235 V2DstIndex = V1DstIndex;
7238 V2SrcIndex = Mask[V2DstIndex] - 4;
7241 // If no V1 inputs are used in place, then the result is created only from
7242 // the zero mask and the V2 insertion - so remove V1 dependency.
7244 V1 = DAG.getUNDEF(MVT::v4f32);
7246 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7247 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7249 // Insert the V2 element into the desired position.
7251 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7252 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7255 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7256 /// UNPCK instruction.
7258 /// This specifically targets cases where we end up with alternating between
7259 /// the two inputs, and so can permute them into something that feeds a single
7260 /// UNPCK instruction. Note that this routine only targets integer vectors
7261 /// because for floating point vectors we have a generalized SHUFPS lowering
7262 /// strategy that handles everything that doesn't *exactly* match an unpack,
7263 /// making this clever lowering unnecessary.
7264 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7265 SDValue V2, ArrayRef<int> Mask,
7266 SelectionDAG &DAG) {
7267 assert(!VT.isFloatingPoint() &&
7268 "This routine only supports integer vectors.");
7269 assert(!isSingleInputShuffleMask(Mask) &&
7270 "This routine should only be used when blending two inputs.");
7271 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7273 int Size = Mask.size();
7275 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7276 return M >= 0 && M % Size < Size / 2;
7278 int NumHiInputs = std::count_if(
7279 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7281 bool UnpackLo = NumLoInputs >= NumHiInputs;
7283 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7284 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7285 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7287 for (int i = 0; i < Size; ++i) {
7291 // Each element of the unpack contains Scale elements from this mask.
7292 int UnpackIdx = i / Scale;
7294 // We only handle the case where V1 feeds the first slots of the unpack.
7295 // We rely on canonicalization to ensure this is the case.
7296 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7299 // Setup the mask for this input. The indexing is tricky as we have to
7300 // handle the unpack stride.
7301 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7302 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7306 // If we will have to shuffle both inputs to use the unpack, check whether
7307 // we can just unpack first and shuffle the result. If so, skip this unpack.
7308 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7309 !isNoopShuffleMask(V2Mask))
7312 // Shuffle the inputs into place.
7313 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7314 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7316 // Cast the inputs to the type we will use to unpack them.
7317 V1 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V1);
7318 V2 = DAG.getNode(ISD::BITCAST, DL, UnpackVT, V2);
7320 // Unpack the inputs and cast the result back to the desired type.
7321 return DAG.getNode(ISD::BITCAST, DL, VT,
7322 DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7323 DL, UnpackVT, V1, V2));
7326 // We try each unpack from the largest to the smallest to try and find one
7327 // that fits this mask.
7328 int OrigNumElements = VT.getVectorNumElements();
7329 int OrigScalarSize = VT.getScalarSizeInBits();
7330 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7331 int Scale = ScalarSize / OrigScalarSize;
7332 int NumElements = OrigNumElements / Scale;
7333 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7334 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7338 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7340 if (NumLoInputs == 0 || NumHiInputs == 0) {
7341 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7342 "We have to have *some* inputs!");
7343 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7345 // FIXME: We could consider the total complexity of the permute of each
7346 // possible unpacking. Or at the least we should consider how many
7347 // half-crossings are created.
7348 // FIXME: We could consider commuting the unpacks.
7350 SmallVector<int, 32> PermMask;
7351 PermMask.assign(Size, -1);
7352 for (int i = 0; i < Size; ++i) {
7356 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7359 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7361 return DAG.getVectorShuffle(
7362 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7364 DAG.getUNDEF(VT), PermMask);
7370 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7372 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7373 /// support for floating point shuffles but not integer shuffles. These
7374 /// instructions will incur a domain crossing penalty on some chips though so
7375 /// it is better to avoid lowering through this for integer vectors where
7377 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7378 const X86Subtarget *Subtarget,
7379 SelectionDAG &DAG) {
7381 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7382 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7383 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7384 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7385 ArrayRef<int> Mask = SVOp->getMask();
7386 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7388 if (isSingleInputShuffleMask(Mask)) {
7389 // Use low duplicate instructions for masks that match their pattern.
7390 if (Subtarget->hasSSE3())
7391 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7392 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7394 // Straight shuffle of a single input vector. Simulate this by using the
7395 // single input as both of the "inputs" to this instruction..
7396 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7398 if (Subtarget->hasAVX()) {
7399 // If we have AVX, we can use VPERMILPS which will allow folding a load
7400 // into the shuffle.
7401 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7402 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7405 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7406 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7408 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7409 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7411 // If we have a single input, insert that into V1 if we can do so cheaply.
7412 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7413 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7414 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7416 // Try inverting the insertion since for v2 masks it is easy to do and we
7417 // can't reliably sort the mask one way or the other.
7418 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7419 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7420 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7421 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7425 // Try to use one of the special instruction patterns to handle two common
7426 // blend patterns if a zero-blend above didn't work.
7427 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7428 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7429 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7430 // We can either use a special instruction to load over the low double or
7431 // to move just the low double.
7433 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7435 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7437 if (Subtarget->hasSSE41())
7438 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7442 // Use dedicated unpack instructions for masks that match their pattern.
7443 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7444 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7445 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7446 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7448 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7449 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7450 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7453 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7455 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7456 /// the integer unit to minimize domain crossing penalties. However, for blends
7457 /// it falls back to the floating point shuffle operation with appropriate bit
7459 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7460 const X86Subtarget *Subtarget,
7461 SelectionDAG &DAG) {
7463 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7464 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7465 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7467 ArrayRef<int> Mask = SVOp->getMask();
7468 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7470 if (isSingleInputShuffleMask(Mask)) {
7471 // Check for being able to broadcast a single element.
7472 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7473 Mask, Subtarget, DAG))
7476 // Straight shuffle of a single input vector. For everything from SSE2
7477 // onward this has a single fast instruction with no scary immediates.
7478 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7479 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7480 int WidenedMask[4] = {
7481 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7482 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7484 ISD::BITCAST, DL, MVT::v2i64,
7485 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7486 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7488 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7489 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7490 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7491 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7493 // If we have a blend of two PACKUS operations an the blend aligns with the
7494 // low and half halves, we can just merge the PACKUS operations. This is
7495 // particularly important as it lets us merge shuffles that this routine itself
7497 auto GetPackNode = [](SDValue V) {
7498 while (V.getOpcode() == ISD::BITCAST)
7499 V = V.getOperand(0);
7501 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7503 if (SDValue V1Pack = GetPackNode(V1))
7504 if (SDValue V2Pack = GetPackNode(V2))
7505 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7506 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7507 Mask[0] == 0 ? V1Pack.getOperand(0)
7508 : V1Pack.getOperand(1),
7509 Mask[1] == 2 ? V2Pack.getOperand(0)
7510 : V2Pack.getOperand(1)));
7512 // Try to use shift instructions.
7514 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7517 // When loading a scalar and then shuffling it into a vector we can often do
7518 // the insertion cheaply.
7519 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7520 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7522 // Try inverting the insertion since for v2 masks it is easy to do and we
7523 // can't reliably sort the mask one way or the other.
7524 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7525 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7526 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7529 // We have different paths for blend lowering, but they all must use the
7530 // *exact* same predicate.
7531 bool IsBlendSupported = Subtarget->hasSSE41();
7532 if (IsBlendSupported)
7533 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7537 // Use dedicated unpack instructions for masks that match their pattern.
7538 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7539 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7540 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7541 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7543 // Try to use byte rotation instructions.
7544 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7545 if (Subtarget->hasSSSE3())
7546 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7547 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7550 // If we have direct support for blends, we should lower by decomposing into
7551 // a permute. That will be faster than the domain cross.
7552 if (IsBlendSupported)
7553 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7556 // We implement this with SHUFPD which is pretty lame because it will likely
7557 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7558 // However, all the alternatives are still more cycles and newer chips don't
7559 // have this problem. It would be really nice if x86 had better shuffles here.
7560 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7561 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7562 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7563 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7566 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7568 /// This is used to disable more specialized lowerings when the shufps lowering
7569 /// will happen to be efficient.
7570 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7571 // This routine only handles 128-bit shufps.
7572 assert(Mask.size() == 4 && "Unsupported mask size!");
7574 // To lower with a single SHUFPS we need to have the low half and high half
7575 // each requiring a single input.
7576 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7578 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7584 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7586 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7587 /// It makes no assumptions about whether this is the *best* lowering, it simply
7589 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7590 ArrayRef<int> Mask, SDValue V1,
7591 SDValue V2, SelectionDAG &DAG) {
7592 SDValue LowV = V1, HighV = V2;
7593 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7596 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7598 if (NumV2Elements == 1) {
7600 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7603 // Compute the index adjacent to V2Index and in the same half by toggling
7605 int V2AdjIndex = V2Index ^ 1;
7607 if (Mask[V2AdjIndex] == -1) {
7608 // Handles all the cases where we have a single V2 element and an undef.
7609 // This will only ever happen in the high lanes because we commute the
7610 // vector otherwise.
7612 std::swap(LowV, HighV);
7613 NewMask[V2Index] -= 4;
7615 // Handle the case where the V2 element ends up adjacent to a V1 element.
7616 // To make this work, blend them together as the first step.
7617 int V1Index = V2AdjIndex;
7618 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7619 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7620 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7622 // Now proceed to reconstruct the final blend as we have the necessary
7623 // high or low half formed.
7630 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7631 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7633 } else if (NumV2Elements == 2) {
7634 if (Mask[0] < 4 && Mask[1] < 4) {
7635 // Handle the easy case where we have V1 in the low lanes and V2 in the
7639 } else if (Mask[2] < 4 && Mask[3] < 4) {
7640 // We also handle the reversed case because this utility may get called
7641 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7642 // arrange things in the right direction.
7648 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7649 // trying to place elements directly, just blend them and set up the final
7650 // shuffle to place them.
7652 // The first two blend mask elements are for V1, the second two are for
7654 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7655 Mask[2] < 4 ? Mask[2] : Mask[3],
7656 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7657 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7658 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7659 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7661 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7664 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7665 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7666 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7667 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7670 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7671 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7674 /// \brief Lower 4-lane 32-bit floating point shuffles.
7676 /// Uses instructions exclusively from the floating point unit to minimize
7677 /// domain crossing penalties, as these are sufficient to implement all v4f32
7679 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7680 const X86Subtarget *Subtarget,
7681 SelectionDAG &DAG) {
7683 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7684 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7685 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7686 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7687 ArrayRef<int> Mask = SVOp->getMask();
7688 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7691 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7693 if (NumV2Elements == 0) {
7694 // Check for being able to broadcast a single element.
7695 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7696 Mask, Subtarget, DAG))
7699 // Use even/odd duplicate instructions for masks that match their pattern.
7700 if (Subtarget->hasSSE3()) {
7701 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7702 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7703 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7704 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7707 if (Subtarget->hasAVX()) {
7708 // If we have AVX, we can use VPERMILPS which will allow folding a load
7709 // into the shuffle.
7710 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7711 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7714 // Otherwise, use a straight shuffle of a single input vector. We pass the
7715 // input vector to both operands to simulate this with a SHUFPS.
7716 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7717 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7720 // There are special ways we can lower some single-element blends. However, we
7721 // have custom ways we can lower more complex single-element blends below that
7722 // we defer to if both this and BLENDPS fail to match, so restrict this to
7723 // when the V2 input is targeting element 0 of the mask -- that is the fast
7725 if (NumV2Elements == 1 && Mask[0] >= 4)
7726 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7727 Mask, Subtarget, DAG))
7730 if (Subtarget->hasSSE41()) {
7731 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7735 // Use INSERTPS if we can complete the shuffle efficiently.
7736 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7739 if (!isSingleSHUFPSMask(Mask))
7740 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7741 DL, MVT::v4f32, V1, V2, Mask, DAG))
7745 // Use dedicated unpack instructions for masks that match their pattern.
7746 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7747 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7748 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7749 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7750 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7751 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7752 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7753 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7755 // Otherwise fall back to a SHUFPS lowering strategy.
7756 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7759 /// \brief Lower 4-lane i32 vector shuffles.
7761 /// We try to handle these with integer-domain shuffles where we can, but for
7762 /// blends we use the floating point domain blend instructions.
7763 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7764 const X86Subtarget *Subtarget,
7765 SelectionDAG &DAG) {
7767 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7768 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7769 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7771 ArrayRef<int> Mask = SVOp->getMask();
7772 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7774 // Whenever we can lower this as a zext, that instruction is strictly faster
7775 // than any alternative. It also allows us to fold memory operands into the
7776 // shuffle in many cases.
7777 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7778 Mask, Subtarget, DAG))
7782 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7784 if (NumV2Elements == 0) {
7785 // Check for being able to broadcast a single element.
7786 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7787 Mask, Subtarget, DAG))
7790 // Straight shuffle of a single input vector. For everything from SSE2
7791 // onward this has a single fast instruction with no scary immediates.
7792 // We coerce the shuffle pattern to be compatible with UNPCK instructions
7793 // but we aren't actually going to use the UNPCK instruction because doing
7794 // so prevents folding a load into this instruction or making a copy.
7795 const int UnpackLoMask[] = {0, 0, 1, 1};
7796 const int UnpackHiMask[] = {2, 2, 3, 3};
7797 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7798 Mask = UnpackLoMask;
7799 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7800 Mask = UnpackHiMask;
7802 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7803 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7806 // Try to use shift instructions.
7808 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7811 // There are special ways we can lower some single-element blends.
7812 if (NumV2Elements == 1)
7813 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7814 Mask, Subtarget, DAG))
7817 // We have different paths for blend lowering, but they all must use the
7818 // *exact* same predicate.
7819 bool IsBlendSupported = Subtarget->hasSSE41();
7820 if (IsBlendSupported)
7821 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7825 if (SDValue Masked =
7826 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7829 // Use dedicated unpack instructions for masks that match their pattern.
7830 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7831 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7832 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7833 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7834 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7835 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7836 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7837 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7839 // Try to use byte rotation instructions.
7840 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7841 if (Subtarget->hasSSSE3())
7842 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7843 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7846 // If we have direct support for blends, we should lower by decomposing into
7847 // a permute. That will be faster than the domain cross.
7848 if (IsBlendSupported)
7849 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7852 // Try to lower by permuting the inputs into an unpack instruction.
7853 if (SDValue Unpack =
7854 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7857 // We implement this with SHUFPS because it can blend from two vectors.
7858 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7859 // up the inputs, bypassing domain shift penalties that we would encur if we
7860 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7862 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7863 DAG.getVectorShuffle(
7865 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7866 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7869 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7870 /// shuffle lowering, and the most complex part.
7872 /// The lowering strategy is to try to form pairs of input lanes which are
7873 /// targeted at the same half of the final vector, and then use a dword shuffle
7874 /// to place them onto the right half, and finally unpack the paired lanes into
7875 /// their final position.
7877 /// The exact breakdown of how to form these dword pairs and align them on the
7878 /// correct sides is really tricky. See the comments within the function for
7879 /// more of the details.
7881 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
7882 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
7883 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
7884 /// vector, form the analogous 128-bit 8-element Mask.
7885 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
7886 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
7887 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7888 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
7889 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
7891 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
7892 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7893 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7895 SmallVector<int, 4> LoInputs;
7896 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7897 [](int M) { return M >= 0; });
7898 std::sort(LoInputs.begin(), LoInputs.end());
7899 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7900 SmallVector<int, 4> HiInputs;
7901 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7902 [](int M) { return M >= 0; });
7903 std::sort(HiInputs.begin(), HiInputs.end());
7904 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7906 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7907 int NumHToL = LoInputs.size() - NumLToL;
7909 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7910 int NumHToH = HiInputs.size() - NumLToH;
7911 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7912 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7913 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7914 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7916 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7917 // such inputs we can swap two of the dwords across the half mark and end up
7918 // with <=2 inputs to each half in each half. Once there, we can fall through
7919 // to the generic code below. For example:
7921 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7922 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7924 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7925 // and an existing 2-into-2 on the other half. In this case we may have to
7926 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7927 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7928 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7929 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7930 // half than the one we target for fixing) will be fixed when we re-enter this
7931 // path. We will also combine away any sequence of PSHUFD instructions that
7932 // result into a single instruction. Here is an example of the tricky case:
7934 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7935 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7937 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7939 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7940 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7942 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7943 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7945 // The result is fine to be handled by the generic logic.
7946 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7947 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7948 int AOffset, int BOffset) {
7949 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7950 "Must call this with A having 3 or 1 inputs from the A half.");
7951 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7952 "Must call this with B having 1 or 3 inputs from the B half.");
7953 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7954 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7956 // Compute the index of dword with only one word among the three inputs in
7957 // a half by taking the sum of the half with three inputs and subtracting
7958 // the sum of the actual three inputs. The difference is the remaining
7961 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7962 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7963 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7964 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7965 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7966 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7967 int TripleNonInputIdx =
7968 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7969 TripleDWord = TripleNonInputIdx / 2;
7971 // We use xor with one to compute the adjacent DWord to whichever one the
7973 OneInputDWord = (OneInput / 2) ^ 1;
7975 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7976 // and BToA inputs. If there is also such a problem with the BToB and AToB
7977 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7978 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7979 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7980 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7981 // Compute how many inputs will be flipped by swapping these DWords. We
7983 // to balance this to ensure we don't form a 3-1 shuffle in the other
7985 int NumFlippedAToBInputs =
7986 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7987 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7988 int NumFlippedBToBInputs =
7989 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7990 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7991 if ((NumFlippedAToBInputs == 1 &&
7992 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7993 (NumFlippedBToBInputs == 1 &&
7994 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7995 // We choose whether to fix the A half or B half based on whether that
7996 // half has zero flipped inputs. At zero, we may not be able to fix it
7997 // with that half. We also bias towards fixing the B half because that
7998 // will more commonly be the high half, and we have to bias one way.
7999 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8000 ArrayRef<int> Inputs) {
8001 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8002 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8003 PinnedIdx ^ 1) != Inputs.end();
8004 // Determine whether the free index is in the flipped dword or the
8005 // unflipped dword based on where the pinned index is. We use this bit
8006 // in an xor to conditionally select the adjacent dword.
8007 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8008 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8009 FixFreeIdx) != Inputs.end();
8010 if (IsFixIdxInput == IsFixFreeIdxInput)
8012 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8013 FixFreeIdx) != Inputs.end();
8014 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8015 "We need to be changing the number of flipped inputs!");
8016 int PSHUFHalfMask[] = {0, 1, 2, 3};
8017 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8018 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8020 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8023 if (M != -1 && M == FixIdx)
8025 else if (M != -1 && M == FixFreeIdx)
8028 if (NumFlippedBToBInputs != 0) {
8030 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8031 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8033 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8035 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8036 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8041 int PSHUFDMask[] = {0, 1, 2, 3};
8042 PSHUFDMask[ADWord] = BDWord;
8043 PSHUFDMask[BDWord] = ADWord;
8044 V = DAG.getNode(ISD::BITCAST, DL, VT,
8045 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8046 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8047 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8050 // Adjust the mask to match the new locations of A and B.
8052 if (M != -1 && M/2 == ADWord)
8053 M = 2 * BDWord + M % 2;
8054 else if (M != -1 && M/2 == BDWord)
8055 M = 2 * ADWord + M % 2;
8057 // Recurse back into this routine to re-compute state now that this isn't
8058 // a 3 and 1 problem.
8059 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8062 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8063 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8064 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8065 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8067 // At this point there are at most two inputs to the low and high halves from
8068 // each half. That means the inputs can always be grouped into dwords and
8069 // those dwords can then be moved to the correct half with a dword shuffle.
8070 // We use at most one low and one high word shuffle to collect these paired
8071 // inputs into dwords, and finally a dword shuffle to place them.
8072 int PSHUFLMask[4] = {-1, -1, -1, -1};
8073 int PSHUFHMask[4] = {-1, -1, -1, -1};
8074 int PSHUFDMask[4] = {-1, -1, -1, -1};
8076 // First fix the masks for all the inputs that are staying in their
8077 // original halves. This will then dictate the targets of the cross-half
8079 auto fixInPlaceInputs =
8080 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8081 MutableArrayRef<int> SourceHalfMask,
8082 MutableArrayRef<int> HalfMask, int HalfOffset) {
8083 if (InPlaceInputs.empty())
8085 if (InPlaceInputs.size() == 1) {
8086 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8087 InPlaceInputs[0] - HalfOffset;
8088 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8091 if (IncomingInputs.empty()) {
8092 // Just fix all of the in place inputs.
8093 for (int Input : InPlaceInputs) {
8094 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8095 PSHUFDMask[Input / 2] = Input / 2;
8100 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8101 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8102 InPlaceInputs[0] - HalfOffset;
8103 // Put the second input next to the first so that they are packed into
8104 // a dword. We find the adjacent index by toggling the low bit.
8105 int AdjIndex = InPlaceInputs[0] ^ 1;
8106 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8107 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8108 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8110 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8111 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8113 // Now gather the cross-half inputs and place them into a free dword of
8114 // their target half.
8115 // FIXME: This operation could almost certainly be simplified dramatically to
8116 // look more like the 3-1 fixing operation.
8117 auto moveInputsToRightHalf = [&PSHUFDMask](
8118 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8119 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8120 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8122 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8123 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8125 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8127 int LowWord = Word & ~1;
8128 int HighWord = Word | 1;
8129 return isWordClobbered(SourceHalfMask, LowWord) ||
8130 isWordClobbered(SourceHalfMask, HighWord);
8133 if (IncomingInputs.empty())
8136 if (ExistingInputs.empty()) {
8137 // Map any dwords with inputs from them into the right half.
8138 for (int Input : IncomingInputs) {
8139 // If the source half mask maps over the inputs, turn those into
8140 // swaps and use the swapped lane.
8141 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8142 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8143 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8144 Input - SourceOffset;
8145 // We have to swap the uses in our half mask in one sweep.
8146 for (int &M : HalfMask)
8147 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8149 else if (M == Input)
8150 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8152 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8153 Input - SourceOffset &&
8154 "Previous placement doesn't match!");
8156 // Note that this correctly re-maps both when we do a swap and when
8157 // we observe the other side of the swap above. We rely on that to
8158 // avoid swapping the members of the input list directly.
8159 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8162 // Map the input's dword into the correct half.
8163 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8164 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8166 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8168 "Previous placement doesn't match!");
8171 // And just directly shift any other-half mask elements to be same-half
8172 // as we will have mirrored the dword containing the element into the
8173 // same position within that half.
8174 for (int &M : HalfMask)
8175 if (M >= SourceOffset && M < SourceOffset + 4) {
8176 M = M - SourceOffset + DestOffset;
8177 assert(M >= 0 && "This should never wrap below zero!");
8182 // Ensure we have the input in a viable dword of its current half. This
8183 // is particularly tricky because the original position may be clobbered
8184 // by inputs being moved and *staying* in that half.
8185 if (IncomingInputs.size() == 1) {
8186 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8187 int InputFixed = std::find(std::begin(SourceHalfMask),
8188 std::end(SourceHalfMask), -1) -
8189 std::begin(SourceHalfMask) + SourceOffset;
8190 SourceHalfMask[InputFixed - SourceOffset] =
8191 IncomingInputs[0] - SourceOffset;
8192 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8194 IncomingInputs[0] = InputFixed;
8196 } else if (IncomingInputs.size() == 2) {
8197 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8198 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8199 // We have two non-adjacent or clobbered inputs we need to extract from
8200 // the source half. To do this, we need to map them into some adjacent
8201 // dword slot in the source mask.
8202 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8203 IncomingInputs[1] - SourceOffset};
8205 // If there is a free slot in the source half mask adjacent to one of
8206 // the inputs, place the other input in it. We use (Index XOR 1) to
8207 // compute an adjacent index.
8208 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8209 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8210 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8211 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8212 InputsFixed[1] = InputsFixed[0] ^ 1;
8213 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8214 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8215 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8216 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8217 InputsFixed[0] = InputsFixed[1] ^ 1;
8218 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8219 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8220 // The two inputs are in the same DWord but it is clobbered and the
8221 // adjacent DWord isn't used at all. Move both inputs to the free
8223 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8224 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8225 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8226 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8228 // The only way we hit this point is if there is no clobbering
8229 // (because there are no off-half inputs to this half) and there is no
8230 // free slot adjacent to one of the inputs. In this case, we have to
8231 // swap an input with a non-input.
8232 for (int i = 0; i < 4; ++i)
8233 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8234 "We can't handle any clobbers here!");
8235 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8236 "Cannot have adjacent inputs here!");
8238 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8239 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8241 // We also have to update the final source mask in this case because
8242 // it may need to undo the above swap.
8243 for (int &M : FinalSourceHalfMask)
8244 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8245 M = InputsFixed[1] + SourceOffset;
8246 else if (M == InputsFixed[1] + SourceOffset)
8247 M = (InputsFixed[0] ^ 1) + SourceOffset;
8249 InputsFixed[1] = InputsFixed[0] ^ 1;
8252 // Point everything at the fixed inputs.
8253 for (int &M : HalfMask)
8254 if (M == IncomingInputs[0])
8255 M = InputsFixed[0] + SourceOffset;
8256 else if (M == IncomingInputs[1])
8257 M = InputsFixed[1] + SourceOffset;
8259 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8260 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8263 llvm_unreachable("Unhandled input size!");
8266 // Now hoist the DWord down to the right half.
8267 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8268 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8269 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8270 for (int &M : HalfMask)
8271 for (int Input : IncomingInputs)
8273 M = FreeDWord * 2 + Input % 2;
8275 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8276 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8277 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8278 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8280 // Now enact all the shuffles we've computed to move the inputs into their
8282 if (!isNoopShuffleMask(PSHUFLMask))
8283 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8284 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8285 if (!isNoopShuffleMask(PSHUFHMask))
8286 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8287 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8288 if (!isNoopShuffleMask(PSHUFDMask))
8289 V = DAG.getNode(ISD::BITCAST, DL, VT,
8290 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT,
8291 DAG.getNode(ISD::BITCAST, DL, PSHUFDVT, V),
8292 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL,
8295 // At this point, each half should contain all its inputs, and we can then
8296 // just shuffle them into their final position.
8297 assert(std::count_if(LoMask.begin(), LoMask.end(),
8298 [](int M) { return M >= 4; }) == 0 &&
8299 "Failed to lift all the high half inputs to the low mask!");
8300 assert(std::count_if(HiMask.begin(), HiMask.end(),
8301 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8302 "Failed to lift all the low half inputs to the high mask!");
8304 // Do a half shuffle for the low mask.
8305 if (!isNoopShuffleMask(LoMask))
8306 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8307 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8309 // Do a half shuffle with the high mask after shifting its values down.
8310 for (int &M : HiMask)
8313 if (!isNoopShuffleMask(HiMask))
8314 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8315 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8320 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8321 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8322 SDValue V2, ArrayRef<int> Mask,
8323 SelectionDAG &DAG, bool &V1InUse,
8325 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8331 int Size = Mask.size();
8332 int Scale = 16 / Size;
8333 for (int i = 0; i < 16; ++i) {
8334 if (Mask[i / Scale] == -1) {
8335 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8337 const int ZeroMask = 0x80;
8338 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8340 int V2Idx = Mask[i / Scale] < Size
8342 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8343 if (Zeroable[i / Scale])
8344 V1Idx = V2Idx = ZeroMask;
8345 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8346 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8347 V1InUse |= (ZeroMask != V1Idx);
8348 V2InUse |= (ZeroMask != V2Idx);
8353 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8354 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V1),
8355 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8357 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8358 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, V2),
8359 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8361 // If we need shuffled inputs from both, blend the two.
8363 if (V1InUse && V2InUse)
8364 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8366 V = V1InUse ? V1 : V2;
8368 // Cast the result back to the correct type.
8369 return DAG.getNode(ISD::BITCAST, DL, VT, V);
8372 /// \brief Generic lowering of 8-lane i16 shuffles.
8374 /// This handles both single-input shuffles and combined shuffle/blends with
8375 /// two inputs. The single input shuffles are immediately delegated to
8376 /// a dedicated lowering routine.
8378 /// The blends are lowered in one of three fundamental ways. If there are few
8379 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8380 /// of the input is significantly cheaper when lowered as an interleaving of
8381 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8382 /// halves of the inputs separately (making them have relatively few inputs)
8383 /// and then concatenate them.
8384 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8385 const X86Subtarget *Subtarget,
8386 SelectionDAG &DAG) {
8388 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8389 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8390 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8391 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8392 ArrayRef<int> OrigMask = SVOp->getMask();
8393 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8394 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8395 MutableArrayRef<int> Mask(MaskStorage);
8397 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8399 // Whenever we can lower this as a zext, that instruction is strictly faster
8400 // than any alternative.
8401 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8402 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8405 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8407 auto isV2 = [](int M) { return M >= 8; };
8409 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8411 if (NumV2Inputs == 0) {
8412 // Check for being able to broadcast a single element.
8413 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8414 Mask, Subtarget, DAG))
8417 // Try to use shift instructions.
8419 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8422 // Use dedicated unpack instructions for masks that match their pattern.
8423 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8424 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8425 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8426 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8428 // Try to use byte rotation instructions.
8429 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8430 Mask, Subtarget, DAG))
8433 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8437 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8438 "All single-input shuffles should be canonicalized to be V1-input "
8441 // Try to use shift instructions.
8443 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8446 // There are special ways we can lower some single-element blends.
8447 if (NumV2Inputs == 1)
8448 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8449 Mask, Subtarget, DAG))
8452 // We have different paths for blend lowering, but they all must use the
8453 // *exact* same predicate.
8454 bool IsBlendSupported = Subtarget->hasSSE41();
8455 if (IsBlendSupported)
8456 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8460 if (SDValue Masked =
8461 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8464 // Use dedicated unpack instructions for masks that match their pattern.
8465 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8466 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8467 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8468 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8470 // Try to use byte rotation instructions.
8471 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8472 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8475 if (SDValue BitBlend =
8476 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8479 if (SDValue Unpack =
8480 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8483 // If we can't directly blend but can use PSHUFB, that will be better as it
8484 // can both shuffle and set up the inefficient blend.
8485 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8486 bool V1InUse, V2InUse;
8487 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8491 // We can always bit-blend if we have to so the fallback strategy is to
8492 // decompose into single-input permutes and blends.
8493 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8497 /// \brief Check whether a compaction lowering can be done by dropping even
8498 /// elements and compute how many times even elements must be dropped.
8500 /// This handles shuffles which take every Nth element where N is a power of
8501 /// two. Example shuffle masks:
8503 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8504 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8505 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8506 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8507 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8508 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8510 /// Any of these lanes can of course be undef.
8512 /// This routine only supports N <= 3.
8513 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8516 /// \returns N above, or the number of times even elements must be dropped if
8517 /// there is such a number. Otherwise returns zero.
8518 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8519 // Figure out whether we're looping over two inputs or just one.
8520 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8522 // The modulus for the shuffle vector entries is based on whether this is
8523 // a single input or not.
8524 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8525 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8526 "We should only be called with masks with a power-of-2 size!");
8528 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8530 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8531 // and 2^3 simultaneously. This is because we may have ambiguity with
8532 // partially undef inputs.
8533 bool ViableForN[3] = {true, true, true};
8535 for (int i = 0, e = Mask.size(); i < e; ++i) {
8536 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8541 bool IsAnyViable = false;
8542 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8543 if (ViableForN[j]) {
8546 // The shuffle mask must be equal to (i * 2^N) % M.
8547 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8550 ViableForN[j] = false;
8552 // Early exit if we exhaust the possible powers of two.
8557 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8561 // Return 0 as there is no viable power of two.
8565 /// \brief Generic lowering of v16i8 shuffles.
8567 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8568 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8569 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8570 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8572 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8573 const X86Subtarget *Subtarget,
8574 SelectionDAG &DAG) {
8576 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8577 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8578 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8579 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8580 ArrayRef<int> Mask = SVOp->getMask();
8581 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8583 // Try to use shift instructions.
8585 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8588 // Try to use byte rotation instructions.
8589 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8590 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8593 // Try to use a zext lowering.
8594 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8595 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8599 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8601 // For single-input shuffles, there are some nicer lowering tricks we can use.
8602 if (NumV2Elements == 0) {
8603 // Check for being able to broadcast a single element.
8604 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8605 Mask, Subtarget, DAG))
8608 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8609 // Notably, this handles splat and partial-splat shuffles more efficiently.
8610 // However, it only makes sense if the pre-duplication shuffle simplifies
8611 // things significantly. Currently, this means we need to be able to
8612 // express the pre-duplication shuffle as an i16 shuffle.
8614 // FIXME: We should check for other patterns which can be widened into an
8615 // i16 shuffle as well.
8616 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8617 for (int i = 0; i < 16; i += 2)
8618 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8623 auto tryToWidenViaDuplication = [&]() -> SDValue {
8624 if (!canWidenViaDuplication(Mask))
8626 SmallVector<int, 4> LoInputs;
8627 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8628 [](int M) { return M >= 0 && M < 8; });
8629 std::sort(LoInputs.begin(), LoInputs.end());
8630 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8632 SmallVector<int, 4> HiInputs;
8633 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8634 [](int M) { return M >= 8; });
8635 std::sort(HiInputs.begin(), HiInputs.end());
8636 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8639 bool TargetLo = LoInputs.size() >= HiInputs.size();
8640 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8641 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8643 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8644 SmallDenseMap<int, int, 8> LaneMap;
8645 for (int I : InPlaceInputs) {
8646 PreDupI16Shuffle[I/2] = I/2;
8649 int j = TargetLo ? 0 : 4, je = j + 4;
8650 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8651 // Check if j is already a shuffle of this input. This happens when
8652 // there are two adjacent bytes after we move the low one.
8653 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8654 // If we haven't yet mapped the input, search for a slot into which
8656 while (j < je && PreDupI16Shuffle[j] != -1)
8660 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8663 // Map this input with the i16 shuffle.
8664 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8667 // Update the lane map based on the mapping we ended up with.
8668 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8671 ISD::BITCAST, DL, MVT::v16i8,
8672 DAG.getVectorShuffle(MVT::v8i16, DL,
8673 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8674 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8676 // Unpack the bytes to form the i16s that will be shuffled into place.
8677 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8678 MVT::v16i8, V1, V1);
8680 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8681 for (int i = 0; i < 16; ++i)
8682 if (Mask[i] != -1) {
8683 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8684 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8685 if (PostDupI16Shuffle[i / 2] == -1)
8686 PostDupI16Shuffle[i / 2] = MappedMask;
8688 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8689 "Conflicting entrties in the original shuffle!");
8692 ISD::BITCAST, DL, MVT::v16i8,
8693 DAG.getVectorShuffle(MVT::v8i16, DL,
8694 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8695 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8697 if (SDValue V = tryToWidenViaDuplication())
8701 // Use dedicated unpack instructions for masks that match their pattern.
8702 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8703 0, 16, 1, 17, 2, 18, 3, 19,
8705 4, 20, 5, 21, 6, 22, 7, 23}))
8706 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8707 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8708 8, 24, 9, 25, 10, 26, 11, 27,
8710 12, 28, 13, 29, 14, 30, 15, 31}))
8711 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8713 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8714 // with PSHUFB. It is important to do this before we attempt to generate any
8715 // blends but after all of the single-input lowerings. If the single input
8716 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8717 // want to preserve that and we can DAG combine any longer sequences into
8718 // a PSHUFB in the end. But once we start blending from multiple inputs,
8719 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8720 // and there are *very* few patterns that would actually be faster than the
8721 // PSHUFB approach because of its ability to zero lanes.
8723 // FIXME: The only exceptions to the above are blends which are exact
8724 // interleavings with direct instructions supporting them. We currently don't
8725 // handle those well here.
8726 if (Subtarget->hasSSSE3()) {
8727 bool V1InUse = false;
8728 bool V2InUse = false;
8730 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8731 DAG, V1InUse, V2InUse);
8733 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8734 // do so. This avoids using them to handle blends-with-zero which is
8735 // important as a single pshufb is significantly faster for that.
8736 if (V1InUse && V2InUse) {
8737 if (Subtarget->hasSSE41())
8738 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8739 Mask, Subtarget, DAG))
8742 // We can use an unpack to do the blending rather than an or in some
8743 // cases. Even though the or may be (very minorly) more efficient, we
8744 // preference this lowering because there are common cases where part of
8745 // the complexity of the shuffles goes away when we do the final blend as
8747 // FIXME: It might be worth trying to detect if the unpack-feeding
8748 // shuffles will both be pshufb, in which case we shouldn't bother with
8750 if (SDValue Unpack =
8751 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8758 // There are special ways we can lower some single-element blends.
8759 if (NumV2Elements == 1)
8760 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8761 Mask, Subtarget, DAG))
8764 if (SDValue BitBlend =
8765 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8768 // Check whether a compaction lowering can be done. This handles shuffles
8769 // which take every Nth element for some even N. See the helper function for
8772 // We special case these as they can be particularly efficiently handled with
8773 // the PACKUSB instruction on x86 and they show up in common patterns of
8774 // rearranging bytes to truncate wide elements.
8775 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8776 // NumEvenDrops is the power of two stride of the elements. Another way of
8777 // thinking about it is that we need to drop the even elements this many
8778 // times to get the original input.
8779 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8781 // First we need to zero all the dropped bytes.
8782 assert(NumEvenDrops <= 3 &&
8783 "No support for dropping even elements more than 3 times.");
8784 // We use the mask type to pick which bytes are preserved based on how many
8785 // elements are dropped.
8786 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8787 SDValue ByteClearMask =
8788 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8789 DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8790 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8792 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8794 // Now pack things back together.
8795 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8796 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8797 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8798 for (int i = 1; i < NumEvenDrops; ++i) {
8799 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8800 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8806 // Handle multi-input cases by blending single-input shuffles.
8807 if (NumV2Elements > 0)
8808 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8811 // The fallback path for single-input shuffles widens this into two v8i16
8812 // vectors with unpacks, shuffles those, and then pulls them back together
8816 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8817 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8818 for (int i = 0; i < 16; ++i)
8820 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8822 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8824 SDValue VLoHalf, VHiHalf;
8825 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8826 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8828 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8829 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8830 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8831 [](int M) { return M >= 0 && M % 2 == 1; })) {
8832 // Use a mask to drop the high bytes.
8833 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8834 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8835 DAG.getConstant(0x00FF, DL, MVT::v8i16));
8837 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8838 VHiHalf = DAG.getUNDEF(MVT::v8i16);
8840 // Squash the masks to point directly into VLoHalf.
8841 for (int &M : LoBlendMask)
8844 for (int &M : HiBlendMask)
8848 // Otherwise just unpack the low half of V into VLoHalf and the high half into
8849 // VHiHalf so that we can blend them as i16s.
8850 VLoHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8851 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8852 VHiHalf = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8853 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8856 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8857 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8859 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8862 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8864 /// This routine breaks down the specific type of 128-bit shuffle and
8865 /// dispatches to the lowering routines accordingly.
8866 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8867 MVT VT, const X86Subtarget *Subtarget,
8868 SelectionDAG &DAG) {
8869 switch (VT.SimpleTy) {
8871 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8873 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8875 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8877 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8879 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8881 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8884 llvm_unreachable("Unimplemented!");
8888 /// \brief Helper function to test whether a shuffle mask could be
8889 /// simplified by widening the elements being shuffled.
8891 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
8892 /// leaves it in an unspecified state.
8894 /// NOTE: This must handle normal vector shuffle masks and *target* vector
8895 /// shuffle masks. The latter have the special property of a '-2' representing
8896 /// a zero-ed lane of a vector.
8897 static bool canWidenShuffleElements(ArrayRef<int> Mask,
8898 SmallVectorImpl<int> &WidenedMask) {
8899 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
8900 // If both elements are undef, its trivial.
8901 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
8902 WidenedMask.push_back(SM_SentinelUndef);
8906 // Check for an undef mask and a mask value properly aligned to fit with
8907 // a pair of values. If we find such a case, use the non-undef mask's value.
8908 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
8909 WidenedMask.push_back(Mask[i + 1] / 2);
8912 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
8913 WidenedMask.push_back(Mask[i] / 2);
8917 // When zeroing, we need to spread the zeroing across both lanes to widen.
8918 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
8919 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
8920 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
8921 WidenedMask.push_back(SM_SentinelZero);
8927 // Finally check if the two mask values are adjacent and aligned with
8929 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
8930 WidenedMask.push_back(Mask[i] / 2);
8934 // Otherwise we can't safely widen the elements used in this shuffle.
8937 assert(WidenedMask.size() == Mask.size() / 2 &&
8938 "Incorrect size of mask after widening the elements!");
8943 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
8945 /// This routine just extracts two subvectors, shuffles them independently, and
8946 /// then concatenates them back together. This should work effectively with all
8947 /// AVX vector shuffle types.
8948 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
8949 SDValue V2, ArrayRef<int> Mask,
8950 SelectionDAG &DAG) {
8951 assert(VT.getSizeInBits() >= 256 &&
8952 "Only for 256-bit or wider vector shuffles!");
8953 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8954 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8956 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
8957 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
8959 int NumElements = VT.getVectorNumElements();
8960 int SplitNumElements = NumElements / 2;
8961 MVT ScalarVT = VT.getScalarType();
8962 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8964 // Rather than splitting build-vectors, just build two narrower build
8965 // vectors. This helps shuffling with splats and zeros.
8966 auto SplitVector = [&](SDValue V) {
8967 while (V.getOpcode() == ISD::BITCAST)
8968 V = V->getOperand(0);
8970 MVT OrigVT = V.getSimpleValueType();
8971 int OrigNumElements = OrigVT.getVectorNumElements();
8972 int OrigSplitNumElements = OrigNumElements / 2;
8973 MVT OrigScalarVT = OrigVT.getScalarType();
8974 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
8978 auto *BV = dyn_cast<BuildVectorSDNode>(V);
8980 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8981 DAG.getIntPtrConstant(0, DL));
8982 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
8983 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
8986 SmallVector<SDValue, 16> LoOps, HiOps;
8987 for (int i = 0; i < OrigSplitNumElements; ++i) {
8988 LoOps.push_back(BV->getOperand(i));
8989 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
8991 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
8992 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
8994 return std::make_pair(DAG.getNode(ISD::BITCAST, DL, SplitVT, LoV),
8995 DAG.getNode(ISD::BITCAST, DL, SplitVT, HiV));
8998 SDValue LoV1, HiV1, LoV2, HiV2;
8999 std::tie(LoV1, HiV1) = SplitVector(V1);
9000 std::tie(LoV2, HiV2) = SplitVector(V2);
9002 // Now create two 4-way blends of these half-width vectors.
9003 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9004 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9005 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9006 for (int i = 0; i < SplitNumElements; ++i) {
9007 int M = HalfMask[i];
9008 if (M >= NumElements) {
9009 if (M >= NumElements + SplitNumElements)
9013 V2BlendMask.push_back(M - NumElements);
9014 V1BlendMask.push_back(-1);
9015 BlendMask.push_back(SplitNumElements + i);
9016 } else if (M >= 0) {
9017 if (M >= SplitNumElements)
9021 V2BlendMask.push_back(-1);
9022 V1BlendMask.push_back(M);
9023 BlendMask.push_back(i);
9025 V2BlendMask.push_back(-1);
9026 V1BlendMask.push_back(-1);
9027 BlendMask.push_back(-1);
9031 // Because the lowering happens after all combining takes place, we need to
9032 // manually combine these blend masks as much as possible so that we create
9033 // a minimal number of high-level vector shuffle nodes.
9035 // First try just blending the halves of V1 or V2.
9036 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9037 return DAG.getUNDEF(SplitVT);
9038 if (!UseLoV2 && !UseHiV2)
9039 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9040 if (!UseLoV1 && !UseHiV1)
9041 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9043 SDValue V1Blend, V2Blend;
9044 if (UseLoV1 && UseHiV1) {
9046 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9048 // We only use half of V1 so map the usage down into the final blend mask.
9049 V1Blend = UseLoV1 ? LoV1 : HiV1;
9050 for (int i = 0; i < SplitNumElements; ++i)
9051 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9052 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9054 if (UseLoV2 && UseHiV2) {
9056 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9058 // We only use half of V2 so map the usage down into the final blend mask.
9059 V2Blend = UseLoV2 ? LoV2 : HiV2;
9060 for (int i = 0; i < SplitNumElements; ++i)
9061 if (BlendMask[i] >= SplitNumElements)
9062 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9064 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9066 SDValue Lo = HalfBlend(LoMask);
9067 SDValue Hi = HalfBlend(HiMask);
9068 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9071 /// \brief Either split a vector in halves or decompose the shuffles and the
9074 /// This is provided as a good fallback for many lowerings of non-single-input
9075 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9076 /// between splitting the shuffle into 128-bit components and stitching those
9077 /// back together vs. extracting the single-input shuffles and blending those
9079 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9080 SDValue V2, ArrayRef<int> Mask,
9081 SelectionDAG &DAG) {
9082 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9083 "lower single-input shuffles as it "
9084 "could then recurse on itself.");
9085 int Size = Mask.size();
9087 // If this can be modeled as a broadcast of two elements followed by a blend,
9088 // prefer that lowering. This is especially important because broadcasts can
9089 // often fold with memory operands.
9090 auto DoBothBroadcast = [&] {
9091 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9094 if (V2BroadcastIdx == -1)
9095 V2BroadcastIdx = M - Size;
9096 else if (M - Size != V2BroadcastIdx)
9098 } else if (M >= 0) {
9099 if (V1BroadcastIdx == -1)
9101 else if (M != V1BroadcastIdx)
9106 if (DoBothBroadcast())
9107 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9110 // If the inputs all stem from a single 128-bit lane of each input, then we
9111 // split them rather than blending because the split will decompose to
9112 // unusually few instructions.
9113 int LaneCount = VT.getSizeInBits() / 128;
9114 int LaneSize = Size / LaneCount;
9115 SmallBitVector LaneInputs[2];
9116 LaneInputs[0].resize(LaneCount, false);
9117 LaneInputs[1].resize(LaneCount, false);
9118 for (int i = 0; i < Size; ++i)
9120 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9121 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9122 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9124 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9125 // that the decomposed single-input shuffles don't end up here.
9126 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9129 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9130 /// a permutation and blend of those lanes.
9132 /// This essentially blends the out-of-lane inputs to each lane into the lane
9133 /// from a permuted copy of the vector. This lowering strategy results in four
9134 /// instructions in the worst case for a single-input cross lane shuffle which
9135 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9136 /// of. Special cases for each particular shuffle pattern should be handled
9137 /// prior to trying this lowering.
9138 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9139 SDValue V1, SDValue V2,
9141 SelectionDAG &DAG) {
9142 // FIXME: This should probably be generalized for 512-bit vectors as well.
9143 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9144 int LaneSize = Mask.size() / 2;
9146 // If there are only inputs from one 128-bit lane, splitting will in fact be
9147 // less expensive. The flags track whether the given lane contains an element
9148 // that crosses to another lane.
9149 bool LaneCrossing[2] = {false, false};
9150 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9151 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9152 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9153 if (!LaneCrossing[0] || !LaneCrossing[1])
9154 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9156 if (isSingleInputShuffleMask(Mask)) {
9157 SmallVector<int, 32> FlippedBlendMask;
9158 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9159 FlippedBlendMask.push_back(
9160 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9162 : Mask[i] % LaneSize +
9163 (i / LaneSize) * LaneSize + Size));
9165 // Flip the vector, and blend the results which should now be in-lane. The
9166 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9167 // 5 for the high source. The value 3 selects the high half of source 2 and
9168 // the value 2 selects the low half of source 2. We only use source 2 to
9169 // allow folding it into a memory operand.
9170 unsigned PERMMask = 3 | 2 << 4;
9171 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9172 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9173 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9176 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9177 // will be handled by the above logic and a blend of the results, much like
9178 // other patterns in AVX.
9179 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9182 /// \brief Handle lowering 2-lane 128-bit shuffles.
9183 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9184 SDValue V2, ArrayRef<int> Mask,
9185 const X86Subtarget *Subtarget,
9186 SelectionDAG &DAG) {
9187 // TODO: If minimizing size and one of the inputs is a zero vector and the
9188 // the zero vector has only one use, we could use a VPERM2X128 to save the
9189 // instruction bytes needed to explicitly generate the zero vector.
9191 // Blends are faster and handle all the non-lane-crossing cases.
9192 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9196 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9197 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9199 // If either input operand is a zero vector, use VPERM2X128 because its mask
9200 // allows us to replace the zero input with an implicit zero.
9201 if (!IsV1Zero && !IsV2Zero) {
9202 // Check for patterns which can be matched with a single insert of a 128-bit
9204 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9205 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9206 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9207 VT.getVectorNumElements() / 2);
9208 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9209 DAG.getIntPtrConstant(0, DL));
9210 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9211 OnlyUsesV1 ? V1 : V2,
9212 DAG.getIntPtrConstant(0, DL));
9213 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9217 // Otherwise form a 128-bit permutation. After accounting for undefs,
9218 // convert the 64-bit shuffle mask selection values into 128-bit
9219 // selection bits by dividing the indexes by 2 and shifting into positions
9220 // defined by a vperm2*128 instruction's immediate control byte.
9222 // The immediate permute control byte looks like this:
9223 // [1:0] - select 128 bits from sources for low half of destination
9225 // [3] - zero low half of destination
9226 // [5:4] - select 128 bits from sources for high half of destination
9228 // [7] - zero high half of destination
9230 int MaskLO = Mask[0];
9231 if (MaskLO == SM_SentinelUndef)
9232 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9234 int MaskHI = Mask[2];
9235 if (MaskHI == SM_SentinelUndef)
9236 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9238 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9240 // If either input is a zero vector, replace it with an undef input.
9241 // Shuffle mask values < 4 are selecting elements of V1.
9242 // Shuffle mask values >= 4 are selecting elements of V2.
9243 // Adjust each half of the permute mask by clearing the half that was
9244 // selecting the zero vector and setting the zero mask bit.
9246 V1 = DAG.getUNDEF(VT);
9248 PermMask = (PermMask & 0xf0) | 0x08;
9250 PermMask = (PermMask & 0x0f) | 0x80;
9253 V2 = DAG.getUNDEF(VT);
9255 PermMask = (PermMask & 0xf0) | 0x08;
9257 PermMask = (PermMask & 0x0f) | 0x80;
9260 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9261 DAG.getConstant(PermMask, DL, MVT::i8));
9264 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9265 /// shuffling each lane.
9267 /// This will only succeed when the result of fixing the 128-bit lanes results
9268 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9269 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9270 /// the lane crosses early and then use simpler shuffles within each lane.
9272 /// FIXME: It might be worthwhile at some point to support this without
9273 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9274 /// in x86 only floating point has interesting non-repeating shuffles, and even
9275 /// those are still *marginally* more expensive.
9276 static SDValue lowerVectorShuffleByMerging128BitLanes(
9277 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9278 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9279 assert(!isSingleInputShuffleMask(Mask) &&
9280 "This is only useful with multiple inputs.");
9282 int Size = Mask.size();
9283 int LaneSize = 128 / VT.getScalarSizeInBits();
9284 int NumLanes = Size / LaneSize;
9285 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9287 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9288 // check whether the in-128-bit lane shuffles share a repeating pattern.
9289 SmallVector<int, 4> Lanes;
9290 Lanes.resize(NumLanes, -1);
9291 SmallVector<int, 4> InLaneMask;
9292 InLaneMask.resize(LaneSize, -1);
9293 for (int i = 0; i < Size; ++i) {
9297 int j = i / LaneSize;
9300 // First entry we've seen for this lane.
9301 Lanes[j] = Mask[i] / LaneSize;
9302 } else if (Lanes[j] != Mask[i] / LaneSize) {
9303 // This doesn't match the lane selected previously!
9307 // Check that within each lane we have a consistent shuffle mask.
9308 int k = i % LaneSize;
9309 if (InLaneMask[k] < 0) {
9310 InLaneMask[k] = Mask[i] % LaneSize;
9311 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9312 // This doesn't fit a repeating in-lane mask.
9317 // First shuffle the lanes into place.
9318 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9319 VT.getSizeInBits() / 64);
9320 SmallVector<int, 8> LaneMask;
9321 LaneMask.resize(NumLanes * 2, -1);
9322 for (int i = 0; i < NumLanes; ++i)
9323 if (Lanes[i] >= 0) {
9324 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9325 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9328 V1 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V1);
9329 V2 = DAG.getNode(ISD::BITCAST, DL, LaneVT, V2);
9330 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9332 // Cast it back to the type we actually want.
9333 LaneShuffle = DAG.getNode(ISD::BITCAST, DL, VT, LaneShuffle);
9335 // Now do a simple shuffle that isn't lane crossing.
9336 SmallVector<int, 8> NewMask;
9337 NewMask.resize(Size, -1);
9338 for (int i = 0; i < Size; ++i)
9340 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9341 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9342 "Must not introduce lane crosses at this point!");
9344 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9347 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9350 /// This returns true if the elements from a particular input are already in the
9351 /// slot required by the given mask and require no permutation.
9352 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9353 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9354 int Size = Mask.size();
9355 for (int i = 0; i < Size; ++i)
9356 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9362 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9364 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9365 /// isn't available.
9366 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9367 const X86Subtarget *Subtarget,
9368 SelectionDAG &DAG) {
9370 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9371 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9372 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9373 ArrayRef<int> Mask = SVOp->getMask();
9374 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9376 SmallVector<int, 4> WidenedMask;
9377 if (canWidenShuffleElements(Mask, WidenedMask))
9378 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9381 if (isSingleInputShuffleMask(Mask)) {
9382 // Check for being able to broadcast a single element.
9383 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9384 Mask, Subtarget, DAG))
9387 // Use low duplicate instructions for masks that match their pattern.
9388 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9389 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9391 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9392 // Non-half-crossing single input shuffles can be lowerid with an
9393 // interleaved permutation.
9394 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9395 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9396 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9397 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9400 // With AVX2 we have direct support for this permutation.
9401 if (Subtarget->hasAVX2())
9402 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9403 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9405 // Otherwise, fall back.
9406 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9410 // X86 has dedicated unpack instructions that can handle specific blend
9411 // operations: UNPCKH and UNPCKL.
9412 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9413 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9414 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9415 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9416 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9417 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9418 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9419 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9421 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9425 // Check if the blend happens to exactly fit that of SHUFPD.
9426 if ((Mask[0] == -1 || Mask[0] < 2) &&
9427 (Mask[1] == -1 || (Mask[1] >= 4 && Mask[1] < 6)) &&
9428 (Mask[2] == -1 || (Mask[2] >= 2 && Mask[2] < 4)) &&
9429 (Mask[3] == -1 || Mask[3] >= 6)) {
9430 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9431 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9432 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9433 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9435 if ((Mask[0] == -1 || (Mask[0] >= 4 && Mask[0] < 6)) &&
9436 (Mask[1] == -1 || Mask[1] < 2) &&
9437 (Mask[2] == -1 || Mask[2] >= 6) &&
9438 (Mask[3] == -1 || (Mask[3] >= 2 && Mask[3] < 4))) {
9439 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9440 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9441 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9442 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
9445 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9446 // shuffle. However, if we have AVX2 and either inputs are already in place,
9447 // we will be able to shuffle even across lanes the other input in a single
9448 // instruction so skip this pattern.
9449 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9450 isShuffleMaskInputInPlace(1, Mask))))
9451 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9452 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9455 // If we have AVX2 then we always want to lower with a blend because an v4 we
9456 // can fully permute the elements.
9457 if (Subtarget->hasAVX2())
9458 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9461 // Otherwise fall back on generic lowering.
9462 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9465 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9467 /// This routine is only called when we have AVX2 and thus a reasonable
9468 /// instruction set for v4i64 shuffling..
9469 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9470 const X86Subtarget *Subtarget,
9471 SelectionDAG &DAG) {
9473 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9474 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9475 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9476 ArrayRef<int> Mask = SVOp->getMask();
9477 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9478 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9480 SmallVector<int, 4> WidenedMask;
9481 if (canWidenShuffleElements(Mask, WidenedMask))
9482 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9485 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9489 // Check for being able to broadcast a single element.
9490 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9491 Mask, Subtarget, DAG))
9494 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9495 // use lower latency instructions that will operate on both 128-bit lanes.
9496 SmallVector<int, 2> RepeatedMask;
9497 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9498 if (isSingleInputShuffleMask(Mask)) {
9499 int PSHUFDMask[] = {-1, -1, -1, -1};
9500 for (int i = 0; i < 2; ++i)
9501 if (RepeatedMask[i] >= 0) {
9502 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9503 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9506 ISD::BITCAST, DL, MVT::v4i64,
9507 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9508 DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9509 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9513 // AVX2 provides a direct instruction for permuting a single input across
9515 if (isSingleInputShuffleMask(Mask))
9516 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9517 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9519 // Try to use shift instructions.
9521 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9524 // Use dedicated unpack instructions for masks that match their pattern.
9525 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9526 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9527 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9528 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9529 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9530 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9531 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9532 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9534 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9535 // shuffle. However, if we have AVX2 and either inputs are already in place,
9536 // we will be able to shuffle even across lanes the other input in a single
9537 // instruction so skip this pattern.
9538 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9539 isShuffleMaskInputInPlace(1, Mask))))
9540 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9541 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9544 // Otherwise fall back on generic blend lowering.
9545 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9549 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9551 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9552 /// isn't available.
9553 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9554 const X86Subtarget *Subtarget,
9555 SelectionDAG &DAG) {
9557 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9558 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9559 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9560 ArrayRef<int> Mask = SVOp->getMask();
9561 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9563 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9567 // Check for being able to broadcast a single element.
9568 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9569 Mask, Subtarget, DAG))
9572 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9573 // options to efficiently lower the shuffle.
9574 SmallVector<int, 4> RepeatedMask;
9575 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9576 assert(RepeatedMask.size() == 4 &&
9577 "Repeated masks must be half the mask width!");
9579 // Use even/odd duplicate instructions for masks that match their pattern.
9580 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9581 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9582 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9583 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9585 if (isSingleInputShuffleMask(Mask))
9586 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9587 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9589 // Use dedicated unpack instructions for masks that match their pattern.
9590 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9591 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9592 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9593 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9594 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9595 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9596 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9597 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9599 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9600 // have already handled any direct blends. We also need to squash the
9601 // repeated mask into a simulated v4f32 mask.
9602 for (int i = 0; i < 4; ++i)
9603 if (RepeatedMask[i] >= 8)
9604 RepeatedMask[i] -= 4;
9605 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9608 // If we have a single input shuffle with different shuffle patterns in the
9609 // two 128-bit lanes use the variable mask to VPERMILPS.
9610 if (isSingleInputShuffleMask(Mask)) {
9611 SDValue VPermMask[8];
9612 for (int i = 0; i < 8; ++i)
9613 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9614 : DAG.getConstant(Mask[i], DL, MVT::i32);
9615 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9617 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9618 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9620 if (Subtarget->hasAVX2())
9621 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
9622 DAG.getNode(ISD::BITCAST, DL, MVT::v8f32,
9623 DAG.getNode(ISD::BUILD_VECTOR, DL,
9624 MVT::v8i32, VPermMask)),
9627 // Otherwise, fall back.
9628 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9632 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9634 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9635 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9638 // If we have AVX2 then we always want to lower with a blend because at v8 we
9639 // can fully permute the elements.
9640 if (Subtarget->hasAVX2())
9641 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9644 // Otherwise fall back on generic lowering.
9645 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9648 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9650 /// This routine is only called when we have AVX2 and thus a reasonable
9651 /// instruction set for v8i32 shuffling..
9652 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9653 const X86Subtarget *Subtarget,
9654 SelectionDAG &DAG) {
9656 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9657 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9658 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9659 ArrayRef<int> Mask = SVOp->getMask();
9660 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9661 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9663 // Whenever we can lower this as a zext, that instruction is strictly faster
9664 // than any alternative. It also allows us to fold memory operands into the
9665 // shuffle in many cases.
9666 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9667 Mask, Subtarget, DAG))
9670 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9674 // Check for being able to broadcast a single element.
9675 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9676 Mask, Subtarget, DAG))
9679 // If the shuffle mask is repeated in each 128-bit lane we can use more
9680 // efficient instructions that mirror the shuffles across the two 128-bit
9682 SmallVector<int, 4> RepeatedMask;
9683 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9684 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9685 if (isSingleInputShuffleMask(Mask))
9686 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9687 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9689 // Use dedicated unpack instructions for masks that match their pattern.
9690 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9691 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9692 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9693 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9694 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9695 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9696 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9697 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9700 // Try to use shift instructions.
9702 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9705 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9706 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9709 // If the shuffle patterns aren't repeated but it is a single input, directly
9710 // generate a cross-lane VPERMD instruction.
9711 if (isSingleInputShuffleMask(Mask)) {
9712 SDValue VPermMask[8];
9713 for (int i = 0; i < 8; ++i)
9714 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9715 : DAG.getConstant(Mask[i], DL, MVT::i32);
9717 X86ISD::VPERMV, DL, MVT::v8i32,
9718 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9721 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9723 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9724 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9727 // Otherwise fall back on generic blend lowering.
9728 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9732 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9734 /// This routine is only called when we have AVX2 and thus a reasonable
9735 /// instruction set for v16i16 shuffling..
9736 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9737 const X86Subtarget *Subtarget,
9738 SelectionDAG &DAG) {
9740 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9741 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9742 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9743 ArrayRef<int> Mask = SVOp->getMask();
9744 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9745 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9747 // Whenever we can lower this as a zext, that instruction is strictly faster
9748 // than any alternative. It also allows us to fold memory operands into the
9749 // shuffle in many cases.
9750 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9751 Mask, Subtarget, DAG))
9754 // Check for being able to broadcast a single element.
9755 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9756 Mask, Subtarget, DAG))
9759 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9763 // Use dedicated unpack instructions for masks that match their pattern.
9764 if (isShuffleEquivalent(V1, V2, Mask,
9765 {// First 128-bit lane:
9766 0, 16, 1, 17, 2, 18, 3, 19,
9767 // Second 128-bit lane:
9768 8, 24, 9, 25, 10, 26, 11, 27}))
9769 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9770 if (isShuffleEquivalent(V1, V2, Mask,
9771 {// First 128-bit lane:
9772 4, 20, 5, 21, 6, 22, 7, 23,
9773 // Second 128-bit lane:
9774 12, 28, 13, 29, 14, 30, 15, 31}))
9775 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9777 // Try to use shift instructions.
9779 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9782 // Try to use byte rotation instructions.
9783 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9784 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9787 if (isSingleInputShuffleMask(Mask)) {
9788 // There are no generalized cross-lane shuffle operations available on i16
9790 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9791 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9794 SmallVector<int, 8> RepeatedMask;
9795 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9796 // As this is a single-input shuffle, the repeated mask should be
9797 // a strictly valid v8i16 mask that we can pass through to the v8i16
9798 // lowering to handle even the v16 case.
9799 return lowerV8I16GeneralSingleInputVectorShuffle(
9800 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9803 SDValue PSHUFBMask[32];
9804 for (int i = 0; i < 16; ++i) {
9805 if (Mask[i] == -1) {
9806 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9810 int M = i < 8 ? Mask[i] : Mask[i] - 8;
9811 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9812 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9813 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9816 ISD::BITCAST, DL, MVT::v16i16,
9818 X86ISD::PSHUFB, DL, MVT::v32i8,
9819 DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, V1),
9820 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask)));
9823 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9825 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9826 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9829 // Otherwise fall back on generic lowering.
9830 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9833 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9835 /// This routine is only called when we have AVX2 and thus a reasonable
9836 /// instruction set for v32i8 shuffling..
9837 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9838 const X86Subtarget *Subtarget,
9839 SelectionDAG &DAG) {
9841 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9842 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9843 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9844 ArrayRef<int> Mask = SVOp->getMask();
9845 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9846 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9848 // Whenever we can lower this as a zext, that instruction is strictly faster
9849 // than any alternative. It also allows us to fold memory operands into the
9850 // shuffle in many cases.
9851 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9852 Mask, Subtarget, DAG))
9855 // Check for being able to broadcast a single element.
9856 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
9857 Mask, Subtarget, DAG))
9860 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
9864 // Use dedicated unpack instructions for masks that match their pattern.
9865 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
9867 if (isShuffleEquivalent(
9869 {// First 128-bit lane:
9870 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
9871 // Second 128-bit lane:
9872 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
9873 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
9874 if (isShuffleEquivalent(
9876 {// First 128-bit lane:
9877 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
9878 // Second 128-bit lane:
9879 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
9880 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
9882 // Try to use shift instructions.
9884 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
9887 // Try to use byte rotation instructions.
9888 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9889 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9892 if (isSingleInputShuffleMask(Mask)) {
9893 // There are no generalized cross-lane shuffle operations available on i8
9895 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
9896 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
9899 SDValue PSHUFBMask[32];
9900 for (int i = 0; i < 32; ++i)
9903 ? DAG.getUNDEF(MVT::i8)
9904 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
9908 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
9909 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
9912 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9914 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9915 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
9918 // Otherwise fall back on generic lowering.
9919 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
9922 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9924 /// This routine either breaks down the specific type of a 256-bit x86 vector
9925 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9926 /// together based on the available instructions.
9927 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9928 MVT VT, const X86Subtarget *Subtarget,
9929 SelectionDAG &DAG) {
9931 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9932 ArrayRef<int> Mask = SVOp->getMask();
9934 // If we have a single input to the zero element, insert that into V1 if we
9935 // can do so cheaply.
9936 int NumElts = VT.getVectorNumElements();
9937 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
9938 return M >= NumElts;
9941 if (NumV2Elements == 1 && Mask[0] >= NumElts)
9942 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9943 DL, VT, V1, V2, Mask, Subtarget, DAG))
9946 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9947 // check for those subtargets here and avoid much of the subtarget querying in
9948 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9949 // ability to manipulate a 256-bit vector with integer types. Since we'll use
9950 // floating point types there eventually, just immediately cast everything to
9951 // a float and operate entirely in that domain.
9952 if (VT.isInteger() && !Subtarget->hasAVX2()) {
9953 int ElementBits = VT.getScalarSizeInBits();
9954 if (ElementBits < 32)
9955 // No floating point type available, decompose into 128-bit vectors.
9956 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9958 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9959 VT.getVectorNumElements());
9960 V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9961 V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9962 return DAG.getNode(ISD::BITCAST, DL, VT,
9963 DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9966 switch (VT.SimpleTy) {
9968 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9970 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9972 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9974 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9976 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9978 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9981 llvm_unreachable("Not a valid 256-bit x86 vector type!");
9985 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
9986 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9987 const X86Subtarget *Subtarget,
9988 SelectionDAG &DAG) {
9990 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9991 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
9992 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9993 ArrayRef<int> Mask = SVOp->getMask();
9994 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9996 // X86 has dedicated unpack instructions that can handle specific blend
9997 // operations: UNPCKH and UNPCKL.
9998 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
9999 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10000 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10001 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10003 // FIXME: Implement direct support for this type!
10004 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10007 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10008 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10009 const X86Subtarget *Subtarget,
10010 SelectionDAG &DAG) {
10012 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10013 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10014 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10015 ArrayRef<int> Mask = SVOp->getMask();
10016 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10018 // Use dedicated unpack instructions for masks that match their pattern.
10019 if (isShuffleEquivalent(V1, V2, Mask,
10020 {// First 128-bit lane.
10021 0, 16, 1, 17, 4, 20, 5, 21,
10022 // Second 128-bit lane.
10023 8, 24, 9, 25, 12, 28, 13, 29}))
10024 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10025 if (isShuffleEquivalent(V1, V2, Mask,
10026 {// First 128-bit lane.
10027 2, 18, 3, 19, 6, 22, 7, 23,
10028 // Second 128-bit lane.
10029 10, 26, 11, 27, 14, 30, 15, 31}))
10030 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10032 // FIXME: Implement direct support for this type!
10033 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10036 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10037 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10038 const X86Subtarget *Subtarget,
10039 SelectionDAG &DAG) {
10041 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10042 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10043 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10044 ArrayRef<int> Mask = SVOp->getMask();
10045 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10047 // X86 has dedicated unpack instructions that can handle specific blend
10048 // operations: UNPCKH and UNPCKL.
10049 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10050 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10051 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10052 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10054 // FIXME: Implement direct support for this type!
10055 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10058 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10059 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060 const X86Subtarget *Subtarget,
10061 SelectionDAG &DAG) {
10063 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10064 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066 ArrayRef<int> Mask = SVOp->getMask();
10067 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10069 // Use dedicated unpack instructions for masks that match their pattern.
10070 if (isShuffleEquivalent(V1, V2, Mask,
10071 {// First 128-bit lane.
10072 0, 16, 1, 17, 4, 20, 5, 21,
10073 // Second 128-bit lane.
10074 8, 24, 9, 25, 12, 28, 13, 29}))
10075 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10076 if (isShuffleEquivalent(V1, V2, Mask,
10077 {// First 128-bit lane.
10078 2, 18, 3, 19, 6, 22, 7, 23,
10079 // Second 128-bit lane.
10080 10, 26, 11, 27, 14, 30, 15, 31}))
10081 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10083 // FIXME: Implement direct support for this type!
10084 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10087 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10088 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10089 const X86Subtarget *Subtarget,
10090 SelectionDAG &DAG) {
10092 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10093 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10094 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10095 ArrayRef<int> Mask = SVOp->getMask();
10096 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10097 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10099 // FIXME: Implement direct support for this type!
10100 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10103 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10104 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10105 const X86Subtarget *Subtarget,
10106 SelectionDAG &DAG) {
10108 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10109 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10110 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10111 ArrayRef<int> Mask = SVOp->getMask();
10112 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10113 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10115 // FIXME: Implement direct support for this type!
10116 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10119 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10121 /// This routine either breaks down the specific type of a 512-bit x86 vector
10122 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10123 /// together based on the available instructions.
10124 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10125 MVT VT, const X86Subtarget *Subtarget,
10126 SelectionDAG &DAG) {
10128 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10129 ArrayRef<int> Mask = SVOp->getMask();
10130 assert(Subtarget->hasAVX512() &&
10131 "Cannot lower 512-bit vectors w/ basic ISA!");
10133 // Check for being able to broadcast a single element.
10134 if (SDValue Broadcast =
10135 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10138 // Dispatch to each element type for lowering. If we don't have supprot for
10139 // specific element type shuffles at 512 bits, immediately split them and
10140 // lower them. Each lowering routine of a given type is allowed to assume that
10141 // the requisite ISA extensions for that element type are available.
10142 switch (VT.SimpleTy) {
10144 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10146 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10148 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10150 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10152 if (Subtarget->hasBWI())
10153 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10156 if (Subtarget->hasBWI())
10157 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10161 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10164 // Otherwise fall back on splitting.
10165 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10168 /// \brief Top-level lowering for x86 vector shuffles.
10170 /// This handles decomposition, canonicalization, and lowering of all x86
10171 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10172 /// above in helper routines. The canonicalization attempts to widen shuffles
10173 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10174 /// s.t. only one of the two inputs needs to be tested, etc.
10175 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10176 SelectionDAG &DAG) {
10177 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10178 ArrayRef<int> Mask = SVOp->getMask();
10179 SDValue V1 = Op.getOperand(0);
10180 SDValue V2 = Op.getOperand(1);
10181 MVT VT = Op.getSimpleValueType();
10182 int NumElements = VT.getVectorNumElements();
10185 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10187 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10188 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10189 if (V1IsUndef && V2IsUndef)
10190 return DAG.getUNDEF(VT);
10192 // When we create a shuffle node we put the UNDEF node to second operand,
10193 // but in some cases the first operand may be transformed to UNDEF.
10194 // In this case we should just commute the node.
10196 return DAG.getCommutedVectorShuffle(*SVOp);
10198 // Check for non-undef masks pointing at an undef vector and make the masks
10199 // undef as well. This makes it easier to match the shuffle based solely on
10203 if (M >= NumElements) {
10204 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10205 for (int &M : NewMask)
10206 if (M >= NumElements)
10208 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10211 // We actually see shuffles that are entirely re-arrangements of a set of
10212 // zero inputs. This mostly happens while decomposing complex shuffles into
10213 // simple ones. Directly lower these as a buildvector of zeros.
10214 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10215 if (Zeroable.all())
10216 return getZeroVector(VT, Subtarget, DAG, dl);
10218 // Try to collapse shuffles into using a vector type with fewer elements but
10219 // wider element types. We cap this to not form integers or floating point
10220 // elements wider than 64 bits, but it might be interesting to form i128
10221 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10222 SmallVector<int, 16> WidenedMask;
10223 if (VT.getScalarSizeInBits() < 64 &&
10224 canWidenShuffleElements(Mask, WidenedMask)) {
10225 MVT NewEltVT = VT.isFloatingPoint()
10226 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10227 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10228 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10229 // Make sure that the new vector type is legal. For example, v2f64 isn't
10231 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10232 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
10233 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
10234 return DAG.getNode(ISD::BITCAST, dl, VT,
10235 DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10239 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10240 for (int M : SVOp->getMask())
10242 ++NumUndefElements;
10243 else if (M < NumElements)
10248 // Commute the shuffle as needed such that more elements come from V1 than
10249 // V2. This allows us to match the shuffle pattern strictly on how many
10250 // elements come from V1 without handling the symmetric cases.
10251 if (NumV2Elements > NumV1Elements)
10252 return DAG.getCommutedVectorShuffle(*SVOp);
10254 // When the number of V1 and V2 elements are the same, try to minimize the
10255 // number of uses of V2 in the low half of the vector. When that is tied,
10256 // ensure that the sum of indices for V1 is equal to or lower than the sum
10257 // indices for V2. When those are equal, try to ensure that the number of odd
10258 // indices for V1 is lower than the number of odd indices for V2.
10259 if (NumV1Elements == NumV2Elements) {
10260 int LowV1Elements = 0, LowV2Elements = 0;
10261 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10262 if (M >= NumElements)
10266 if (LowV2Elements > LowV1Elements) {
10267 return DAG.getCommutedVectorShuffle(*SVOp);
10268 } else if (LowV2Elements == LowV1Elements) {
10269 int SumV1Indices = 0, SumV2Indices = 0;
10270 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10271 if (SVOp->getMask()[i] >= NumElements)
10273 else if (SVOp->getMask()[i] >= 0)
10275 if (SumV2Indices < SumV1Indices) {
10276 return DAG.getCommutedVectorShuffle(*SVOp);
10277 } else if (SumV2Indices == SumV1Indices) {
10278 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10279 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10280 if (SVOp->getMask()[i] >= NumElements)
10281 NumV2OddIndices += i % 2;
10282 else if (SVOp->getMask()[i] >= 0)
10283 NumV1OddIndices += i % 2;
10284 if (NumV2OddIndices < NumV1OddIndices)
10285 return DAG.getCommutedVectorShuffle(*SVOp);
10290 // For each vector width, delegate to a specialized lowering routine.
10291 if (VT.getSizeInBits() == 128)
10292 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10294 if (VT.getSizeInBits() == 256)
10295 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10297 // Force AVX-512 vectors to be scalarized for now.
10298 // FIXME: Implement AVX-512 support!
10299 if (VT.getSizeInBits() == 512)
10300 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10302 llvm_unreachable("Unimplemented!");
10305 // This function assumes its argument is a BUILD_VECTOR of constants or
10306 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10308 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10309 unsigned &MaskValue) {
10311 unsigned NumElems = BuildVector->getNumOperands();
10312 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10313 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10314 unsigned NumElemsInLane = NumElems / NumLanes;
10316 // Blend for v16i16 should be symetric for the both lanes.
10317 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10318 SDValue EltCond = BuildVector->getOperand(i);
10319 SDValue SndLaneEltCond =
10320 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10322 int Lane1Cond = -1, Lane2Cond = -1;
10323 if (isa<ConstantSDNode>(EltCond))
10324 Lane1Cond = !isZero(EltCond);
10325 if (isa<ConstantSDNode>(SndLaneEltCond))
10326 Lane2Cond = !isZero(SndLaneEltCond);
10328 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10329 // Lane1Cond != 0, means we want the first argument.
10330 // Lane1Cond == 0, means we want the second argument.
10331 // The encoding of this argument is 0 for the first argument, 1
10332 // for the second. Therefore, invert the condition.
10333 MaskValue |= !Lane1Cond << i;
10334 else if (Lane1Cond < 0)
10335 MaskValue |= !Lane2Cond << i;
10342 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10343 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10344 const X86Subtarget *Subtarget,
10345 SelectionDAG &DAG) {
10346 SDValue Cond = Op.getOperand(0);
10347 SDValue LHS = Op.getOperand(1);
10348 SDValue RHS = Op.getOperand(2);
10350 MVT VT = Op.getSimpleValueType();
10352 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10354 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10356 // Only non-legal VSELECTs reach this lowering, convert those into generic
10357 // shuffles and re-use the shuffle lowering path for blends.
10358 SmallVector<int, 32> Mask;
10359 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10360 SDValue CondElt = CondBV->getOperand(i);
10362 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10364 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10367 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10368 // A vselect where all conditions and data are constants can be optimized into
10369 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10370 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10371 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10372 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10375 // Try to lower this to a blend-style vector shuffle. This can handle all
10376 // constant condition cases.
10377 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10380 // Variable blends are only legal from SSE4.1 onward.
10381 if (!Subtarget->hasSSE41())
10384 // Only some types will be legal on some subtargets. If we can emit a legal
10385 // VSELECT-matching blend, return Op, and but if we need to expand, return
10387 switch (Op.getSimpleValueType().SimpleTy) {
10389 // Most of the vector types have blends past SSE4.1.
10393 // The byte blends for AVX vectors were introduced only in AVX2.
10394 if (Subtarget->hasAVX2())
10401 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10402 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10405 // FIXME: We should custom lower this by fixing the condition and using i8
10411 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10412 MVT VT = Op.getSimpleValueType();
10415 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10418 if (VT.getSizeInBits() == 8) {
10419 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10420 Op.getOperand(0), Op.getOperand(1));
10421 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10422 DAG.getValueType(VT));
10423 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10426 if (VT.getSizeInBits() == 16) {
10427 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10428 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10430 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10431 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10432 DAG.getNode(ISD::BITCAST, dl,
10435 Op.getOperand(1)));
10436 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10437 Op.getOperand(0), Op.getOperand(1));
10438 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10439 DAG.getValueType(VT));
10440 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10443 if (VT == MVT::f32) {
10444 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10445 // the result back to FR32 register. It's only worth matching if the
10446 // result has a single use which is a store or a bitcast to i32. And in
10447 // the case of a store, it's not worth it if the index is a constant 0,
10448 // because a MOVSSmr can be used instead, which is smaller and faster.
10449 if (!Op.hasOneUse())
10451 SDNode *User = *Op.getNode()->use_begin();
10452 if ((User->getOpcode() != ISD::STORE ||
10453 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10454 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10455 (User->getOpcode() != ISD::BITCAST ||
10456 User->getValueType(0) != MVT::i32))
10458 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10459 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10462 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10465 if (VT == MVT::i32 || VT == MVT::i64) {
10466 // ExtractPS/pextrq works with constant index.
10467 if (isa<ConstantSDNode>(Op.getOperand(1)))
10473 /// Extract one bit from mask vector, like v16i1 or v8i1.
10474 /// AVX-512 feature.
10476 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10477 SDValue Vec = Op.getOperand(0);
10479 MVT VecVT = Vec.getSimpleValueType();
10480 SDValue Idx = Op.getOperand(1);
10481 MVT EltVT = Op.getSimpleValueType();
10483 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10484 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10485 "Unexpected vector type in ExtractBitFromMaskVector");
10487 // variable index can't be handled in mask registers,
10488 // extend vector to VR512
10489 if (!isa<ConstantSDNode>(Idx)) {
10490 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10491 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10492 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10493 ExtVT.getVectorElementType(), Ext, Idx);
10494 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10497 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10498 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10499 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10500 rc = getRegClassFor(MVT::v16i1);
10501 unsigned MaxSift = rc->getSize()*8 - 1;
10502 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10503 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10504 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10505 DAG.getConstant(MaxSift, dl, MVT::i8));
10506 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10507 DAG.getIntPtrConstant(0, dl));
10511 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10512 SelectionDAG &DAG) const {
10514 SDValue Vec = Op.getOperand(0);
10515 MVT VecVT = Vec.getSimpleValueType();
10516 SDValue Idx = Op.getOperand(1);
10518 if (Op.getSimpleValueType() == MVT::i1)
10519 return ExtractBitFromMaskVector(Op, DAG);
10521 if (!isa<ConstantSDNode>(Idx)) {
10522 if (VecVT.is512BitVector() ||
10523 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10524 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10527 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10528 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10529 MaskEltVT.getSizeInBits());
10531 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10532 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10533 getZeroVector(MaskVT, Subtarget, DAG, dl),
10534 Idx, DAG.getConstant(0, dl, getPointerTy()));
10535 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10536 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10537 Perm, DAG.getConstant(0, dl, getPointerTy()));
10542 // If this is a 256-bit vector result, first extract the 128-bit vector and
10543 // then extract the element from the 128-bit vector.
10544 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10546 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10547 // Get the 128-bit vector.
10548 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10549 MVT EltVT = VecVT.getVectorElementType();
10551 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10553 //if (IdxVal >= NumElems/2)
10554 // IdxVal -= NumElems/2;
10555 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10556 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10557 DAG.getConstant(IdxVal, dl, MVT::i32));
10560 assert(VecVT.is128BitVector() && "Unexpected vector length");
10562 if (Subtarget->hasSSE41()) {
10563 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10568 MVT VT = Op.getSimpleValueType();
10569 // TODO: handle v16i8.
10570 if (VT.getSizeInBits() == 16) {
10571 SDValue Vec = Op.getOperand(0);
10572 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10574 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10575 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10576 DAG.getNode(ISD::BITCAST, dl,
10578 Op.getOperand(1)));
10579 // Transform it so it match pextrw which produces a 32-bit result.
10580 MVT EltVT = MVT::i32;
10581 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10582 Op.getOperand(0), Op.getOperand(1));
10583 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10584 DAG.getValueType(VT));
10585 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10588 if (VT.getSizeInBits() == 32) {
10589 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10593 // SHUFPS the element to the lowest double word, then movss.
10594 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10595 MVT VVT = Op.getOperand(0).getSimpleValueType();
10596 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10597 DAG.getUNDEF(VVT), Mask);
10598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10599 DAG.getIntPtrConstant(0, dl));
10602 if (VT.getSizeInBits() == 64) {
10603 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10604 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10605 // to match extract_elt for f64.
10606 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10610 // UNPCKHPD the element to the lowest double word, then movsd.
10611 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10612 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10613 int Mask[2] = { 1, -1 };
10614 MVT VVT = Op.getOperand(0).getSimpleValueType();
10615 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10616 DAG.getUNDEF(VVT), Mask);
10617 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10618 DAG.getIntPtrConstant(0, dl));
10624 /// Insert one bit to mask vector, like v16i1 or v8i1.
10625 /// AVX-512 feature.
10627 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10629 SDValue Vec = Op.getOperand(0);
10630 SDValue Elt = Op.getOperand(1);
10631 SDValue Idx = Op.getOperand(2);
10632 MVT VecVT = Vec.getSimpleValueType();
10634 if (!isa<ConstantSDNode>(Idx)) {
10635 // Non constant index. Extend source and destination,
10636 // insert element and then truncate the result.
10637 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10638 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10639 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10640 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10641 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10642 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10645 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10646 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10647 if (Vec.getOpcode() == ISD::UNDEF)
10648 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10649 DAG.getConstant(IdxVal, dl, MVT::i8));
10650 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10651 unsigned MaxSift = rc->getSize()*8 - 1;
10652 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10653 DAG.getConstant(MaxSift, dl, MVT::i8));
10654 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10655 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10656 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10659 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10660 SelectionDAG &DAG) const {
10661 MVT VT = Op.getSimpleValueType();
10662 MVT EltVT = VT.getVectorElementType();
10664 if (EltVT == MVT::i1)
10665 return InsertBitToMaskVector(Op, DAG);
10668 SDValue N0 = Op.getOperand(0);
10669 SDValue N1 = Op.getOperand(1);
10670 SDValue N2 = Op.getOperand(2);
10671 if (!isa<ConstantSDNode>(N2))
10673 auto *N2C = cast<ConstantSDNode>(N2);
10674 unsigned IdxVal = N2C->getZExtValue();
10676 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10677 // into that, and then insert the subvector back into the result.
10678 if (VT.is256BitVector() || VT.is512BitVector()) {
10679 // With a 256-bit vector, we can insert into the zero element efficiently
10680 // using a blend if we have AVX or AVX2 and the right data type.
10681 if (VT.is256BitVector() && IdxVal == 0) {
10682 // TODO: It is worthwhile to cast integer to floating point and back
10683 // and incur a domain crossing penalty if that's what we'll end up
10684 // doing anyway after extracting to a 128-bit vector.
10685 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10686 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10687 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10688 N2 = DAG.getIntPtrConstant(1, dl);
10689 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10693 // Get the desired 128-bit vector chunk.
10694 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10696 // Insert the element into the desired chunk.
10697 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10698 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10700 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10701 DAG.getConstant(IdxIn128, dl, MVT::i32));
10703 // Insert the changed part back into the bigger vector
10704 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10706 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10708 if (Subtarget->hasSSE41()) {
10709 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10711 if (VT == MVT::v8i16) {
10712 Opc = X86ISD::PINSRW;
10714 assert(VT == MVT::v16i8);
10715 Opc = X86ISD::PINSRB;
10718 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10720 if (N1.getValueType() != MVT::i32)
10721 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10722 if (N2.getValueType() != MVT::i32)
10723 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10724 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10727 if (EltVT == MVT::f32) {
10728 // Bits [7:6] of the constant are the source select. This will always be
10729 // zero here. The DAG Combiner may combine an extract_elt index into
10730 // these bits. For example (insert (extract, 3), 2) could be matched by
10731 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10732 // Bits [5:4] of the constant are the destination select. This is the
10733 // value of the incoming immediate.
10734 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10735 // combine either bitwise AND or insert of float 0.0 to set these bits.
10737 const Function *F = DAG.getMachineFunction().getFunction();
10738 bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10739 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10740 // If this is an insertion of 32-bits into the low 32-bits of
10741 // a vector, we prefer to generate a blend with immediate rather
10742 // than an insertps. Blends are simpler operations in hardware and so
10743 // will always have equal or better performance than insertps.
10744 // But if optimizing for size and there's a load folding opportunity,
10745 // generate insertps because blendps does not have a 32-bit memory
10747 N2 = DAG.getIntPtrConstant(1, dl);
10748 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10749 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10751 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10752 // Create this as a scalar to vector..
10753 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10754 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10757 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10758 // PINSR* works with constant index.
10763 if (EltVT == MVT::i8)
10766 if (EltVT.getSizeInBits() == 16) {
10767 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10768 // as its second argument.
10769 if (N1.getValueType() != MVT::i32)
10770 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10771 if (N2.getValueType() != MVT::i32)
10772 N2 = DAG.getIntPtrConstant(IdxVal, dl);
10773 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10778 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10780 MVT OpVT = Op.getSimpleValueType();
10782 // If this is a 256-bit vector result, first insert into a 128-bit
10783 // vector and then insert into the 256-bit vector.
10784 if (!OpVT.is128BitVector()) {
10785 // Insert into a 128-bit vector.
10786 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10787 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10788 OpVT.getVectorNumElements() / SizeFactor);
10790 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10792 // Insert the 128-bit vector.
10793 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10796 if (OpVT == MVT::v1i64 &&
10797 Op.getOperand(0).getValueType() == MVT::i64)
10798 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10800 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10801 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10802 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10803 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10806 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10807 // a simple subregister reference or explicit instructions to grab
10808 // upper bits of a vector.
10809 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10810 SelectionDAG &DAG) {
10812 SDValue In = Op.getOperand(0);
10813 SDValue Idx = Op.getOperand(1);
10814 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10815 MVT ResVT = Op.getSimpleValueType();
10816 MVT InVT = In.getSimpleValueType();
10818 if (Subtarget->hasFp256()) {
10819 if (ResVT.is128BitVector() &&
10820 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10821 isa<ConstantSDNode>(Idx)) {
10822 return Extract128BitVector(In, IdxVal, DAG, dl);
10824 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10825 isa<ConstantSDNode>(Idx)) {
10826 return Extract256BitVector(In, IdxVal, DAG, dl);
10832 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10833 // simple superregister reference or explicit instructions to insert
10834 // the upper bits of a vector.
10835 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10836 SelectionDAG &DAG) {
10837 if (!Subtarget->hasAVX())
10841 SDValue Vec = Op.getOperand(0);
10842 SDValue SubVec = Op.getOperand(1);
10843 SDValue Idx = Op.getOperand(2);
10845 if (!isa<ConstantSDNode>(Idx))
10848 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10849 MVT OpVT = Op.getSimpleValueType();
10850 MVT SubVecVT = SubVec.getSimpleValueType();
10852 // Fold two 16-byte subvector loads into one 32-byte load:
10853 // (insert_subvector (insert_subvector undef, (load addr), 0),
10854 // (load addr + 16), Elts/2)
10856 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10857 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10858 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10859 !Subtarget->isUnalignedMem32Slow()) {
10860 SDValue SubVec2 = Vec.getOperand(1);
10861 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10862 if (Idx2->getZExtValue() == 0) {
10863 SDValue Ops[] = { SubVec2, SubVec };
10864 SDValue LD = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false);
10871 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
10872 SubVecVT.is128BitVector())
10873 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10875 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
10876 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10878 if (OpVT.getVectorElementType() == MVT::i1) {
10879 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
10881 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
10882 SDValue Undef = DAG.getUNDEF(OpVT);
10883 unsigned NumElems = OpVT.getVectorNumElements();
10884 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
10886 if (IdxVal == OpVT.getVectorNumElements() / 2) {
10887 // Zero upper bits of the Vec
10888 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10889 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10891 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10893 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10894 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10897 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
10899 // Zero upper bits of the Vec2
10900 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
10901 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
10902 // Zero lower bits of the Vec
10903 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
10904 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
10905 // Merge them together
10906 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
10912 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10913 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10914 // one of the above mentioned nodes. It has to be wrapped because otherwise
10915 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10916 // be used to form addressing mode. These wrapped nodes will be selected
10919 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10920 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10922 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10923 // global base reg.
10924 unsigned char OpFlag = 0;
10925 unsigned WrapperKind = X86ISD::Wrapper;
10926 CodeModel::Model M = DAG.getTarget().getCodeModel();
10928 if (Subtarget->isPICStyleRIPRel() &&
10929 (M == CodeModel::Small || M == CodeModel::Kernel))
10930 WrapperKind = X86ISD::WrapperRIP;
10931 else if (Subtarget->isPICStyleGOT())
10932 OpFlag = X86II::MO_GOTOFF;
10933 else if (Subtarget->isPICStyleStubPIC())
10934 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10936 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10937 CP->getAlignment(),
10938 CP->getOffset(), OpFlag);
10940 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10941 // With PIC, the address is actually $g + Offset.
10943 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10944 DAG.getNode(X86ISD::GlobalBaseReg,
10945 SDLoc(), getPointerTy()),
10952 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10953 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10955 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10956 // global base reg.
10957 unsigned char OpFlag = 0;
10958 unsigned WrapperKind = X86ISD::Wrapper;
10959 CodeModel::Model M = DAG.getTarget().getCodeModel();
10961 if (Subtarget->isPICStyleRIPRel() &&
10962 (M == CodeModel::Small || M == CodeModel::Kernel))
10963 WrapperKind = X86ISD::WrapperRIP;
10964 else if (Subtarget->isPICStyleGOT())
10965 OpFlag = X86II::MO_GOTOFF;
10966 else if (Subtarget->isPICStyleStubPIC())
10967 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10969 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10972 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10974 // With PIC, the address is actually $g + Offset.
10976 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10977 DAG.getNode(X86ISD::GlobalBaseReg,
10978 SDLoc(), getPointerTy()),
10985 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10986 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10988 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10989 // global base reg.
10990 unsigned char OpFlag = 0;
10991 unsigned WrapperKind = X86ISD::Wrapper;
10992 CodeModel::Model M = DAG.getTarget().getCodeModel();
10994 if (Subtarget->isPICStyleRIPRel() &&
10995 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10996 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10997 OpFlag = X86II::MO_GOTPCREL;
10998 WrapperKind = X86ISD::WrapperRIP;
10999 } else if (Subtarget->isPICStyleGOT()) {
11000 OpFlag = X86II::MO_GOT;
11001 } else if (Subtarget->isPICStyleStubPIC()) {
11002 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11003 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11004 OpFlag = X86II::MO_DARWIN_NONLAZY;
11007 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11010 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11012 // With PIC, the address is actually $g + Offset.
11013 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11014 !Subtarget->is64Bit()) {
11015 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11016 DAG.getNode(X86ISD::GlobalBaseReg,
11017 SDLoc(), getPointerTy()),
11021 // For symbols that require a load from a stub to get the address, emit the
11023 if (isGlobalStubReference(OpFlag))
11024 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11025 MachinePointerInfo::getGOT(), false, false, false, 0);
11031 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11032 // Create the TargetBlockAddressAddress node.
11033 unsigned char OpFlags =
11034 Subtarget->ClassifyBlockAddressReference();
11035 CodeModel::Model M = DAG.getTarget().getCodeModel();
11036 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11037 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11039 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11042 if (Subtarget->isPICStyleRIPRel() &&
11043 (M == CodeModel::Small || M == CodeModel::Kernel))
11044 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11046 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11048 // With PIC, the address is actually $g + Offset.
11049 if (isGlobalRelativeToPICBase(OpFlags)) {
11050 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11051 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11059 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11060 int64_t Offset, SelectionDAG &DAG) const {
11061 // Create the TargetGlobalAddress node, folding in the constant
11062 // offset if it is legal.
11063 unsigned char OpFlags =
11064 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11065 CodeModel::Model M = DAG.getTarget().getCodeModel();
11067 if (OpFlags == X86II::MO_NO_FLAG &&
11068 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11069 // A direct static reference to a global.
11070 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11073 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11076 if (Subtarget->isPICStyleRIPRel() &&
11077 (M == CodeModel::Small || M == CodeModel::Kernel))
11078 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11080 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11082 // With PIC, the address is actually $g + Offset.
11083 if (isGlobalRelativeToPICBase(OpFlags)) {
11084 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11085 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11089 // For globals that require a load from a stub to get the address, emit the
11091 if (isGlobalStubReference(OpFlags))
11092 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11093 MachinePointerInfo::getGOT(), false, false, false, 0);
11095 // If there was a non-zero offset that we didn't fold, create an explicit
11096 // addition for it.
11098 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11099 DAG.getConstant(Offset, dl, getPointerTy()));
11105 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11106 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11107 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11108 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11112 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11113 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11114 unsigned char OperandFlags, bool LocalDynamic = false) {
11115 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11116 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11118 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11119 GA->getValueType(0),
11123 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11127 SDValue Ops[] = { Chain, TGA, *InFlag };
11128 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11130 SDValue Ops[] = { Chain, TGA };
11131 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11134 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11135 MFI->setAdjustsStack(true);
11136 MFI->setHasCalls(true);
11138 SDValue Flag = Chain.getValue(1);
11139 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11142 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11144 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11147 SDLoc dl(GA); // ? function entry point might be better
11148 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11149 DAG.getNode(X86ISD::GlobalBaseReg,
11150 SDLoc(), PtrVT), InFlag);
11151 InFlag = Chain.getValue(1);
11153 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11156 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11158 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11160 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11161 X86::RAX, X86II::MO_TLSGD);
11164 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11170 // Get the start address of the TLS block for this module.
11171 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11172 .getInfo<X86MachineFunctionInfo>();
11173 MFI->incNumLocalDynamicTLSAccesses();
11177 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11178 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11181 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11182 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11183 InFlag = Chain.getValue(1);
11184 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11185 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11188 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11192 unsigned char OperandFlags = X86II::MO_DTPOFF;
11193 unsigned WrapperKind = X86ISD::Wrapper;
11194 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11195 GA->getValueType(0),
11196 GA->getOffset(), OperandFlags);
11197 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11199 // Add x@dtpoff with the base.
11200 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11203 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11204 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11205 const EVT PtrVT, TLSModel::Model model,
11206 bool is64Bit, bool isPIC) {
11209 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11210 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11211 is64Bit ? 257 : 256));
11213 SDValue ThreadPointer =
11214 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11215 MachinePointerInfo(Ptr), false, false, false, 0);
11217 unsigned char OperandFlags = 0;
11218 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11220 unsigned WrapperKind = X86ISD::Wrapper;
11221 if (model == TLSModel::LocalExec) {
11222 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11223 } else if (model == TLSModel::InitialExec) {
11225 OperandFlags = X86II::MO_GOTTPOFF;
11226 WrapperKind = X86ISD::WrapperRIP;
11228 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11231 llvm_unreachable("Unexpected model");
11234 // emit "addl x@ntpoff,%eax" (local exec)
11235 // or "addl x@indntpoff,%eax" (initial exec)
11236 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11238 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11239 GA->getOffset(), OperandFlags);
11240 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11242 if (model == TLSModel::InitialExec) {
11243 if (isPIC && !is64Bit) {
11244 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11245 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11249 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11250 MachinePointerInfo::getGOT(), false, false, false, 0);
11253 // The address of the thread local variable is the add of the thread
11254 // pointer with the offset of the variable.
11255 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11259 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11261 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11262 const GlobalValue *GV = GA->getGlobal();
11264 if (Subtarget->isTargetELF()) {
11265 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11268 case TLSModel::GeneralDynamic:
11269 if (Subtarget->is64Bit())
11270 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11271 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11272 case TLSModel::LocalDynamic:
11273 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11274 Subtarget->is64Bit());
11275 case TLSModel::InitialExec:
11276 case TLSModel::LocalExec:
11277 return LowerToTLSExecModel(
11278 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11279 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11281 llvm_unreachable("Unknown TLS model.");
11284 if (Subtarget->isTargetDarwin()) {
11285 // Darwin only has one model of TLS. Lower to that.
11286 unsigned char OpFlag = 0;
11287 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11288 X86ISD::WrapperRIP : X86ISD::Wrapper;
11290 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11291 // global base reg.
11292 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11293 !Subtarget->is64Bit();
11295 OpFlag = X86II::MO_TLVP_PIC_BASE;
11297 OpFlag = X86II::MO_TLVP;
11299 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11300 GA->getValueType(0),
11301 GA->getOffset(), OpFlag);
11302 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11304 // With PIC32, the address is actually $g + Offset.
11306 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11307 DAG.getNode(X86ISD::GlobalBaseReg,
11308 SDLoc(), getPointerTy()),
11311 // Lowering the machine isd will make sure everything is in the right
11313 SDValue Chain = DAG.getEntryNode();
11314 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11315 SDValue Args[] = { Chain, Offset };
11316 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11318 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11319 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11320 MFI->setAdjustsStack(true);
11322 // And our return value (tls address) is in the standard call return value
11324 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11325 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11326 Chain.getValue(1));
11329 if (Subtarget->isTargetKnownWindowsMSVC() ||
11330 Subtarget->isTargetWindowsGNU()) {
11331 // Just use the implicit TLS architecture
11332 // Need to generate someting similar to:
11333 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11335 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11336 // mov rcx, qword [rdx+rcx*8]
11337 // mov eax, .tls$:tlsvar
11338 // [rax+rcx] contains the address
11339 // Windows 64bit: gs:0x58
11340 // Windows 32bit: fs:__tls_array
11343 SDValue Chain = DAG.getEntryNode();
11345 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11346 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11347 // use its literal value of 0x2C.
11348 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11349 ? Type::getInt8PtrTy(*DAG.getContext(),
11351 : Type::getInt32PtrTy(*DAG.getContext(),
11355 Subtarget->is64Bit()
11356 ? DAG.getIntPtrConstant(0x58, dl)
11357 : (Subtarget->isTargetWindowsGNU()
11358 ? DAG.getIntPtrConstant(0x2C, dl)
11359 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11361 SDValue ThreadPointer =
11362 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11363 MachinePointerInfo(Ptr), false, false, false, 0);
11365 // Load the _tls_index variable
11366 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11367 if (Subtarget->is64Bit())
11368 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11369 IDX, MachinePointerInfo(), MVT::i32,
11370 false, false, false, 0);
11372 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11373 false, false, false, 0);
11375 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11377 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11379 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11380 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11381 false, false, false, 0);
11383 // Get the offset of start of .tls section
11384 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11385 GA->getValueType(0),
11386 GA->getOffset(), X86II::MO_SECREL);
11387 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11389 // The address of the thread local variable is the add of the thread
11390 // pointer with the offset of the variable.
11391 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11394 llvm_unreachable("TLS not implemented for this target.");
11397 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11398 /// and take a 2 x i32 value to shift plus a shift amount.
11399 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11400 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11401 MVT VT = Op.getSimpleValueType();
11402 unsigned VTBits = VT.getSizeInBits();
11404 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11405 SDValue ShOpLo = Op.getOperand(0);
11406 SDValue ShOpHi = Op.getOperand(1);
11407 SDValue ShAmt = Op.getOperand(2);
11408 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11409 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11411 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11412 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11413 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11414 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11415 : DAG.getConstant(0, dl, VT);
11417 SDValue Tmp2, Tmp3;
11418 if (Op.getOpcode() == ISD::SHL_PARTS) {
11419 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11420 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11422 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11423 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11426 // If the shift amount is larger or equal than the width of a part we can't
11427 // rely on the results of shld/shrd. Insert a test and select the appropriate
11428 // values for large shift amounts.
11429 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11430 DAG.getConstant(VTBits, dl, MVT::i8));
11431 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11432 AndNode, DAG.getConstant(0, dl, MVT::i8));
11435 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11436 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11437 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11439 if (Op.getOpcode() == ISD::SHL_PARTS) {
11440 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11441 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11443 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11444 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11447 SDValue Ops[2] = { Lo, Hi };
11448 return DAG.getMergeValues(Ops, dl);
11451 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11452 SelectionDAG &DAG) const {
11453 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11456 if (SrcVT.isVector()) {
11457 if (SrcVT.getVectorElementType() == MVT::i1) {
11458 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11459 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11460 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT,
11461 Op.getOperand(0)));
11466 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11467 "Unknown SINT_TO_FP to lower!");
11469 // These are really Legal; return the operand so the caller accepts it as
11471 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11473 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11474 Subtarget->is64Bit()) {
11478 unsigned Size = SrcVT.getSizeInBits()/8;
11479 MachineFunction &MF = DAG.getMachineFunction();
11480 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11481 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11482 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11484 MachinePointerInfo::getFixedStack(SSFI),
11486 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11489 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11491 SelectionDAG &DAG) const {
11495 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11497 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11499 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11501 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11503 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11504 MachineMemOperand *MMO;
11506 int SSFI = FI->getIndex();
11508 DAG.getMachineFunction()
11509 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11510 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11512 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11513 StackSlot = StackSlot.getOperand(1);
11515 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11516 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11518 Tys, Ops, SrcVT, MMO);
11521 Chain = Result.getValue(1);
11522 SDValue InFlag = Result.getValue(2);
11524 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11525 // shouldn't be necessary except that RFP cannot be live across
11526 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11527 MachineFunction &MF = DAG.getMachineFunction();
11528 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11529 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11530 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11531 Tys = DAG.getVTList(MVT::Other);
11533 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11535 MachineMemOperand *MMO =
11536 DAG.getMachineFunction()
11537 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11538 MachineMemOperand::MOStore, SSFISize, SSFISize);
11540 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11541 Ops, Op.getValueType(), MMO);
11542 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11543 MachinePointerInfo::getFixedStack(SSFI),
11544 false, false, false, 0);
11550 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11551 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11552 SelectionDAG &DAG) const {
11553 // This algorithm is not obvious. Here it is what we're trying to output:
11556 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11557 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11559 haddpd %xmm0, %xmm0
11561 pshufd $0x4e, %xmm0, %xmm1
11567 LLVMContext *Context = DAG.getContext();
11569 // Build some magic constants.
11570 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11571 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11572 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11574 SmallVector<Constant*,2> CV1;
11576 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11577 APInt(64, 0x4330000000000000ULL))));
11579 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11580 APInt(64, 0x4530000000000000ULL))));
11581 Constant *C1 = ConstantVector::get(CV1);
11582 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11584 // Load the 64-bit value into an XMM register.
11585 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11587 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11588 MachinePointerInfo::getConstantPool(),
11589 false, false, false, 16);
11590 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11591 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11594 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11595 MachinePointerInfo::getConstantPool(),
11596 false, false, false, 16);
11597 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11598 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11601 if (Subtarget->hasSSE3()) {
11602 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11603 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11605 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11606 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11608 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11609 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11613 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11614 DAG.getIntPtrConstant(0, dl));
11617 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11618 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11619 SelectionDAG &DAG) const {
11621 // FP constant to bias correct the final result.
11622 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11625 // Load the 32-bit value into an XMM register.
11626 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11629 // Zero out the upper parts of the register.
11630 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11632 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11633 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11634 DAG.getIntPtrConstant(0, dl));
11636 // Or the load with the bias.
11637 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11638 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11639 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11640 MVT::v2f64, Load)),
11641 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11642 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11643 MVT::v2f64, Bias)));
11644 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11645 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11646 DAG.getIntPtrConstant(0, dl));
11648 // Subtract the bias.
11649 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11651 // Handle final rounding.
11652 EVT DestVT = Op.getValueType();
11654 if (DestVT.bitsLT(MVT::f64))
11655 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11656 DAG.getIntPtrConstant(0, dl));
11657 if (DestVT.bitsGT(MVT::f64))
11658 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11660 // Handle final rounding.
11664 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11665 const X86Subtarget &Subtarget) {
11666 // The algorithm is the following:
11667 // #ifdef __SSE4_1__
11668 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11669 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11670 // (uint4) 0x53000000, 0xaa);
11672 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11673 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11675 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11676 // return (float4) lo + fhi;
11679 SDValue V = Op->getOperand(0);
11680 EVT VecIntVT = V.getValueType();
11681 bool Is128 = VecIntVT == MVT::v4i32;
11682 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11683 // If we convert to something else than the supported type, e.g., to v4f64,
11685 if (VecFloatVT != Op->getValueType(0))
11688 unsigned NumElts = VecIntVT.getVectorNumElements();
11689 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11690 "Unsupported custom type");
11691 assert(NumElts <= 8 && "The size of the constant array must be fixed");
11693 // In the #idef/#else code, we have in common:
11694 // - The vector of constants:
11700 // Create the splat vector for 0x4b000000.
11701 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11702 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11703 CstLow, CstLow, CstLow, CstLow};
11704 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11705 makeArrayRef(&CstLowArray[0], NumElts));
11706 // Create the splat vector for 0x53000000.
11707 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11708 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11709 CstHigh, CstHigh, CstHigh, CstHigh};
11710 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11711 makeArrayRef(&CstHighArray[0], NumElts));
11713 // Create the right shift.
11714 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11715 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11716 CstShift, CstShift, CstShift, CstShift};
11717 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11718 makeArrayRef(&CstShiftArray[0], NumElts));
11719 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11722 if (Subtarget.hasSSE41()) {
11723 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11724 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11725 SDValue VecCstLowBitcast =
11726 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstLow);
11727 SDValue VecBitcast = DAG.getNode(ISD::BITCAST, DL, VecI16VT, V);
11728 // Low will be bitcasted right away, so do not bother bitcasting back to its
11730 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11731 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11732 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11733 // (uint4) 0x53000000, 0xaa);
11734 SDValue VecCstHighBitcast =
11735 DAG.getNode(ISD::BITCAST, DL, VecI16VT, VecCstHigh);
11736 SDValue VecShiftBitcast =
11737 DAG.getNode(ISD::BITCAST, DL, VecI16VT, HighShift);
11738 // High will be bitcasted right away, so do not bother bitcasting back to
11739 // its original type.
11740 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11741 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11743 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11744 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11745 CstMask, CstMask, CstMask);
11746 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11747 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11748 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11750 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
11751 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11754 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11755 SDValue CstFAdd = DAG.getConstantFP(
11756 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11757 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11758 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11759 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11760 makeArrayRef(&CstFAddArray[0], NumElts));
11762 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11763 SDValue HighBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, High);
11765 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11766 // return (float4) lo + fhi;
11767 SDValue LowBitcast = DAG.getNode(ISD::BITCAST, DL, VecFloatVT, Low);
11768 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11771 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11772 SelectionDAG &DAG) const {
11773 SDValue N0 = Op.getOperand(0);
11774 MVT SVT = N0.getSimpleValueType();
11777 switch (SVT.SimpleTy) {
11779 llvm_unreachable("Custom UINT_TO_FP is not supported!");
11784 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11785 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11786 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11790 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11792 llvm_unreachable(nullptr);
11795 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11796 SelectionDAG &DAG) const {
11797 SDValue N0 = Op.getOperand(0);
11800 if (Op.getValueType().isVector())
11801 return lowerUINT_TO_FP_vec(Op, DAG);
11803 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11804 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11805 // the optimization here.
11806 if (DAG.SignBitIsZero(N0))
11807 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11809 MVT SrcVT = N0.getSimpleValueType();
11810 MVT DstVT = Op.getSimpleValueType();
11811 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11812 return LowerUINT_TO_FP_i64(Op, DAG);
11813 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11814 return LowerUINT_TO_FP_i32(Op, DAG);
11815 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11818 // Make a 64-bit buffer, and use it to build an FILD.
11819 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11820 if (SrcVT == MVT::i32) {
11821 SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11822 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11823 getPointerTy(), StackSlot, WordOff);
11824 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11825 StackSlot, MachinePointerInfo(),
11827 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11828 OffsetSlot, MachinePointerInfo(),
11830 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11834 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11835 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11836 StackSlot, MachinePointerInfo(),
11838 // For i64 source, we need to add the appropriate power of 2 if the input
11839 // was negative. This is the same as the optimization in
11840 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11841 // we must be careful to do the computation in x87 extended precision, not
11842 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11843 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11844 MachineMemOperand *MMO =
11845 DAG.getMachineFunction()
11846 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11847 MachineMemOperand::MOLoad, 8, 8);
11849 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11850 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11851 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11854 APInt FF(32, 0x5F800000ULL);
11856 // Check whether the sign bit is set.
11857 SDValue SignSet = DAG.getSetCC(dl,
11858 getSetCCResultType(*DAG.getContext(), MVT::i64),
11860 DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
11862 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11863 SDValue FudgePtr = DAG.getConstantPool(
11864 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11867 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11868 SDValue Zero = DAG.getIntPtrConstant(0, dl);
11869 SDValue Four = DAG.getIntPtrConstant(4, dl);
11870 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11872 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11874 // Load the value out, extending it from f32 to f80.
11875 // FIXME: Avoid the extend by constructing the right constant pool?
11876 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11877 FudgePtr, MachinePointerInfo::getConstantPool(),
11878 MVT::f32, false, false, false, 4);
11879 // Extend everything to 80 bits to force it to be done on x87.
11880 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11881 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
11882 DAG.getIntPtrConstant(0, dl));
11885 std::pair<SDValue,SDValue>
11886 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11887 bool IsSigned, bool IsReplace) const {
11890 EVT DstTy = Op.getValueType();
11892 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11893 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11897 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11898 DstTy.getSimpleVT() >= MVT::i16 &&
11899 "Unknown FP_TO_INT to lower!");
11901 // These are really Legal.
11902 if (DstTy == MVT::i32 &&
11903 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11904 return std::make_pair(SDValue(), SDValue());
11905 if (Subtarget->is64Bit() &&
11906 DstTy == MVT::i64 &&
11907 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11908 return std::make_pair(SDValue(), SDValue());
11910 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11911 // stack slot, or into the FTOL runtime function.
11912 MachineFunction &MF = DAG.getMachineFunction();
11913 unsigned MemSize = DstTy.getSizeInBits()/8;
11914 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11915 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11918 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11919 Opc = X86ISD::WIN_FTOL;
11921 switch (DstTy.getSimpleVT().SimpleTy) {
11922 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11923 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11924 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11925 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11928 SDValue Chain = DAG.getEntryNode();
11929 SDValue Value = Op.getOperand(0);
11930 EVT TheVT = Op.getOperand(0).getValueType();
11931 // FIXME This causes a redundant load/store if the SSE-class value is already
11932 // in memory, such as if it is on the callstack.
11933 if (isScalarFPTypeInSSEReg(TheVT)) {
11934 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11935 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11936 MachinePointerInfo::getFixedStack(SSFI),
11938 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11940 Chain, StackSlot, DAG.getValueType(TheVT)
11943 MachineMemOperand *MMO =
11944 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11945 MachineMemOperand::MOLoad, MemSize, MemSize);
11946 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11947 Chain = Value.getValue(1);
11948 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11949 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11952 MachineMemOperand *MMO =
11953 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11954 MachineMemOperand::MOStore, MemSize, MemSize);
11956 if (Opc != X86ISD::WIN_FTOL) {
11957 // Build the FP_TO_INT*_IN_MEM
11958 SDValue Ops[] = { Chain, Value, StackSlot };
11959 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11961 return std::make_pair(FIST, StackSlot);
11963 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11964 DAG.getVTList(MVT::Other, MVT::Glue),
11966 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11967 MVT::i32, ftol.getValue(1));
11968 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11969 MVT::i32, eax.getValue(2));
11970 SDValue Ops[] = { eax, edx };
11971 SDValue pair = IsReplace
11972 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11973 : DAG.getMergeValues(Ops, DL);
11974 return std::make_pair(pair, SDValue());
11978 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11979 const X86Subtarget *Subtarget) {
11980 MVT VT = Op->getSimpleValueType(0);
11981 SDValue In = Op->getOperand(0);
11982 MVT InVT = In.getSimpleValueType();
11985 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
11986 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
11988 // Optimize vectors in AVX mode:
11991 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11992 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11993 // Concat upper and lower parts.
11996 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11997 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11998 // Concat upper and lower parts.
12001 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12002 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12003 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12006 if (Subtarget->hasInt256())
12007 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12009 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12010 SDValue Undef = DAG.getUNDEF(InVT);
12011 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12012 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12013 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12015 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12016 VT.getVectorNumElements()/2);
12018 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12019 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12021 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12024 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12025 SelectionDAG &DAG) {
12026 MVT VT = Op->getSimpleValueType(0);
12027 SDValue In = Op->getOperand(0);
12028 MVT InVT = In.getSimpleValueType();
12030 unsigned int NumElts = VT.getVectorNumElements();
12031 if (NumElts != 8 && NumElts != 16)
12034 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12035 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12037 assert(InVT.getVectorElementType() == MVT::i1);
12038 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12040 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12042 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12044 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12045 if (VT.is512BitVector())
12047 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12050 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12051 SelectionDAG &DAG) {
12052 if (Subtarget->hasFp256()) {
12053 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12061 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12062 SelectionDAG &DAG) {
12064 MVT VT = Op.getSimpleValueType();
12065 SDValue In = Op.getOperand(0);
12066 MVT SVT = In.getSimpleValueType();
12068 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12069 return LowerZERO_EXTEND_AVX512(Op, DAG);
12071 if (Subtarget->hasFp256()) {
12072 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12077 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12078 VT.getVectorNumElements() != SVT.getVectorNumElements());
12082 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12084 MVT VT = Op.getSimpleValueType();
12085 SDValue In = Op.getOperand(0);
12086 MVT InVT = In.getSimpleValueType();
12088 if (VT == MVT::i1) {
12089 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12090 "Invalid scalar TRUNCATE operation");
12091 if (InVT.getSizeInBits() >= 32)
12093 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12094 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12096 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12097 "Invalid TRUNCATE operation");
12099 // move vector to mask - truncate solution for SKX
12100 if (VT.getVectorElementType() == MVT::i1) {
12101 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12102 Subtarget->hasBWI())
12103 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12104 if ((InVT.is256BitVector() || InVT.is128BitVector())
12105 && InVT.getScalarSizeInBits() <= 16 &&
12106 Subtarget->hasBWI() && Subtarget->hasVLX())
12107 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12108 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12109 Subtarget->hasDQI())
12110 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12111 if ((InVT.is256BitVector() || InVT.is128BitVector())
12112 && InVT.getScalarSizeInBits() >= 32 &&
12113 Subtarget->hasDQI() && Subtarget->hasVLX())
12114 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12116 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12117 if (VT.getVectorElementType().getSizeInBits() >=8)
12118 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12120 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12121 unsigned NumElts = InVT.getVectorNumElements();
12122 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12123 if (InVT.getSizeInBits() < 512) {
12124 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12125 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12130 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12131 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12132 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12135 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12136 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12137 if (Subtarget->hasInt256()) {
12138 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12139 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12140 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12142 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12143 DAG.getIntPtrConstant(0, DL));
12146 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12147 DAG.getIntPtrConstant(0, DL));
12148 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12149 DAG.getIntPtrConstant(2, DL));
12150 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12151 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12152 static const int ShufMask[] = {0, 2, 4, 6};
12153 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12156 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12157 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12158 if (Subtarget->hasInt256()) {
12159 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12161 SmallVector<SDValue,32> pshufbMask;
12162 for (unsigned i = 0; i < 2; ++i) {
12163 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12164 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12165 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12166 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12167 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12168 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12169 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12170 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12171 for (unsigned j = 0; j < 8; ++j)
12172 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12174 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12175 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12176 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12178 static const int ShufMask[] = {0, 2, -1, -1};
12179 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12181 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12182 DAG.getIntPtrConstant(0, DL));
12183 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12186 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12187 DAG.getIntPtrConstant(0, DL));
12189 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12190 DAG.getIntPtrConstant(4, DL));
12192 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12193 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12195 // The PSHUFB mask:
12196 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12197 -1, -1, -1, -1, -1, -1, -1, -1};
12199 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12200 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12201 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12203 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12204 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12206 // The MOVLHPS Mask:
12207 static const int ShufMask2[] = {0, 1, 4, 5};
12208 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12209 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12212 // Handle truncation of V256 to V128 using shuffles.
12213 if (!VT.is128BitVector() || !InVT.is256BitVector())
12216 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12218 unsigned NumElems = VT.getVectorNumElements();
12219 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12221 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12222 // Prepare truncation shuffle mask
12223 for (unsigned i = 0; i != NumElems; ++i)
12224 MaskVec[i] = i * 2;
12225 SDValue V = DAG.getVectorShuffle(NVT, DL,
12226 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12227 DAG.getUNDEF(NVT), &MaskVec[0]);
12228 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12229 DAG.getIntPtrConstant(0, DL));
12232 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12233 SelectionDAG &DAG) const {
12234 assert(!Op.getSimpleValueType().isVector());
12236 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12237 /*IsSigned=*/ true, /*IsReplace=*/ false);
12238 SDValue FIST = Vals.first, StackSlot = Vals.second;
12239 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12240 if (!FIST.getNode()) return Op;
12242 if (StackSlot.getNode())
12243 // Load the result.
12244 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12245 FIST, StackSlot, MachinePointerInfo(),
12246 false, false, false, 0);
12248 // The node is the result.
12252 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12253 SelectionDAG &DAG) const {
12254 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12255 /*IsSigned=*/ false, /*IsReplace=*/ false);
12256 SDValue FIST = Vals.first, StackSlot = Vals.second;
12257 assert(FIST.getNode() && "Unexpected failure");
12259 if (StackSlot.getNode())
12260 // Load the result.
12261 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12262 FIST, StackSlot, MachinePointerInfo(),
12263 false, false, false, 0);
12265 // The node is the result.
12269 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12271 MVT VT = Op.getSimpleValueType();
12272 SDValue In = Op.getOperand(0);
12273 MVT SVT = In.getSimpleValueType();
12275 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12277 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12278 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12279 In, DAG.getUNDEF(SVT)));
12282 /// The only differences between FABS and FNEG are the mask and the logic op.
12283 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12284 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12285 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12286 "Wrong opcode for lowering FABS or FNEG.");
12288 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12290 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12291 // into an FNABS. We'll lower the FABS after that if it is still in use.
12293 for (SDNode *User : Op->uses())
12294 if (User->getOpcode() == ISD::FNEG)
12297 SDValue Op0 = Op.getOperand(0);
12298 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12301 MVT VT = Op.getSimpleValueType();
12302 // Assume scalar op for initialization; update for vector if needed.
12303 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12304 // generate a 16-byte vector constant and logic op even for the scalar case.
12305 // Using a 16-byte mask allows folding the load of the mask with
12306 // the logic op, so it can save (~4 bytes) on code size.
12308 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12309 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12310 // decide if we should generate a 16-byte constant mask when we only need 4 or
12311 // 8 bytes for the scalar case.
12312 if (VT.isVector()) {
12313 EltVT = VT.getVectorElementType();
12314 NumElts = VT.getVectorNumElements();
12317 unsigned EltBits = EltVT.getSizeInBits();
12318 LLVMContext *Context = DAG.getContext();
12319 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12321 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12322 Constant *C = ConstantInt::get(*Context, MaskElt);
12323 C = ConstantVector::getSplat(NumElts, C);
12324 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12325 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12326 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12327 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12328 MachinePointerInfo::getConstantPool(),
12329 false, false, false, Alignment);
12331 if (VT.isVector()) {
12332 // For a vector, cast operands to a vector type, perform the logic op,
12333 // and cast the result back to the original value type.
12334 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12335 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12336 SDValue Operand = IsFNABS ?
12337 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0.getOperand(0)) :
12338 DAG.getNode(ISD::BITCAST, dl, VecVT, Op0);
12339 unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12340 return DAG.getNode(ISD::BITCAST, dl, VT,
12341 DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12344 // If not vector, then scalar.
12345 unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12346 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12347 return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12350 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12351 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12352 LLVMContext *Context = DAG.getContext();
12353 SDValue Op0 = Op.getOperand(0);
12354 SDValue Op1 = Op.getOperand(1);
12356 MVT VT = Op.getSimpleValueType();
12357 MVT SrcVT = Op1.getSimpleValueType();
12359 // If second operand is smaller, extend it first.
12360 if (SrcVT.bitsLT(VT)) {
12361 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12364 // And if it is bigger, shrink it first.
12365 if (SrcVT.bitsGT(VT)) {
12366 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12370 // At this point the operands and the result should have the same
12371 // type, and that won't be f80 since that is not custom lowered.
12373 const fltSemantics &Sem =
12374 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12375 const unsigned SizeInBits = VT.getSizeInBits();
12377 SmallVector<Constant *, 4> CV(
12378 VT == MVT::f64 ? 2 : 4,
12379 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12381 // First, clear all bits but the sign bit from the second operand (sign).
12382 CV[0] = ConstantFP::get(*Context,
12383 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12384 Constant *C = ConstantVector::get(CV);
12385 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12386 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12387 MachinePointerInfo::getConstantPool(),
12388 false, false, false, 16);
12389 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12391 // Next, clear the sign bit from the first operand (magnitude).
12392 // If it's a constant, we can clear it here.
12393 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12394 APFloat APF = Op0CN->getValueAPF();
12395 // If the magnitude is a positive zero, the sign bit alone is enough.
12396 if (APF.isPosZero())
12399 CV[0] = ConstantFP::get(*Context, APF);
12401 CV[0] = ConstantFP::get(
12403 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12405 C = ConstantVector::get(CV);
12406 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12407 SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12408 MachinePointerInfo::getConstantPool(),
12409 false, false, false, 16);
12410 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12411 if (!isa<ConstantFPSDNode>(Op0))
12412 Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12414 // OR the magnitude value with the sign bit.
12415 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12418 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12419 SDValue N0 = Op.getOperand(0);
12421 MVT VT = Op.getSimpleValueType();
12423 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12424 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12425 DAG.getConstant(1, dl, VT));
12426 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12429 // Check whether an OR'd tree is PTEST-able.
12430 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12431 SelectionDAG &DAG) {
12432 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12434 if (!Subtarget->hasSSE41())
12437 if (!Op->hasOneUse())
12440 SDNode *N = Op.getNode();
12443 SmallVector<SDValue, 8> Opnds;
12444 DenseMap<SDValue, unsigned> VecInMap;
12445 SmallVector<SDValue, 8> VecIns;
12446 EVT VT = MVT::Other;
12448 // Recognize a special case where a vector is casted into wide integer to
12450 Opnds.push_back(N->getOperand(0));
12451 Opnds.push_back(N->getOperand(1));
12453 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12454 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12455 // BFS traverse all OR'd operands.
12456 if (I->getOpcode() == ISD::OR) {
12457 Opnds.push_back(I->getOperand(0));
12458 Opnds.push_back(I->getOperand(1));
12459 // Re-evaluate the number of nodes to be traversed.
12460 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12464 // Quit if a non-EXTRACT_VECTOR_ELT
12465 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12468 // Quit if without a constant index.
12469 SDValue Idx = I->getOperand(1);
12470 if (!isa<ConstantSDNode>(Idx))
12473 SDValue ExtractedFromVec = I->getOperand(0);
12474 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12475 if (M == VecInMap.end()) {
12476 VT = ExtractedFromVec.getValueType();
12477 // Quit if not 128/256-bit vector.
12478 if (!VT.is128BitVector() && !VT.is256BitVector())
12480 // Quit if not the same type.
12481 if (VecInMap.begin() != VecInMap.end() &&
12482 VT != VecInMap.begin()->first.getValueType())
12484 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12485 VecIns.push_back(ExtractedFromVec);
12487 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12490 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12491 "Not extracted from 128-/256-bit vector.");
12493 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12495 for (DenseMap<SDValue, unsigned>::const_iterator
12496 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12497 // Quit if not all elements are used.
12498 if (I->second != FullMask)
12502 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12504 // Cast all vectors into TestVT for PTEST.
12505 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12506 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12508 // If more than one full vectors are evaluated, OR them first before PTEST.
12509 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12510 // Each iteration will OR 2 nodes and append the result until there is only
12511 // 1 node left, i.e. the final OR'd value of all vectors.
12512 SDValue LHS = VecIns[Slot];
12513 SDValue RHS = VecIns[Slot + 1];
12514 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12517 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12518 VecIns.back(), VecIns.back());
12521 /// \brief return true if \c Op has a use that doesn't just read flags.
12522 static bool hasNonFlagsUse(SDValue Op) {
12523 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12525 SDNode *User = *UI;
12526 unsigned UOpNo = UI.getOperandNo();
12527 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12528 // Look pass truncate.
12529 UOpNo = User->use_begin().getOperandNo();
12530 User = *User->use_begin();
12533 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12534 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12540 /// Emit nodes that will be selected as "test Op0,Op0", or something
12542 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12543 SelectionDAG &DAG) const {
12544 if (Op.getValueType() == MVT::i1) {
12545 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12546 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12547 DAG.getConstant(0, dl, MVT::i8));
12549 // CF and OF aren't always set the way we want. Determine which
12550 // of these we need.
12551 bool NeedCF = false;
12552 bool NeedOF = false;
12555 case X86::COND_A: case X86::COND_AE:
12556 case X86::COND_B: case X86::COND_BE:
12559 case X86::COND_G: case X86::COND_GE:
12560 case X86::COND_L: case X86::COND_LE:
12561 case X86::COND_O: case X86::COND_NO: {
12562 // Check if we really need to set the
12563 // Overflow flag. If NoSignedWrap is present
12564 // that is not actually needed.
12565 switch (Op->getOpcode()) {
12570 const BinaryWithFlagsSDNode *BinNode =
12571 cast<BinaryWithFlagsSDNode>(Op.getNode());
12572 if (BinNode->Flags.hasNoSignedWrap())
12582 // See if we can use the EFLAGS value from the operand instead of
12583 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12584 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12585 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12586 // Emit a CMP with 0, which is the TEST pattern.
12587 //if (Op.getValueType() == MVT::i1)
12588 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12589 // DAG.getConstant(0, MVT::i1));
12590 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12591 DAG.getConstant(0, dl, Op.getValueType()));
12593 unsigned Opcode = 0;
12594 unsigned NumOperands = 0;
12596 // Truncate operations may prevent the merge of the SETCC instruction
12597 // and the arithmetic instruction before it. Attempt to truncate the operands
12598 // of the arithmetic instruction and use a reduced bit-width instruction.
12599 bool NeedTruncation = false;
12600 SDValue ArithOp = Op;
12601 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12602 SDValue Arith = Op->getOperand(0);
12603 // Both the trunc and the arithmetic op need to have one user each.
12604 if (Arith->hasOneUse())
12605 switch (Arith.getOpcode()) {
12612 NeedTruncation = true;
12618 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12619 // which may be the result of a CAST. We use the variable 'Op', which is the
12620 // non-casted variable when we check for possible users.
12621 switch (ArithOp.getOpcode()) {
12623 // Due to an isel shortcoming, be conservative if this add is likely to be
12624 // selected as part of a load-modify-store instruction. When the root node
12625 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12626 // uses of other nodes in the match, such as the ADD in this case. This
12627 // leads to the ADD being left around and reselected, with the result being
12628 // two adds in the output. Alas, even if none our users are stores, that
12629 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12630 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12631 // climbing the DAG back to the root, and it doesn't seem to be worth the
12633 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12634 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12635 if (UI->getOpcode() != ISD::CopyToReg &&
12636 UI->getOpcode() != ISD::SETCC &&
12637 UI->getOpcode() != ISD::STORE)
12640 if (ConstantSDNode *C =
12641 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12642 // An add of one will be selected as an INC.
12643 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12644 Opcode = X86ISD::INC;
12649 // An add of negative one (subtract of one) will be selected as a DEC.
12650 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12651 Opcode = X86ISD::DEC;
12657 // Otherwise use a regular EFLAGS-setting add.
12658 Opcode = X86ISD::ADD;
12663 // If we have a constant logical shift that's only used in a comparison
12664 // against zero turn it into an equivalent AND. This allows turning it into
12665 // a TEST instruction later.
12666 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12667 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12668 EVT VT = Op.getValueType();
12669 unsigned BitWidth = VT.getSizeInBits();
12670 unsigned ShAmt = Op->getConstantOperandVal(1);
12671 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12673 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12674 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12675 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12676 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12678 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12679 DAG.getConstant(Mask, dl, VT));
12680 DAG.ReplaceAllUsesWith(Op, New);
12686 // If the primary and result isn't used, don't bother using X86ISD::AND,
12687 // because a TEST instruction will be better.
12688 if (!hasNonFlagsUse(Op))
12694 // Due to the ISEL shortcoming noted above, be conservative if this op is
12695 // likely to be selected as part of a load-modify-store instruction.
12696 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12697 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12698 if (UI->getOpcode() == ISD::STORE)
12701 // Otherwise use a regular EFLAGS-setting instruction.
12702 switch (ArithOp.getOpcode()) {
12703 default: llvm_unreachable("unexpected operator!");
12704 case ISD::SUB: Opcode = X86ISD::SUB; break;
12705 case ISD::XOR: Opcode = X86ISD::XOR; break;
12706 case ISD::AND: Opcode = X86ISD::AND; break;
12708 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12709 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12710 if (EFLAGS.getNode())
12713 Opcode = X86ISD::OR;
12727 return SDValue(Op.getNode(), 1);
12733 // If we found that truncation is beneficial, perform the truncation and
12735 if (NeedTruncation) {
12736 EVT VT = Op.getValueType();
12737 SDValue WideVal = Op->getOperand(0);
12738 EVT WideVT = WideVal.getValueType();
12739 unsigned ConvertedOp = 0;
12740 // Use a target machine opcode to prevent further DAGCombine
12741 // optimizations that may separate the arithmetic operations
12742 // from the setcc node.
12743 switch (WideVal.getOpcode()) {
12745 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12746 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12747 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12748 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12749 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12753 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12754 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12755 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12756 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12757 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12763 // Emit a CMP with 0, which is the TEST pattern.
12764 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12765 DAG.getConstant(0, dl, Op.getValueType()));
12767 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12768 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12770 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12771 DAG.ReplaceAllUsesWith(Op, New);
12772 return SDValue(New.getNode(), 1);
12775 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12777 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12778 SDLoc dl, SelectionDAG &DAG) const {
12779 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12780 if (C->getAPIntValue() == 0)
12781 return EmitTest(Op0, X86CC, dl, DAG);
12783 if (Op0.getValueType() == MVT::i1)
12784 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12787 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12788 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12789 // Do the comparison at i32 if it's smaller, besides the Atom case.
12790 // This avoids subregister aliasing issues. Keep the smaller reference
12791 // if we're optimizing for size, however, as that'll allow better folding
12792 // of memory operations.
12793 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12794 !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12795 Attribute::MinSize) &&
12796 !Subtarget->isAtom()) {
12797 unsigned ExtendOp =
12798 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12799 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12800 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12802 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12803 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12804 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12806 return SDValue(Sub.getNode(), 1);
12808 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12811 /// Convert a comparison if required by the subtarget.
12812 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12813 SelectionDAG &DAG) const {
12814 // If the subtarget does not support the FUCOMI instruction, floating-point
12815 // comparisons have to be converted.
12816 if (Subtarget->hasCMov() ||
12817 Cmp.getOpcode() != X86ISD::CMP ||
12818 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12819 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12822 // The instruction selector will select an FUCOM instruction instead of
12823 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12824 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12825 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12827 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12828 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12829 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12830 DAG.getConstant(8, dl, MVT::i8));
12831 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12832 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12835 /// The minimum architected relative accuracy is 2^-12. We need one
12836 /// Newton-Raphson step to have a good float result (24 bits of precision).
12837 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12838 DAGCombinerInfo &DCI,
12839 unsigned &RefinementSteps,
12840 bool &UseOneConstNR) const {
12841 // FIXME: We should use instruction latency models to calculate the cost of
12842 // each potential sequence, but this is very hard to do reliably because
12843 // at least Intel's Core* chips have variable timing based on the number of
12844 // significant digits in the divisor and/or sqrt operand.
12845 if (!Subtarget->useSqrtEst())
12848 EVT VT = Op.getValueType();
12850 // SSE1 has rsqrtss and rsqrtps.
12851 // TODO: Add support for AVX512 (v16f32).
12852 // It is likely not profitable to do this for f64 because a double-precision
12853 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12854 // instructions: convert to single, rsqrtss, convert back to double, refine
12855 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12856 // along with FMA, this could be a throughput win.
12857 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12858 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12859 RefinementSteps = 1;
12860 UseOneConstNR = false;
12861 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
12866 /// The minimum architected relative accuracy is 2^-12. We need one
12867 /// Newton-Raphson step to have a good float result (24 bits of precision).
12868 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
12869 DAGCombinerInfo &DCI,
12870 unsigned &RefinementSteps) const {
12871 // FIXME: We should use instruction latency models to calculate the cost of
12872 // each potential sequence, but this is very hard to do reliably because
12873 // at least Intel's Core* chips have variable timing based on the number of
12874 // significant digits in the divisor.
12875 if (!Subtarget->useReciprocalEst())
12878 EVT VT = Op.getValueType();
12880 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
12881 // TODO: Add support for AVX512 (v16f32).
12882 // It is likely not profitable to do this for f64 because a double-precision
12883 // reciprocal estimate with refinement on x86 prior to FMA requires
12884 // 15 instructions: convert to single, rcpss, convert back to double, refine
12885 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
12886 // along with FMA, this could be a throughput win.
12887 if ((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
12888 (Subtarget->hasAVX() && VT == MVT::v8f32)) {
12889 RefinementSteps = ReciprocalEstimateRefinementSteps;
12890 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
12895 /// If we have at least two divisions that use the same divisor, convert to
12896 /// multplication by a reciprocal. This may need to be adjusted for a given
12897 /// CPU if a division's cost is not at least twice the cost of a multiplication.
12898 /// This is because we still need one division to calculate the reciprocal and
12899 /// then we need two multiplies by that reciprocal as replacements for the
12900 /// original divisions.
12901 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
12902 return NumUsers > 1;
12905 static bool isAllOnes(SDValue V) {
12906 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12907 return C && C->isAllOnesValue();
12910 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12911 /// if it's possible.
12912 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12913 SDLoc dl, SelectionDAG &DAG) const {
12914 SDValue Op0 = And.getOperand(0);
12915 SDValue Op1 = And.getOperand(1);
12916 if (Op0.getOpcode() == ISD::TRUNCATE)
12917 Op0 = Op0.getOperand(0);
12918 if (Op1.getOpcode() == ISD::TRUNCATE)
12919 Op1 = Op1.getOperand(0);
12922 if (Op1.getOpcode() == ISD::SHL)
12923 std::swap(Op0, Op1);
12924 if (Op0.getOpcode() == ISD::SHL) {
12925 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12926 if (And00C->getZExtValue() == 1) {
12927 // If we looked past a truncate, check that it's only truncating away
12929 unsigned BitWidth = Op0.getValueSizeInBits();
12930 unsigned AndBitWidth = And.getValueSizeInBits();
12931 if (BitWidth > AndBitWidth) {
12933 DAG.computeKnownBits(Op0, Zeros, Ones);
12934 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12938 RHS = Op0.getOperand(1);
12940 } else if (Op1.getOpcode() == ISD::Constant) {
12941 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12942 uint64_t AndRHSVal = AndRHS->getZExtValue();
12943 SDValue AndLHS = Op0;
12945 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12946 LHS = AndLHS.getOperand(0);
12947 RHS = AndLHS.getOperand(1);
12950 // Use BT if the immediate can't be encoded in a TEST instruction.
12951 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12953 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
12957 if (LHS.getNode()) {
12958 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12959 // instruction. Since the shift amount is in-range-or-undefined, we know
12960 // that doing a bittest on the i32 value is ok. We extend to i32 because
12961 // the encoding for the i16 version is larger than the i32 version.
12962 // Also promote i16 to i32 for performance / code size reason.
12963 if (LHS.getValueType() == MVT::i8 ||
12964 LHS.getValueType() == MVT::i16)
12965 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12967 // If the operand types disagree, extend the shift amount to match. Since
12968 // BT ignores high bits (like shifts) we can use anyextend.
12969 if (LHS.getValueType() != RHS.getValueType())
12970 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12972 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12973 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12974 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12975 DAG.getConstant(Cond, dl, MVT::i8), BT);
12981 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12983 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12988 // SSE Condition code mapping:
12997 switch (SetCCOpcode) {
12998 default: llvm_unreachable("Unexpected SETCC condition");
13000 case ISD::SETEQ: SSECC = 0; break;
13002 case ISD::SETGT: Swap = true; // Fallthrough
13004 case ISD::SETOLT: SSECC = 1; break;
13006 case ISD::SETGE: Swap = true; // Fallthrough
13008 case ISD::SETOLE: SSECC = 2; break;
13009 case ISD::SETUO: SSECC = 3; break;
13011 case ISD::SETNE: SSECC = 4; break;
13012 case ISD::SETULE: Swap = true; // Fallthrough
13013 case ISD::SETUGE: SSECC = 5; break;
13014 case ISD::SETULT: Swap = true; // Fallthrough
13015 case ISD::SETUGT: SSECC = 6; break;
13016 case ISD::SETO: SSECC = 7; break;
13018 case ISD::SETONE: SSECC = 8; break;
13021 std::swap(Op0, Op1);
13026 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13027 // ones, and then concatenate the result back.
13028 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13029 MVT VT = Op.getSimpleValueType();
13031 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13032 "Unsupported value type for operation");
13034 unsigned NumElems = VT.getVectorNumElements();
13036 SDValue CC = Op.getOperand(2);
13038 // Extract the LHS vectors
13039 SDValue LHS = Op.getOperand(0);
13040 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13041 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13043 // Extract the RHS vectors
13044 SDValue RHS = Op.getOperand(1);
13045 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13046 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13048 // Issue the operation on the smaller types and concatenate the result back
13049 MVT EltVT = VT.getVectorElementType();
13050 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13051 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13052 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13053 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13056 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13057 SDValue Op0 = Op.getOperand(0);
13058 SDValue Op1 = Op.getOperand(1);
13059 SDValue CC = Op.getOperand(2);
13060 MVT VT = Op.getSimpleValueType();
13063 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13064 "Unexpected type for boolean compare operation");
13065 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13066 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13067 DAG.getConstant(-1, dl, VT));
13068 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13069 DAG.getConstant(-1, dl, VT));
13070 switch (SetCCOpcode) {
13071 default: llvm_unreachable("Unexpected SETCC condition");
13073 // (x != y) -> ~(x ^ y)
13074 return DAG.getNode(ISD::XOR, dl, VT,
13075 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13076 DAG.getConstant(-1, dl, VT));
13078 // (x == y) -> (x ^ y)
13079 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13082 // (x > y) -> (x & ~y)
13083 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13086 // (x < y) -> (~x & y)
13087 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13090 // (x <= y) -> (~x | y)
13091 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13094 // (x >=y) -> (x | ~y)
13095 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13099 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13100 const X86Subtarget *Subtarget) {
13101 SDValue Op0 = Op.getOperand(0);
13102 SDValue Op1 = Op.getOperand(1);
13103 SDValue CC = Op.getOperand(2);
13104 MVT VT = Op.getSimpleValueType();
13107 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13108 Op.getValueType().getScalarType() == MVT::i1 &&
13109 "Cannot set masked compare for this operation");
13111 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13113 bool Unsigned = false;
13116 switch (SetCCOpcode) {
13117 default: llvm_unreachable("Unexpected SETCC condition");
13118 case ISD::SETNE: SSECC = 4; break;
13119 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13120 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13121 case ISD::SETLT: Swap = true; //fall-through
13122 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13123 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13124 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13125 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13126 case ISD::SETULE: Unsigned = true; //fall-through
13127 case ISD::SETLE: SSECC = 2; break;
13131 std::swap(Op0, Op1);
13133 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13134 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13135 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13136 DAG.getConstant(SSECC, dl, MVT::i8));
13139 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13140 /// operand \p Op1. If non-trivial (for example because it's not constant)
13141 /// return an empty value.
13142 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13144 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13148 MVT VT = Op1.getSimpleValueType();
13149 MVT EVT = VT.getVectorElementType();
13150 unsigned n = VT.getVectorNumElements();
13151 SmallVector<SDValue, 8> ULTOp1;
13153 for (unsigned i = 0; i < n; ++i) {
13154 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13155 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13158 // Avoid underflow.
13159 APInt Val = Elt->getAPIntValue();
13163 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13166 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13169 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13170 SelectionDAG &DAG) {
13171 SDValue Op0 = Op.getOperand(0);
13172 SDValue Op1 = Op.getOperand(1);
13173 SDValue CC = Op.getOperand(2);
13174 MVT VT = Op.getSimpleValueType();
13175 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13176 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13181 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13182 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13185 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13186 unsigned Opc = X86ISD::CMPP;
13187 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13188 assert(VT.getVectorNumElements() <= 16);
13189 Opc = X86ISD::CMPM;
13191 // In the two special cases we can't handle, emit two comparisons.
13194 unsigned CombineOpc;
13195 if (SetCCOpcode == ISD::SETUEQ) {
13196 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13198 assert(SetCCOpcode == ISD::SETONE);
13199 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13202 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13203 DAG.getConstant(CC0, dl, MVT::i8));
13204 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13205 DAG.getConstant(CC1, dl, MVT::i8));
13206 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13208 // Handle all other FP comparisons here.
13209 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13210 DAG.getConstant(SSECC, dl, MVT::i8));
13213 // Break 256-bit integer vector compare into smaller ones.
13214 if (VT.is256BitVector() && !Subtarget->hasInt256())
13215 return Lower256IntVSETCC(Op, DAG);
13217 EVT OpVT = Op1.getValueType();
13218 if (OpVT.getVectorElementType() == MVT::i1)
13219 return LowerBoolVSETCC_AVX512(Op, DAG);
13221 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13222 if (Subtarget->hasAVX512()) {
13223 if (Op1.getValueType().is512BitVector() ||
13224 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13225 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13226 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13228 // In AVX-512 architecture setcc returns mask with i1 elements,
13229 // But there is no compare instruction for i8 and i16 elements in KNL.
13230 // We are not talking about 512-bit operands in this case, these
13231 // types are illegal.
13233 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13234 OpVT.getVectorElementType().getSizeInBits() >= 8))
13235 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13236 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13239 // We are handling one of the integer comparisons here. Since SSE only has
13240 // GT and EQ comparisons for integer, swapping operands and multiple
13241 // operations may be required for some comparisons.
13243 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13244 bool Subus = false;
13246 switch (SetCCOpcode) {
13247 default: llvm_unreachable("Unexpected SETCC condition");
13248 case ISD::SETNE: Invert = true;
13249 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13250 case ISD::SETLT: Swap = true;
13251 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13252 case ISD::SETGE: Swap = true;
13253 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13254 Invert = true; break;
13255 case ISD::SETULT: Swap = true;
13256 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13257 FlipSigns = true; break;
13258 case ISD::SETUGE: Swap = true;
13259 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13260 FlipSigns = true; Invert = true; break;
13263 // Special case: Use min/max operations for SETULE/SETUGE
13264 MVT VET = VT.getVectorElementType();
13266 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13267 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13270 switch (SetCCOpcode) {
13272 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13273 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13276 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13279 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13280 if (!MinMax && hasSubus) {
13281 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13283 // t = psubus Op0, Op1
13284 // pcmpeq t, <0..0>
13285 switch (SetCCOpcode) {
13287 case ISD::SETULT: {
13288 // If the comparison is against a constant we can turn this into a
13289 // setule. With psubus, setule does not require a swap. This is
13290 // beneficial because the constant in the register is no longer
13291 // destructed as the destination so it can be hoisted out of a loop.
13292 // Only do this pre-AVX since vpcmp* is no longer destructive.
13293 if (Subtarget->hasAVX())
13295 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13296 if (ULEOp1.getNode()) {
13298 Subus = true; Invert = false; Swap = false;
13302 // Psubus is better than flip-sign because it requires no inversion.
13303 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13304 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13308 Opc = X86ISD::SUBUS;
13314 std::swap(Op0, Op1);
13316 // Check that the operation in question is available (most are plain SSE2,
13317 // but PCMPGTQ and PCMPEQQ have different requirements).
13318 if (VT == MVT::v2i64) {
13319 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13320 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13322 // First cast everything to the right type.
13323 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13324 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13326 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13327 // bits of the inputs before performing those operations. The lower
13328 // compare is always unsigned.
13331 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13333 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13334 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13335 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13336 Sign, Zero, Sign, Zero);
13338 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13339 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13341 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13342 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13343 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13345 // Create masks for only the low parts/high parts of the 64 bit integers.
13346 static const int MaskHi[] = { 1, 1, 3, 3 };
13347 static const int MaskLo[] = { 0, 0, 2, 2 };
13348 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13349 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13350 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13352 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13353 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13356 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13358 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13361 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13362 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13363 // pcmpeqd + pshufd + pand.
13364 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13366 // First cast everything to the right type.
13367 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13368 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13371 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13373 // Make sure the lower and upper halves are both all-ones.
13374 static const int Mask[] = { 1, 0, 3, 2 };
13375 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13376 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13379 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13381 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13385 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13386 // bits of the inputs before performing those operations.
13388 EVT EltVT = VT.getVectorElementType();
13389 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13391 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13392 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13395 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13397 // If the logical-not of the result is required, perform that now.
13399 Result = DAG.getNOT(dl, Result, VT);
13402 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13405 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13406 getZeroVector(VT, Subtarget, DAG, dl));
13411 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13413 MVT VT = Op.getSimpleValueType();
13415 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13417 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13418 && "SetCC type must be 8-bit or 1-bit integer");
13419 SDValue Op0 = Op.getOperand(0);
13420 SDValue Op1 = Op.getOperand(1);
13422 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13424 // Optimize to BT if possible.
13425 // Lower (X & (1 << N)) == 0 to BT(X, N).
13426 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13427 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13428 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13429 Op1.getOpcode() == ISD::Constant &&
13430 cast<ConstantSDNode>(Op1)->isNullValue() &&
13431 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13432 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13433 if (NewSetCC.getNode()) {
13435 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13440 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13442 if (Op1.getOpcode() == ISD::Constant &&
13443 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13444 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13445 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13447 // If the input is a setcc, then reuse the input setcc or use a new one with
13448 // the inverted condition.
13449 if (Op0.getOpcode() == X86ISD::SETCC) {
13450 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13451 bool Invert = (CC == ISD::SETNE) ^
13452 cast<ConstantSDNode>(Op1)->isNullValue();
13456 CCode = X86::GetOppositeBranchCondition(CCode);
13457 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13458 DAG.getConstant(CCode, dl, MVT::i8),
13459 Op0.getOperand(1));
13461 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13465 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13466 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13467 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13469 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13470 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13473 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13474 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13475 if (X86CC == X86::COND_INVALID)
13478 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13479 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13480 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13481 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13483 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13487 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13488 static bool isX86LogicalCmp(SDValue Op) {
13489 unsigned Opc = Op.getNode()->getOpcode();
13490 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13491 Opc == X86ISD::SAHF)
13493 if (Op.getResNo() == 1 &&
13494 (Opc == X86ISD::ADD ||
13495 Opc == X86ISD::SUB ||
13496 Opc == X86ISD::ADC ||
13497 Opc == X86ISD::SBB ||
13498 Opc == X86ISD::SMUL ||
13499 Opc == X86ISD::UMUL ||
13500 Opc == X86ISD::INC ||
13501 Opc == X86ISD::DEC ||
13502 Opc == X86ISD::OR ||
13503 Opc == X86ISD::XOR ||
13504 Opc == X86ISD::AND))
13507 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13513 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13514 if (V.getOpcode() != ISD::TRUNCATE)
13517 SDValue VOp0 = V.getOperand(0);
13518 unsigned InBits = VOp0.getValueSizeInBits();
13519 unsigned Bits = V.getValueSizeInBits();
13520 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13523 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13524 bool addTest = true;
13525 SDValue Cond = Op.getOperand(0);
13526 SDValue Op1 = Op.getOperand(1);
13527 SDValue Op2 = Op.getOperand(2);
13529 EVT VT = Op1.getValueType();
13532 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13533 // are available or VBLENDV if AVX is available.
13534 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13535 if (Cond.getOpcode() == ISD::SETCC &&
13536 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13537 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13538 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13539 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13540 int SSECC = translateX86FSETCC(
13541 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13544 if (Subtarget->hasAVX512()) {
13545 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13546 DAG.getConstant(SSECC, DL, MVT::i8));
13547 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13550 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13551 DAG.getConstant(SSECC, DL, MVT::i8));
13553 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13554 // of 3 logic instructions for size savings and potentially speed.
13555 // Unfortunately, there is no scalar form of VBLENDV.
13557 // If either operand is a constant, don't try this. We can expect to
13558 // optimize away at least one of the logic instructions later in that
13559 // case, so that sequence would be faster than a variable blend.
13561 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13562 // uses XMM0 as the selection register. That may need just as many
13563 // instructions as the AND/ANDN/OR sequence due to register moves, so
13566 if (Subtarget->hasAVX() &&
13567 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13569 // Convert to vectors, do a VSELECT, and convert back to scalar.
13570 // All of the conversions should be optimized away.
13572 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13573 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13574 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13575 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13577 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13578 VCmp = DAG.getNode(ISD::BITCAST, DL, VCmpVT, VCmp);
13580 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13582 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13583 VSel, DAG.getIntPtrConstant(0, DL));
13585 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13586 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13587 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13591 if (Cond.getOpcode() == ISD::SETCC) {
13592 SDValue NewCond = LowerSETCC(Cond, DAG);
13593 if (NewCond.getNode())
13597 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13598 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13599 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13600 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13601 if (Cond.getOpcode() == X86ISD::SETCC &&
13602 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13603 isZero(Cond.getOperand(1).getOperand(1))) {
13604 SDValue Cmp = Cond.getOperand(1);
13606 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13608 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13609 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13610 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13612 SDValue CmpOp0 = Cmp.getOperand(0);
13613 // Apply further optimizations for special cases
13614 // (select (x != 0), -1, 0) -> neg & sbb
13615 // (select (x == 0), 0, -1) -> neg & sbb
13616 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13617 if (YC->isNullValue() &&
13618 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13619 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13620 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13621 DAG.getConstant(0, DL,
13622 CmpOp0.getValueType()),
13624 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13625 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13626 SDValue(Neg.getNode(), 1));
13630 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13631 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13632 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13634 SDValue Res = // Res = 0 or -1.
13635 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13636 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13638 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13639 Res = DAG.getNOT(DL, Res, Res.getValueType());
13641 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13642 if (!N2C || !N2C->isNullValue())
13643 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13648 // Look past (and (setcc_carry (cmp ...)), 1).
13649 if (Cond.getOpcode() == ISD::AND &&
13650 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13651 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13652 if (C && C->getAPIntValue() == 1)
13653 Cond = Cond.getOperand(0);
13656 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13657 // setting operand in place of the X86ISD::SETCC.
13658 unsigned CondOpcode = Cond.getOpcode();
13659 if (CondOpcode == X86ISD::SETCC ||
13660 CondOpcode == X86ISD::SETCC_CARRY) {
13661 CC = Cond.getOperand(0);
13663 SDValue Cmp = Cond.getOperand(1);
13664 unsigned Opc = Cmp.getOpcode();
13665 MVT VT = Op.getSimpleValueType();
13667 bool IllegalFPCMov = false;
13668 if (VT.isFloatingPoint() && !VT.isVector() &&
13669 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13670 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13672 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13673 Opc == X86ISD::BT) { // FIXME
13677 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13678 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13679 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13680 Cond.getOperand(0).getValueType() != MVT::i8)) {
13681 SDValue LHS = Cond.getOperand(0);
13682 SDValue RHS = Cond.getOperand(1);
13683 unsigned X86Opcode;
13686 switch (CondOpcode) {
13687 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13688 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13689 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13690 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13691 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13692 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13693 default: llvm_unreachable("unexpected overflowing operator");
13695 if (CondOpcode == ISD::UMULO)
13696 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13699 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13701 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13703 if (CondOpcode == ISD::UMULO)
13704 Cond = X86Op.getValue(2);
13706 Cond = X86Op.getValue(1);
13708 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13713 // Look pass the truncate if the high bits are known zero.
13714 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13715 Cond = Cond.getOperand(0);
13717 // We know the result of AND is compared against zero. Try to match
13719 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13720 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13721 if (NewSetCC.getNode()) {
13722 CC = NewSetCC.getOperand(0);
13723 Cond = NewSetCC.getOperand(1);
13730 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13731 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13734 // a < b ? -1 : 0 -> RES = ~setcc_carry
13735 // a < b ? 0 : -1 -> RES = setcc_carry
13736 // a >= b ? -1 : 0 -> RES = setcc_carry
13737 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13738 if (Cond.getOpcode() == X86ISD::SUB) {
13739 Cond = ConvertCmpIfNecessary(Cond, DAG);
13740 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13742 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13743 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13744 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13745 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13747 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13748 return DAG.getNOT(DL, Res, Res.getValueType());
13753 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13754 // widen the cmov and push the truncate through. This avoids introducing a new
13755 // branch during isel and doesn't add any extensions.
13756 if (Op.getValueType() == MVT::i8 &&
13757 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13758 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13759 if (T1.getValueType() == T2.getValueType() &&
13760 // Blacklist CopyFromReg to avoid partial register stalls.
13761 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13762 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13763 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13764 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13768 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13769 // condition is true.
13770 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13771 SDValue Ops[] = { Op2, Op1, CC, Cond };
13772 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13775 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, const X86Subtarget *Subtarget,
13776 SelectionDAG &DAG) {
13777 MVT VT = Op->getSimpleValueType(0);
13778 SDValue In = Op->getOperand(0);
13779 MVT InVT = In.getSimpleValueType();
13780 MVT VTElt = VT.getVectorElementType();
13781 MVT InVTElt = InVT.getVectorElementType();
13785 if ((InVTElt == MVT::i1) &&
13786 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13787 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13789 ((Subtarget->hasBWI() && VT.is512BitVector() &&
13790 VTElt.getSizeInBits() <= 16)) ||
13792 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13793 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13795 ((Subtarget->hasDQI() && VT.is512BitVector() &&
13796 VTElt.getSizeInBits() >= 32))))
13797 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13799 unsigned int NumElts = VT.getVectorNumElements();
13801 if (NumElts != 8 && NumElts != 16)
13804 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13805 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13806 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13807 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13810 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13811 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13813 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13816 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13818 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13819 if (VT.is512BitVector())
13821 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13824 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13825 SelectionDAG &DAG) {
13826 MVT VT = Op->getSimpleValueType(0);
13827 SDValue In = Op->getOperand(0);
13828 MVT InVT = In.getSimpleValueType();
13831 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13832 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
13834 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13835 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13836 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13839 if (Subtarget->hasInt256())
13840 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13842 // Optimize vectors in AVX mode
13843 // Sign extend v8i16 to v8i32 and
13846 // Divide input vector into two parts
13847 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13848 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13849 // concat the vectors to original VT
13851 unsigned NumElems = InVT.getVectorNumElements();
13852 SDValue Undef = DAG.getUNDEF(InVT);
13854 SmallVector<int,8> ShufMask1(NumElems, -1);
13855 for (unsigned i = 0; i != NumElems/2; ++i)
13858 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13860 SmallVector<int,8> ShufMask2(NumElems, -1);
13861 for (unsigned i = 0; i != NumElems/2; ++i)
13862 ShufMask2[i] = i + NumElems/2;
13864 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13866 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13867 VT.getVectorNumElements()/2);
13869 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13870 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13872 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13875 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13876 // may emit an illegal shuffle but the expansion is still better than scalar
13877 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13878 // we'll emit a shuffle and a arithmetic shift.
13879 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
13880 // TODO: It is possible to support ZExt by zeroing the undef values during
13881 // the shuffle phase or after the shuffle.
13882 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13883 SelectionDAG &DAG) {
13884 MVT RegVT = Op.getSimpleValueType();
13885 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13886 assert(RegVT.isInteger() &&
13887 "We only custom lower integer vector sext loads.");
13889 // Nothing useful we can do without SSE2 shuffles.
13890 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13892 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13894 EVT MemVT = Ld->getMemoryVT();
13895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13896 unsigned RegSz = RegVT.getSizeInBits();
13898 ISD::LoadExtType Ext = Ld->getExtensionType();
13900 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13901 && "Only anyext and sext are currently implemented.");
13902 assert(MemVT != RegVT && "Cannot extend to the same type");
13903 assert(MemVT.isVector() && "Must load a vector from memory");
13905 unsigned NumElems = RegVT.getVectorNumElements();
13906 unsigned MemSz = MemVT.getSizeInBits();
13907 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13909 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13910 // The only way in which we have a legal 256-bit vector result but not the
13911 // integer 256-bit operations needed to directly lower a sextload is if we
13912 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13913 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13914 // correctly legalized. We do this late to allow the canonical form of
13915 // sextload to persist throughout the rest of the DAG combiner -- it wants
13916 // to fold together any extensions it can, and so will fuse a sign_extend
13917 // of an sextload into a sextload targeting a wider value.
13919 if (MemSz == 128) {
13920 // Just switch this to a normal load.
13921 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13922 "it must be a legal 128-bit vector "
13924 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13925 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13926 Ld->isInvariant(), Ld->getAlignment());
13928 assert(MemSz < 128 &&
13929 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13930 // Do an sext load to a 128-bit vector type. We want to use the same
13931 // number of elements, but elements half as wide. This will end up being
13932 // recursively lowered by this routine, but will succeed as we definitely
13933 // have all the necessary features if we're using AVX1.
13935 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13936 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13938 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13939 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13940 Ld->isNonTemporal(), Ld->isInvariant(),
13941 Ld->getAlignment());
13944 // Replace chain users with the new chain.
13945 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13946 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13948 // Finally, do a normal sign-extend to the desired register.
13949 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13952 // All sizes must be a power of two.
13953 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13954 "Non-power-of-two elements are not custom lowered!");
13956 // Attempt to load the original value using scalar loads.
13957 // Find the largest scalar type that divides the total loaded size.
13958 MVT SclrLoadTy = MVT::i8;
13959 for (MVT Tp : MVT::integer_valuetypes()) {
13960 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13965 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13966 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13968 SclrLoadTy = MVT::f64;
13970 // Calculate the number of scalar loads that we need to perform
13971 // in order to load our vector from memory.
13972 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13974 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13975 "Can only lower sext loads with a single scalar load!");
13977 unsigned loadRegZize = RegSz;
13978 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13981 // Represent our vector as a sequence of elements which are the
13982 // largest scalar that we can load.
13983 EVT LoadUnitVecVT = EVT::getVectorVT(
13984 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13986 // Represent the data using the same element type that is stored in
13987 // memory. In practice, we ''widen'' MemVT.
13989 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13990 loadRegZize / MemVT.getScalarType().getSizeInBits());
13992 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13993 "Invalid vector type");
13995 // We can't shuffle using an illegal type.
13996 assert(TLI.isTypeLegal(WideVecVT) &&
13997 "We only lower types that form legal widened vector types");
13999 SmallVector<SDValue, 8> Chains;
14000 SDValue Ptr = Ld->getBasePtr();
14001 SDValue Increment =
14002 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14003 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14005 for (unsigned i = 0; i < NumLoads; ++i) {
14006 // Perform a single load.
14007 SDValue ScalarLoad =
14008 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14009 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14010 Ld->getAlignment());
14011 Chains.push_back(ScalarLoad.getValue(1));
14012 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14013 // another round of DAGCombining.
14015 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14017 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14018 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14020 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14023 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14025 // Bitcast the loaded value to a vector of the original element type, in
14026 // the size of the target vector type.
14027 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14028 unsigned SizeRatio = RegSz / MemSz;
14030 if (Ext == ISD::SEXTLOAD) {
14031 // If we have SSE4.1, we can directly emit a VSEXT node.
14032 if (Subtarget->hasSSE41()) {
14033 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14034 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14038 // Otherwise we'll shuffle the small elements in the high bits of the
14039 // larger type and perform an arithmetic shift. If the shift is not legal
14040 // it's better to scalarize.
14041 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14042 "We can't implement a sext load without an arithmetic right shift!");
14044 // Redistribute the loaded elements into the different locations.
14045 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14046 for (unsigned i = 0; i != NumElems; ++i)
14047 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14049 SDValue Shuff = DAG.getVectorShuffle(
14050 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14052 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14054 // Build the arithmetic shift.
14055 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14056 MemVT.getVectorElementType().getSizeInBits();
14058 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14059 DAG.getConstant(Amt, dl, RegVT));
14061 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14065 // Redistribute the loaded elements into the different locations.
14066 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14067 for (unsigned i = 0; i != NumElems; ++i)
14068 ShuffleVec[i * SizeRatio] = i;
14070 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14071 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14073 // Bitcast to the requested type.
14074 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14075 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14079 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14080 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14081 // from the AND / OR.
14082 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14083 Opc = Op.getOpcode();
14084 if (Opc != ISD::OR && Opc != ISD::AND)
14086 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14087 Op.getOperand(0).hasOneUse() &&
14088 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14089 Op.getOperand(1).hasOneUse());
14092 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14093 // 1 and that the SETCC node has a single use.
14094 static bool isXor1OfSetCC(SDValue Op) {
14095 if (Op.getOpcode() != ISD::XOR)
14097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14098 if (N1C && N1C->getAPIntValue() == 1) {
14099 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14100 Op.getOperand(0).hasOneUse();
14105 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14106 bool addTest = true;
14107 SDValue Chain = Op.getOperand(0);
14108 SDValue Cond = Op.getOperand(1);
14109 SDValue Dest = Op.getOperand(2);
14112 bool Inverted = false;
14114 if (Cond.getOpcode() == ISD::SETCC) {
14115 // Check for setcc([su]{add,sub,mul}o == 0).
14116 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14117 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14118 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14119 Cond.getOperand(0).getResNo() == 1 &&
14120 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14121 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14122 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14123 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14124 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14125 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14127 Cond = Cond.getOperand(0);
14129 SDValue NewCond = LowerSETCC(Cond, DAG);
14130 if (NewCond.getNode())
14135 // FIXME: LowerXALUO doesn't handle these!!
14136 else if (Cond.getOpcode() == X86ISD::ADD ||
14137 Cond.getOpcode() == X86ISD::SUB ||
14138 Cond.getOpcode() == X86ISD::SMUL ||
14139 Cond.getOpcode() == X86ISD::UMUL)
14140 Cond = LowerXALUO(Cond, DAG);
14143 // Look pass (and (setcc_carry (cmp ...)), 1).
14144 if (Cond.getOpcode() == ISD::AND &&
14145 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14146 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14147 if (C && C->getAPIntValue() == 1)
14148 Cond = Cond.getOperand(0);
14151 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14152 // setting operand in place of the X86ISD::SETCC.
14153 unsigned CondOpcode = Cond.getOpcode();
14154 if (CondOpcode == X86ISD::SETCC ||
14155 CondOpcode == X86ISD::SETCC_CARRY) {
14156 CC = Cond.getOperand(0);
14158 SDValue Cmp = Cond.getOperand(1);
14159 unsigned Opc = Cmp.getOpcode();
14160 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14161 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14165 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14169 // These can only come from an arithmetic instruction with overflow,
14170 // e.g. SADDO, UADDO.
14171 Cond = Cond.getNode()->getOperand(1);
14177 CondOpcode = Cond.getOpcode();
14178 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14179 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14180 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14181 Cond.getOperand(0).getValueType() != MVT::i8)) {
14182 SDValue LHS = Cond.getOperand(0);
14183 SDValue RHS = Cond.getOperand(1);
14184 unsigned X86Opcode;
14187 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14188 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14190 switch (CondOpcode) {
14191 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14193 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14195 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14198 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14199 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14201 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14203 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14206 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14207 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14208 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14209 default: llvm_unreachable("unexpected overflowing operator");
14212 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14213 if (CondOpcode == ISD::UMULO)
14214 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14217 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14219 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14221 if (CondOpcode == ISD::UMULO)
14222 Cond = X86Op.getValue(2);
14224 Cond = X86Op.getValue(1);
14226 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14230 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14231 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14232 if (CondOpc == ISD::OR) {
14233 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14234 // two branches instead of an explicit OR instruction with a
14236 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14237 isX86LogicalCmp(Cmp)) {
14238 CC = Cond.getOperand(0).getOperand(0);
14239 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14240 Chain, Dest, CC, Cmp);
14241 CC = Cond.getOperand(1).getOperand(0);
14245 } else { // ISD::AND
14246 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14247 // two branches instead of an explicit AND instruction with a
14248 // separate test. However, we only do this if this block doesn't
14249 // have a fall-through edge, because this requires an explicit
14250 // jmp when the condition is false.
14251 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14252 isX86LogicalCmp(Cmp) &&
14253 Op.getNode()->hasOneUse()) {
14254 X86::CondCode CCode =
14255 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14256 CCode = X86::GetOppositeBranchCondition(CCode);
14257 CC = DAG.getConstant(CCode, dl, MVT::i8);
14258 SDNode *User = *Op.getNode()->use_begin();
14259 // Look for an unconditional branch following this conditional branch.
14260 // We need this because we need to reverse the successors in order
14261 // to implement FCMP_OEQ.
14262 if (User->getOpcode() == ISD::BR) {
14263 SDValue FalseBB = User->getOperand(1);
14265 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14266 assert(NewBR == User);
14270 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14271 Chain, Dest, CC, Cmp);
14272 X86::CondCode CCode =
14273 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14274 CCode = X86::GetOppositeBranchCondition(CCode);
14275 CC = DAG.getConstant(CCode, dl, MVT::i8);
14281 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14282 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14283 // It should be transformed during dag combiner except when the condition
14284 // is set by a arithmetics with overflow node.
14285 X86::CondCode CCode =
14286 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14287 CCode = X86::GetOppositeBranchCondition(CCode);
14288 CC = DAG.getConstant(CCode, dl, MVT::i8);
14289 Cond = Cond.getOperand(0).getOperand(1);
14291 } else if (Cond.getOpcode() == ISD::SETCC &&
14292 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14293 // For FCMP_OEQ, we can emit
14294 // two branches instead of an explicit AND instruction with a
14295 // separate test. However, we only do this if this block doesn't
14296 // have a fall-through edge, because this requires an explicit
14297 // jmp when the condition is false.
14298 if (Op.getNode()->hasOneUse()) {
14299 SDNode *User = *Op.getNode()->use_begin();
14300 // Look for an unconditional branch following this conditional branch.
14301 // We need this because we need to reverse the successors in order
14302 // to implement FCMP_OEQ.
14303 if (User->getOpcode() == ISD::BR) {
14304 SDValue FalseBB = User->getOperand(1);
14306 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14307 assert(NewBR == User);
14311 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14312 Cond.getOperand(0), Cond.getOperand(1));
14313 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14314 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14315 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14316 Chain, Dest, CC, Cmp);
14317 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14322 } else if (Cond.getOpcode() == ISD::SETCC &&
14323 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14324 // For FCMP_UNE, we can emit
14325 // two branches instead of an explicit AND instruction with a
14326 // separate test. However, we only do this if this block doesn't
14327 // have a fall-through edge, because this requires an explicit
14328 // jmp when the condition is false.
14329 if (Op.getNode()->hasOneUse()) {
14330 SDNode *User = *Op.getNode()->use_begin();
14331 // Look for an unconditional branch following this conditional branch.
14332 // We need this because we need to reverse the successors in order
14333 // to implement FCMP_UNE.
14334 if (User->getOpcode() == ISD::BR) {
14335 SDValue FalseBB = User->getOperand(1);
14337 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14338 assert(NewBR == User);
14341 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14342 Cond.getOperand(0), Cond.getOperand(1));
14343 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14344 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14345 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14346 Chain, Dest, CC, Cmp);
14347 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14357 // Look pass the truncate if the high bits are known zero.
14358 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14359 Cond = Cond.getOperand(0);
14361 // We know the result of AND is compared against zero. Try to match
14363 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14364 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14365 if (NewSetCC.getNode()) {
14366 CC = NewSetCC.getOperand(0);
14367 Cond = NewSetCC.getOperand(1);
14374 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14375 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14376 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14378 Cond = ConvertCmpIfNecessary(Cond, DAG);
14379 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14380 Chain, Dest, CC, Cond);
14383 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14384 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14385 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14386 // that the guard pages used by the OS virtual memory manager are allocated in
14387 // correct sequence.
14389 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14390 SelectionDAG &DAG) const {
14391 MachineFunction &MF = DAG.getMachineFunction();
14392 bool SplitStack = MF.shouldSplitStack();
14393 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14399 SDNode* Node = Op.getNode();
14401 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14402 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14403 " not tell us which reg is the stack pointer!");
14404 EVT VT = Node->getValueType(0);
14405 SDValue Tmp1 = SDValue(Node, 0);
14406 SDValue Tmp2 = SDValue(Node, 1);
14407 SDValue Tmp3 = Node->getOperand(2);
14408 SDValue Chain = Tmp1.getOperand(0);
14410 // Chain the dynamic stack allocation so that it doesn't modify the stack
14411 // pointer when other instructions are using the stack.
14412 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14415 SDValue Size = Tmp2.getOperand(1);
14416 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14417 Chain = SP.getValue(1);
14418 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14419 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14420 unsigned StackAlign = TFI.getStackAlignment();
14421 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14422 if (Align > StackAlign)
14423 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14424 DAG.getConstant(-(uint64_t)Align, dl, VT));
14425 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14427 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14428 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14431 SDValue Ops[2] = { Tmp1, Tmp2 };
14432 return DAG.getMergeValues(Ops, dl);
14436 SDValue Chain = Op.getOperand(0);
14437 SDValue Size = Op.getOperand(1);
14438 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14439 EVT VT = Op.getNode()->getValueType(0);
14441 bool Is64Bit = Subtarget->is64Bit();
14442 EVT SPTy = getPointerTy();
14445 MachineRegisterInfo &MRI = MF.getRegInfo();
14448 // The 64 bit implementation of segmented stacks needs to clobber both r10
14449 // r11. This makes it impossible to use it along with nested parameters.
14450 const Function *F = MF.getFunction();
14452 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14454 if (I->hasNestAttr())
14455 report_fatal_error("Cannot use segmented stacks with functions that "
14456 "have nested arguments.");
14459 const TargetRegisterClass *AddrRegClass =
14460 getRegClassFor(getPointerTy());
14461 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14462 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14463 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14464 DAG.getRegister(Vreg, SPTy));
14465 SDValue Ops1[2] = { Value, Chain };
14466 return DAG.getMergeValues(Ops1, dl);
14469 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14471 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14472 Flag = Chain.getValue(1);
14473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14475 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14477 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14478 unsigned SPReg = RegInfo->getStackRegister();
14479 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14480 Chain = SP.getValue(1);
14483 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14484 DAG.getConstant(-(uint64_t)Align, dl, VT));
14485 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14488 SDValue Ops1[2] = { SP, Chain };
14489 return DAG.getMergeValues(Ops1, dl);
14493 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14494 MachineFunction &MF = DAG.getMachineFunction();
14495 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14497 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14500 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14501 // vastart just stores the address of the VarArgsFrameIndex slot into the
14502 // memory location argument.
14503 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14505 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14506 MachinePointerInfo(SV), false, false, 0);
14510 // gp_offset (0 - 6 * 8)
14511 // fp_offset (48 - 48 + 8 * 16)
14512 // overflow_arg_area (point to parameters coming in memory).
14514 SmallVector<SDValue, 8> MemOps;
14515 SDValue FIN = Op.getOperand(1);
14517 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14518 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14520 FIN, MachinePointerInfo(SV), false, false, 0);
14521 MemOps.push_back(Store);
14524 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14525 FIN, DAG.getIntPtrConstant(4, DL));
14526 Store = DAG.getStore(Op.getOperand(0), DL,
14527 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14529 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14530 MemOps.push_back(Store);
14532 // Store ptr to overflow_arg_area
14533 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14534 FIN, DAG.getIntPtrConstant(4, DL));
14535 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14537 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14538 MachinePointerInfo(SV, 8),
14540 MemOps.push_back(Store);
14542 // Store ptr to reg_save_area.
14543 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14544 FIN, DAG.getIntPtrConstant(8, DL));
14545 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14547 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14548 MachinePointerInfo(SV, 16), false, false, 0);
14549 MemOps.push_back(Store);
14550 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14554 assert(Subtarget->is64Bit() &&
14555 "LowerVAARG only handles 64-bit va_arg!");
14556 assert((Subtarget->isTargetLinux() ||
14557 Subtarget->isTargetDarwin()) &&
14558 "Unhandled target in LowerVAARG");
14559 assert(Op.getNode()->getNumOperands() == 4);
14560 SDValue Chain = Op.getOperand(0);
14561 SDValue SrcPtr = Op.getOperand(1);
14562 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14563 unsigned Align = Op.getConstantOperandVal(3);
14566 EVT ArgVT = Op.getNode()->getValueType(0);
14567 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14568 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14571 // Decide which area this value should be read from.
14572 // TODO: Implement the AMD64 ABI in its entirety. This simple
14573 // selection mechanism works only for the basic types.
14574 if (ArgVT == MVT::f80) {
14575 llvm_unreachable("va_arg for f80 not yet implemented");
14576 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14577 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14578 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14579 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14581 llvm_unreachable("Unhandled argument type in LowerVAARG");
14584 if (ArgMode == 2) {
14585 // Sanity Check: Make sure using fp_offset makes sense.
14586 assert(!DAG.getTarget().Options.UseSoftFloat &&
14587 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14588 Attribute::NoImplicitFloat)) &&
14589 Subtarget->hasSSE1());
14592 // Insert VAARG_64 node into the DAG
14593 // VAARG_64 returns two values: Variable Argument Address, Chain
14594 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14595 DAG.getConstant(ArgMode, dl, MVT::i8),
14596 DAG.getConstant(Align, dl, MVT::i32)};
14597 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14598 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14599 VTs, InstOps, MVT::i64,
14600 MachinePointerInfo(SV),
14602 /*Volatile=*/false,
14604 /*WriteMem=*/true);
14605 Chain = VAARG.getValue(1);
14607 // Load the next argument and return it
14608 return DAG.getLoad(ArgVT, dl,
14611 MachinePointerInfo(),
14612 false, false, false, 0);
14615 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14616 SelectionDAG &DAG) {
14617 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14618 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14619 SDValue Chain = Op.getOperand(0);
14620 SDValue DstPtr = Op.getOperand(1);
14621 SDValue SrcPtr = Op.getOperand(2);
14622 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14623 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14626 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14627 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14629 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14632 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14633 // amount is a constant. Takes immediate version of shift as input.
14634 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14635 SDValue SrcOp, uint64_t ShiftAmt,
14636 SelectionDAG &DAG) {
14637 MVT ElementType = VT.getVectorElementType();
14639 // Fold this packed shift into its first operand if ShiftAmt is 0.
14643 // Check for ShiftAmt >= element width
14644 if (ShiftAmt >= ElementType.getSizeInBits()) {
14645 if (Opc == X86ISD::VSRAI)
14646 ShiftAmt = ElementType.getSizeInBits() - 1;
14648 return DAG.getConstant(0, dl, VT);
14651 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14652 && "Unknown target vector shift-by-constant node");
14654 // Fold this packed vector shift into a build vector if SrcOp is a
14655 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14656 if (VT == SrcOp.getSimpleValueType() &&
14657 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14658 SmallVector<SDValue, 8> Elts;
14659 unsigned NumElts = SrcOp->getNumOperands();
14660 ConstantSDNode *ND;
14663 default: llvm_unreachable(nullptr);
14664 case X86ISD::VSHLI:
14665 for (unsigned i=0; i!=NumElts; ++i) {
14666 SDValue CurrentOp = SrcOp->getOperand(i);
14667 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14668 Elts.push_back(CurrentOp);
14671 ND = cast<ConstantSDNode>(CurrentOp);
14672 const APInt &C = ND->getAPIntValue();
14673 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14676 case X86ISD::VSRLI:
14677 for (unsigned i=0; i!=NumElts; ++i) {
14678 SDValue CurrentOp = SrcOp->getOperand(i);
14679 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14680 Elts.push_back(CurrentOp);
14683 ND = cast<ConstantSDNode>(CurrentOp);
14684 const APInt &C = ND->getAPIntValue();
14685 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14688 case X86ISD::VSRAI:
14689 for (unsigned i=0; i!=NumElts; ++i) {
14690 SDValue CurrentOp = SrcOp->getOperand(i);
14691 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14692 Elts.push_back(CurrentOp);
14695 ND = cast<ConstantSDNode>(CurrentOp);
14696 const APInt &C = ND->getAPIntValue();
14697 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14702 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14705 return DAG.getNode(Opc, dl, VT, SrcOp,
14706 DAG.getConstant(ShiftAmt, dl, MVT::i8));
14709 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14710 // may or may not be a constant. Takes immediate version of shift as input.
14711 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14712 SDValue SrcOp, SDValue ShAmt,
14713 SelectionDAG &DAG) {
14714 MVT SVT = ShAmt.getSimpleValueType();
14715 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14717 // Catch shift-by-constant.
14718 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14719 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14720 CShAmt->getZExtValue(), DAG);
14722 // Change opcode to non-immediate version
14724 default: llvm_unreachable("Unknown target vector shift node");
14725 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14726 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14727 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14730 const X86Subtarget &Subtarget =
14731 static_cast<const X86Subtarget &>(DAG.getSubtarget());
14732 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14733 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14734 // Let the shuffle legalizer expand this shift amount node.
14735 SDValue Op0 = ShAmt.getOperand(0);
14736 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14737 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14739 // Need to build a vector containing shift amount.
14740 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14741 SmallVector<SDValue, 4> ShOps;
14742 ShOps.push_back(ShAmt);
14743 if (SVT == MVT::i32) {
14744 ShOps.push_back(DAG.getConstant(0, dl, SVT));
14745 ShOps.push_back(DAG.getUNDEF(SVT));
14747 ShOps.push_back(DAG.getUNDEF(SVT));
14749 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14750 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14753 // The return type has to be a 128-bit type with the same element
14754 // type as the input type.
14755 MVT EltVT = VT.getVectorElementType();
14756 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14758 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14759 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14762 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14763 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14764 /// necessary casting for \p Mask when lowering masking intrinsics.
14765 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14766 SDValue PreservedSrc,
14767 const X86Subtarget *Subtarget,
14768 SelectionDAG &DAG) {
14769 EVT VT = Op.getValueType();
14770 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14771 MVT::i1, VT.getVectorNumElements());
14772 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14773 Mask.getValueType().getSizeInBits());
14776 assert(MaskVT.isSimple() && "invalid mask type");
14778 if (isAllOnes(Mask))
14781 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
14782 // are extracted by EXTRACT_SUBVECTOR.
14783 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
14784 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
14785 DAG.getIntPtrConstant(0, dl));
14787 switch (Op.getOpcode()) {
14789 case X86ISD::PCMPEQM:
14790 case X86ISD::PCMPGTM:
14792 case X86ISD::CMPMU:
14793 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
14795 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14796 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14797 return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
14800 /// \brief Creates an SDNode for a predicated scalar operation.
14801 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
14802 /// The mask is comming as MVT::i8 and it should be truncated
14803 /// to MVT::i1 while lowering masking intrinsics.
14804 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
14805 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
14806 /// a scalar instruction.
14807 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
14808 SDValue PreservedSrc,
14809 const X86Subtarget *Subtarget,
14810 SelectionDAG &DAG) {
14811 if (isAllOnes(Mask))
14814 EVT VT = Op.getValueType();
14816 // The mask should be of type MVT::i1
14817 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
14819 if (PreservedSrc.getOpcode() == ISD::UNDEF)
14820 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
14821 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
14824 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14825 SelectionDAG &DAG) {
14827 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14828 EVT VT = Op.getValueType();
14829 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14831 switch(IntrData->Type) {
14832 case INTR_TYPE_1OP:
14833 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14834 case INTR_TYPE_2OP:
14835 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14837 case INTR_TYPE_3OP:
14838 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14839 Op.getOperand(2), Op.getOperand(3));
14840 case INTR_TYPE_1OP_MASK_RM: {
14841 SDValue Src = Op.getOperand(1);
14842 SDValue Src0 = Op.getOperand(2);
14843 SDValue Mask = Op.getOperand(3);
14844 SDValue RoundingMode = Op.getOperand(4);
14845 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
14847 Mask, Src0, Subtarget, DAG);
14849 case INTR_TYPE_SCALAR_MASK_RM: {
14850 SDValue Src1 = Op.getOperand(1);
14851 SDValue Src2 = Op.getOperand(2);
14852 SDValue Src0 = Op.getOperand(3);
14853 SDValue Mask = Op.getOperand(4);
14854 // There are 2 kinds of intrinsics in this group:
14855 // (1) With supress-all-exceptions (sae) - 6 operands
14856 // (2) With rounding mode and sae - 7 operands.
14857 if (Op.getNumOperands() == 6) {
14858 SDValue Sae = Op.getOperand(5);
14859 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14861 Mask, Src0, Subtarget, DAG);
14863 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
14864 SDValue RoundingMode = Op.getOperand(5);
14865 SDValue Sae = Op.getOperand(6);
14866 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
14867 RoundingMode, Sae),
14868 Mask, Src0, Subtarget, DAG);
14870 case INTR_TYPE_2OP_MASK: {
14871 SDValue Src1 = Op.getOperand(1);
14872 SDValue Src2 = Op.getOperand(2);
14873 SDValue PassThru = Op.getOperand(3);
14874 SDValue Mask = Op.getOperand(4);
14875 // We specify 2 possible opcodes for intrinsics with rounding modes.
14876 // First, we check if the intrinsic may have non-default rounding mode,
14877 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14878 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14879 if (IntrWithRoundingModeOpcode != 0) {
14880 SDValue Rnd = Op.getOperand(5);
14881 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
14882 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
14883 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14884 dl, Op.getValueType(),
14886 Mask, PassThru, Subtarget, DAG);
14889 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
14891 Mask, PassThru, Subtarget, DAG);
14893 case FMA_OP_MASK: {
14894 SDValue Src1 = Op.getOperand(1);
14895 SDValue Src2 = Op.getOperand(2);
14896 SDValue Src3 = Op.getOperand(3);
14897 SDValue Mask = Op.getOperand(4);
14898 // We specify 2 possible opcodes for intrinsics with rounding modes.
14899 // First, we check if the intrinsic may have non-default rounding mode,
14900 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14901 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
14902 if (IntrWithRoundingModeOpcode != 0) {
14903 SDValue Rnd = Op.getOperand(5);
14904 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14905 X86::STATIC_ROUNDING::CUR_DIRECTION)
14906 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
14907 dl, Op.getValueType(),
14908 Src1, Src2, Src3, Rnd),
14909 Mask, Src1, Subtarget, DAG);
14911 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
14912 dl, Op.getValueType(),
14914 Mask, Src1, Subtarget, DAG);
14917 case CMP_MASK_CC: {
14918 // Comparison intrinsics with masks.
14919 // Example of transformation:
14920 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
14921 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
14923 // (v8i1 (insert_subvector undef,
14924 // (v2i1 (and (PCMPEQM %a, %b),
14925 // (extract_subvector
14926 // (v8i1 (bitcast %mask)), 0))), 0))))
14927 EVT VT = Op.getOperand(1).getValueType();
14928 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14929 VT.getVectorNumElements());
14930 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
14931 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14932 Mask.getValueType().getSizeInBits());
14934 if (IntrData->Type == CMP_MASK_CC) {
14935 SDValue CC = Op.getOperand(3);
14936 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
14937 // We specify 2 possible opcodes for intrinsics with rounding modes.
14938 // First, we check if the intrinsic may have non-default rounding mode,
14939 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
14940 if (IntrData->Opc1 != 0) {
14941 SDValue Rnd = Op.getOperand(5);
14942 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
14943 X86::STATIC_ROUNDING::CUR_DIRECTION)
14944 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
14945 Op.getOperand(2), CC, Rnd);
14947 //default rounding mode
14949 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14950 Op.getOperand(2), CC);
14953 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
14954 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
14957 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
14958 DAG.getTargetConstant(0, dl,
14961 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
14962 DAG.getUNDEF(BitcastVT), CmpMask,
14963 DAG.getIntPtrConstant(0, dl));
14964 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
14966 case COMI: { // Comparison intrinsics
14967 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14968 SDValue LHS = Op.getOperand(1);
14969 SDValue RHS = Op.getOperand(2);
14970 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
14971 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14972 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14973 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14974 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
14975 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14978 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14979 Op.getOperand(1), Op.getOperand(2), DAG);
14981 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
14982 Op.getSimpleValueType(),
14984 Op.getOperand(2), DAG),
14985 Op.getOperand(4), Op.getOperand(3), Subtarget,
14987 case COMPRESS_EXPAND_IN_REG: {
14988 SDValue Mask = Op.getOperand(3);
14989 SDValue DataToCompress = Op.getOperand(1);
14990 SDValue PassThru = Op.getOperand(2);
14991 if (isAllOnes(Mask)) // return data as is
14992 return Op.getOperand(1);
14993 EVT VT = Op.getValueType();
14994 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14995 VT.getVectorNumElements());
14996 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
14997 Mask.getValueType().getSizeInBits());
14999 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15000 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15001 DAG.getIntPtrConstant(0, dl));
15003 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToCompress,
15007 SDValue Mask = Op.getOperand(3);
15008 EVT VT = Op.getValueType();
15009 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15010 VT.getVectorNumElements());
15011 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15012 Mask.getValueType().getSizeInBits());
15014 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15015 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15016 DAG.getIntPtrConstant(0, dl));
15017 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15026 default: return SDValue(); // Don't custom lower most intrinsics.
15028 case Intrinsic::x86_avx2_permd:
15029 case Intrinsic::x86_avx2_permps:
15030 // Operands intentionally swapped. Mask is last operand to intrinsic,
15031 // but second operand for node/instruction.
15032 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15033 Op.getOperand(2), Op.getOperand(1));
15035 case Intrinsic::x86_avx512_mask_valign_q_512:
15036 case Intrinsic::x86_avx512_mask_valign_d_512:
15037 // Vector source operands are swapped.
15038 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15039 Op.getValueType(), Op.getOperand(2),
15042 Op.getOperand(5), Op.getOperand(4),
15045 // ptest and testp intrinsics. The intrinsic these come from are designed to
15046 // return an integer value, not just an instruction so lower it to the ptest
15047 // or testp pattern and a setcc for the result.
15048 case Intrinsic::x86_sse41_ptestz:
15049 case Intrinsic::x86_sse41_ptestc:
15050 case Intrinsic::x86_sse41_ptestnzc:
15051 case Intrinsic::x86_avx_ptestz_256:
15052 case Intrinsic::x86_avx_ptestc_256:
15053 case Intrinsic::x86_avx_ptestnzc_256:
15054 case Intrinsic::x86_avx_vtestz_ps:
15055 case Intrinsic::x86_avx_vtestc_ps:
15056 case Intrinsic::x86_avx_vtestnzc_ps:
15057 case Intrinsic::x86_avx_vtestz_pd:
15058 case Intrinsic::x86_avx_vtestc_pd:
15059 case Intrinsic::x86_avx_vtestnzc_pd:
15060 case Intrinsic::x86_avx_vtestz_ps_256:
15061 case Intrinsic::x86_avx_vtestc_ps_256:
15062 case Intrinsic::x86_avx_vtestnzc_ps_256:
15063 case Intrinsic::x86_avx_vtestz_pd_256:
15064 case Intrinsic::x86_avx_vtestc_pd_256:
15065 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15066 bool IsTestPacked = false;
15069 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15070 case Intrinsic::x86_avx_vtestz_ps:
15071 case Intrinsic::x86_avx_vtestz_pd:
15072 case Intrinsic::x86_avx_vtestz_ps_256:
15073 case Intrinsic::x86_avx_vtestz_pd_256:
15074 IsTestPacked = true; // Fallthrough
15075 case Intrinsic::x86_sse41_ptestz:
15076 case Intrinsic::x86_avx_ptestz_256:
15078 X86CC = X86::COND_E;
15080 case Intrinsic::x86_avx_vtestc_ps:
15081 case Intrinsic::x86_avx_vtestc_pd:
15082 case Intrinsic::x86_avx_vtestc_ps_256:
15083 case Intrinsic::x86_avx_vtestc_pd_256:
15084 IsTestPacked = true; // Fallthrough
15085 case Intrinsic::x86_sse41_ptestc:
15086 case Intrinsic::x86_avx_ptestc_256:
15088 X86CC = X86::COND_B;
15090 case Intrinsic::x86_avx_vtestnzc_ps:
15091 case Intrinsic::x86_avx_vtestnzc_pd:
15092 case Intrinsic::x86_avx_vtestnzc_ps_256:
15093 case Intrinsic::x86_avx_vtestnzc_pd_256:
15094 IsTestPacked = true; // Fallthrough
15095 case Intrinsic::x86_sse41_ptestnzc:
15096 case Intrinsic::x86_avx_ptestnzc_256:
15098 X86CC = X86::COND_A;
15102 SDValue LHS = Op.getOperand(1);
15103 SDValue RHS = Op.getOperand(2);
15104 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15105 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15106 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15107 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15108 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15110 case Intrinsic::x86_avx512_kortestz_w:
15111 case Intrinsic::x86_avx512_kortestc_w: {
15112 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15113 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15114 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15115 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15116 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15117 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15118 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15121 case Intrinsic::x86_sse42_pcmpistria128:
15122 case Intrinsic::x86_sse42_pcmpestria128:
15123 case Intrinsic::x86_sse42_pcmpistric128:
15124 case Intrinsic::x86_sse42_pcmpestric128:
15125 case Intrinsic::x86_sse42_pcmpistrio128:
15126 case Intrinsic::x86_sse42_pcmpestrio128:
15127 case Intrinsic::x86_sse42_pcmpistris128:
15128 case Intrinsic::x86_sse42_pcmpestris128:
15129 case Intrinsic::x86_sse42_pcmpistriz128:
15130 case Intrinsic::x86_sse42_pcmpestriz128: {
15134 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15135 case Intrinsic::x86_sse42_pcmpistria128:
15136 Opcode = X86ISD::PCMPISTRI;
15137 X86CC = X86::COND_A;
15139 case Intrinsic::x86_sse42_pcmpestria128:
15140 Opcode = X86ISD::PCMPESTRI;
15141 X86CC = X86::COND_A;
15143 case Intrinsic::x86_sse42_pcmpistric128:
15144 Opcode = X86ISD::PCMPISTRI;
15145 X86CC = X86::COND_B;
15147 case Intrinsic::x86_sse42_pcmpestric128:
15148 Opcode = X86ISD::PCMPESTRI;
15149 X86CC = X86::COND_B;
15151 case Intrinsic::x86_sse42_pcmpistrio128:
15152 Opcode = X86ISD::PCMPISTRI;
15153 X86CC = X86::COND_O;
15155 case Intrinsic::x86_sse42_pcmpestrio128:
15156 Opcode = X86ISD::PCMPESTRI;
15157 X86CC = X86::COND_O;
15159 case Intrinsic::x86_sse42_pcmpistris128:
15160 Opcode = X86ISD::PCMPISTRI;
15161 X86CC = X86::COND_S;
15163 case Intrinsic::x86_sse42_pcmpestris128:
15164 Opcode = X86ISD::PCMPESTRI;
15165 X86CC = X86::COND_S;
15167 case Intrinsic::x86_sse42_pcmpistriz128:
15168 Opcode = X86ISD::PCMPISTRI;
15169 X86CC = X86::COND_E;
15171 case Intrinsic::x86_sse42_pcmpestriz128:
15172 Opcode = X86ISD::PCMPESTRI;
15173 X86CC = X86::COND_E;
15176 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15177 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15178 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15179 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15180 DAG.getConstant(X86CC, dl, MVT::i8),
15181 SDValue(PCMP.getNode(), 1));
15182 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15185 case Intrinsic::x86_sse42_pcmpistri128:
15186 case Intrinsic::x86_sse42_pcmpestri128: {
15188 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15189 Opcode = X86ISD::PCMPISTRI;
15191 Opcode = X86ISD::PCMPESTRI;
15193 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15194 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15195 return DAG.getNode(Opcode, dl, VTs, NewOps);
15200 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15201 SDValue Src, SDValue Mask, SDValue Base,
15202 SDValue Index, SDValue ScaleOp, SDValue Chain,
15203 const X86Subtarget * Subtarget) {
15205 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15206 assert(C && "Invalid scale type");
15207 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15208 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15209 Index.getSimpleValueType().getVectorNumElements());
15211 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15213 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15215 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15216 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15217 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15218 SDValue Segment = DAG.getRegister(0, MVT::i32);
15219 if (Src.getOpcode() == ISD::UNDEF)
15220 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15221 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15222 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15223 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15224 return DAG.getMergeValues(RetOps, dl);
15227 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15228 SDValue Src, SDValue Mask, SDValue Base,
15229 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15232 assert(C && "Invalid scale type");
15233 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15234 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15235 SDValue Segment = DAG.getRegister(0, MVT::i32);
15236 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15237 Index.getSimpleValueType().getVectorNumElements());
15239 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15241 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15243 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15244 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15245 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15246 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15247 return SDValue(Res, 1);
15250 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15251 SDValue Mask, SDValue Base, SDValue Index,
15252 SDValue ScaleOp, SDValue Chain) {
15254 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15255 assert(C && "Invalid scale type");
15256 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15257 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15258 SDValue Segment = DAG.getRegister(0, MVT::i32);
15260 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15262 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15264 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15266 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15267 //SDVTList VTs = DAG.getVTList(MVT::Other);
15268 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15269 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15270 return SDValue(Res, 0);
15273 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15274 // read performance monitor counters (x86_rdpmc).
15275 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15276 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15277 SmallVectorImpl<SDValue> &Results) {
15278 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15279 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15282 // The ECX register is used to select the index of the performance counter
15284 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15286 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15288 // Reads the content of a 64-bit performance counter and returns it in the
15289 // registers EDX:EAX.
15290 if (Subtarget->is64Bit()) {
15291 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15292 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15295 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15296 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15299 Chain = HI.getValue(1);
15301 if (Subtarget->is64Bit()) {
15302 // The EAX register is loaded with the low-order 32 bits. The EDX register
15303 // is loaded with the supported high-order bits of the counter.
15304 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15305 DAG.getConstant(32, DL, MVT::i8));
15306 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15307 Results.push_back(Chain);
15311 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15312 SDValue Ops[] = { LO, HI };
15313 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15314 Results.push_back(Pair);
15315 Results.push_back(Chain);
15318 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15319 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15320 // also used to custom lower READCYCLECOUNTER nodes.
15321 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15322 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15323 SmallVectorImpl<SDValue> &Results) {
15324 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15325 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15328 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15329 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15330 // and the EAX register is loaded with the low-order 32 bits.
15331 if (Subtarget->is64Bit()) {
15332 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15333 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15336 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15337 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15340 SDValue Chain = HI.getValue(1);
15342 if (Opcode == X86ISD::RDTSCP_DAG) {
15343 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15345 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15346 // the ECX register. Add 'ecx' explicitly to the chain.
15347 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15349 // Explicitly store the content of ECX at the location passed in input
15350 // to the 'rdtscp' intrinsic.
15351 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15352 MachinePointerInfo(), false, false, 0);
15355 if (Subtarget->is64Bit()) {
15356 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15357 // the EAX register is loaded with the low-order 32 bits.
15358 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15359 DAG.getConstant(32, DL, MVT::i8));
15360 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15361 Results.push_back(Chain);
15365 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15366 SDValue Ops[] = { LO, HI };
15367 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15368 Results.push_back(Pair);
15369 Results.push_back(Chain);
15372 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15373 SelectionDAG &DAG) {
15374 SmallVector<SDValue, 2> Results;
15376 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15378 return DAG.getMergeValues(Results, DL);
15382 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15383 SelectionDAG &DAG) {
15384 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15386 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15391 switch(IntrData->Type) {
15393 llvm_unreachable("Unknown Intrinsic Type");
15397 // Emit the node with the right value type.
15398 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15399 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15401 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15402 // Otherwise return the value from Rand, which is always 0, casted to i32.
15403 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15404 DAG.getConstant(1, dl, Op->getValueType(1)),
15405 DAG.getConstant(X86::COND_B, dl, MVT::i32),
15406 SDValue(Result.getNode(), 1) };
15407 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15408 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15411 // Return { result, isValid, chain }.
15412 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15413 SDValue(Result.getNode(), 2));
15416 //gather(v1, mask, index, base, scale);
15417 SDValue Chain = Op.getOperand(0);
15418 SDValue Src = Op.getOperand(2);
15419 SDValue Base = Op.getOperand(3);
15420 SDValue Index = Op.getOperand(4);
15421 SDValue Mask = Op.getOperand(5);
15422 SDValue Scale = Op.getOperand(6);
15423 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15427 //scatter(base, mask, index, v1, scale);
15428 SDValue Chain = Op.getOperand(0);
15429 SDValue Base = Op.getOperand(2);
15430 SDValue Mask = Op.getOperand(3);
15431 SDValue Index = Op.getOperand(4);
15432 SDValue Src = Op.getOperand(5);
15433 SDValue Scale = Op.getOperand(6);
15434 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15438 SDValue Hint = Op.getOperand(6);
15439 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15440 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15441 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15442 SDValue Chain = Op.getOperand(0);
15443 SDValue Mask = Op.getOperand(2);
15444 SDValue Index = Op.getOperand(3);
15445 SDValue Base = Op.getOperand(4);
15446 SDValue Scale = Op.getOperand(5);
15447 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15449 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15451 SmallVector<SDValue, 2> Results;
15452 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15454 return DAG.getMergeValues(Results, dl);
15456 // Read Performance Monitoring Counters.
15458 SmallVector<SDValue, 2> Results;
15459 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15460 return DAG.getMergeValues(Results, dl);
15462 // XTEST intrinsics.
15464 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15465 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15466 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15467 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15469 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15470 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15471 Ret, SDValue(InTrans.getNode(), 1));
15475 SmallVector<SDValue, 2> Results;
15476 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15477 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15478 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15479 DAG.getConstant(-1, dl, MVT::i8));
15480 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15481 Op.getOperand(4), GenCF.getValue(1));
15482 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15483 Op.getOperand(5), MachinePointerInfo(),
15485 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15486 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15488 Results.push_back(SetCC);
15489 Results.push_back(Store);
15490 return DAG.getMergeValues(Results, dl);
15492 case COMPRESS_TO_MEM: {
15494 SDValue Mask = Op.getOperand(4);
15495 SDValue DataToCompress = Op.getOperand(3);
15496 SDValue Addr = Op.getOperand(2);
15497 SDValue Chain = Op.getOperand(0);
15499 if (isAllOnes(Mask)) // return just a store
15500 return DAG.getStore(Chain, dl, DataToCompress, Addr,
15501 MachinePointerInfo(), false, false, 0);
15503 EVT VT = DataToCompress.getValueType();
15504 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15505 VT.getVectorNumElements());
15506 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15507 Mask.getValueType().getSizeInBits());
15508 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15509 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15510 DAG.getIntPtrConstant(0, dl));
15512 SDValue Compressed = DAG.getNode(IntrData->Opc0, dl, VT, VMask,
15513 DataToCompress, DAG.getUNDEF(VT));
15514 return DAG.getStore(Chain, dl, Compressed, Addr,
15515 MachinePointerInfo(), false, false, 0);
15517 case EXPAND_FROM_MEM: {
15519 SDValue Mask = Op.getOperand(4);
15520 SDValue PathThru = Op.getOperand(3);
15521 SDValue Addr = Op.getOperand(2);
15522 SDValue Chain = Op.getOperand(0);
15523 EVT VT = Op.getValueType();
15525 if (isAllOnes(Mask)) // return just a load
15526 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15528 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15529 VT.getVectorNumElements());
15530 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15531 Mask.getValueType().getSizeInBits());
15532 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15533 DAG.getNode(ISD::BITCAST, dl, BitcastVT, Mask),
15534 DAG.getIntPtrConstant(0, dl));
15536 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15537 false, false, false, 0);
15539 SDValue Results[] = {
15540 DAG.getNode(IntrData->Opc0, dl, VT, VMask, DataToExpand, PathThru),
15542 return DAG.getMergeValues(Results, dl);
15547 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15548 SelectionDAG &DAG) const {
15549 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15550 MFI->setReturnAddressIsTaken(true);
15552 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15555 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15557 EVT PtrVT = getPointerTy();
15560 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15561 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15562 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15563 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15564 DAG.getNode(ISD::ADD, dl, PtrVT,
15565 FrameAddr, Offset),
15566 MachinePointerInfo(), false, false, false, 0);
15569 // Just load the return address.
15570 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15571 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15572 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15575 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15576 MachineFunction &MF = DAG.getMachineFunction();
15577 MachineFrameInfo *MFI = MF.getFrameInfo();
15578 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15579 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15580 EVT VT = Op.getValueType();
15582 MFI->setFrameAddressIsTaken(true);
15584 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15585 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
15586 // is not possible to crawl up the stack without looking at the unwind codes
15588 int FrameAddrIndex = FuncInfo->getFAIndex();
15589 if (!FrameAddrIndex) {
15590 // Set up a frame object for the return address.
15591 unsigned SlotSize = RegInfo->getSlotSize();
15592 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
15593 SlotSize, /*Offset=*/INT64_MIN, /*IsImmutable=*/false);
15594 FuncInfo->setFAIndex(FrameAddrIndex);
15596 return DAG.getFrameIndex(FrameAddrIndex, VT);
15599 unsigned FrameReg =
15600 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15601 SDLoc dl(Op); // FIXME probably not meaningful
15602 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15603 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15604 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15605 "Invalid Frame Register!");
15606 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15608 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15609 MachinePointerInfo(),
15610 false, false, false, 0);
15614 // FIXME? Maybe this could be a TableGen attribute on some registers and
15615 // this table could be generated automatically from RegInfo.
15616 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15618 unsigned Reg = StringSwitch<unsigned>(RegName)
15619 .Case("esp", X86::ESP)
15620 .Case("rsp", X86::RSP)
15624 report_fatal_error("Invalid register name global variable");
15627 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15628 SelectionDAG &DAG) const {
15629 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15630 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
15633 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15634 SDValue Chain = Op.getOperand(0);
15635 SDValue Offset = Op.getOperand(1);
15636 SDValue Handler = Op.getOperand(2);
15639 EVT PtrVT = getPointerTy();
15640 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15641 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15642 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15643 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15644 "Invalid Frame Register!");
15645 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15646 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15648 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15649 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
15651 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15652 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15654 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15656 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15657 DAG.getRegister(StoreAddrReg, PtrVT));
15660 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15661 SelectionDAG &DAG) const {
15663 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15664 DAG.getVTList(MVT::i32, MVT::Other),
15665 Op.getOperand(0), Op.getOperand(1));
15668 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15669 SelectionDAG &DAG) const {
15671 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15672 Op.getOperand(0), Op.getOperand(1));
15675 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15676 return Op.getOperand(0);
15679 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15680 SelectionDAG &DAG) const {
15681 SDValue Root = Op.getOperand(0);
15682 SDValue Trmp = Op.getOperand(1); // trampoline
15683 SDValue FPtr = Op.getOperand(2); // nested function
15684 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15687 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15688 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
15690 if (Subtarget->is64Bit()) {
15691 SDValue OutChains[6];
15693 // Large code-model.
15694 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15695 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15697 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15698 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15700 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15702 // Load the pointer to the nested function into R11.
15703 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15704 SDValue Addr = Trmp;
15705 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15706 Addr, MachinePointerInfo(TrmpAddr),
15709 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15710 DAG.getConstant(2, dl, MVT::i64));
15711 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15712 MachinePointerInfo(TrmpAddr, 2),
15715 // Load the 'nest' parameter value into R10.
15716 // R10 is specified in X86CallingConv.td
15717 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15718 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15719 DAG.getConstant(10, dl, MVT::i64));
15720 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15721 Addr, MachinePointerInfo(TrmpAddr, 10),
15724 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15725 DAG.getConstant(12, dl, MVT::i64));
15726 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15727 MachinePointerInfo(TrmpAddr, 12),
15730 // Jump to the nested function.
15731 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15732 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15733 DAG.getConstant(20, dl, MVT::i64));
15734 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
15735 Addr, MachinePointerInfo(TrmpAddr, 20),
15738 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15739 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15740 DAG.getConstant(22, dl, MVT::i64));
15741 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
15742 Addr, MachinePointerInfo(TrmpAddr, 22),
15745 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15747 const Function *Func =
15748 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15749 CallingConv::ID CC = Func->getCallingConv();
15754 llvm_unreachable("Unsupported calling convention");
15755 case CallingConv::C:
15756 case CallingConv::X86_StdCall: {
15757 // Pass 'nest' parameter in ECX.
15758 // Must be kept in sync with X86CallingConv.td
15759 NestReg = X86::ECX;
15761 // Check that ECX wasn't needed by an 'inreg' parameter.
15762 FunctionType *FTy = Func->getFunctionType();
15763 const AttributeSet &Attrs = Func->getAttributes();
15765 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15766 unsigned InRegCount = 0;
15769 for (FunctionType::param_iterator I = FTy->param_begin(),
15770 E = FTy->param_end(); I != E; ++I, ++Idx)
15771 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15772 // FIXME: should only count parameters that are lowered to integers.
15773 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15775 if (InRegCount > 2) {
15776 report_fatal_error("Nest register in use - reduce number of inreg"
15782 case CallingConv::X86_FastCall:
15783 case CallingConv::X86_ThisCall:
15784 case CallingConv::Fast:
15785 // Pass 'nest' parameter in EAX.
15786 // Must be kept in sync with X86CallingConv.td
15787 NestReg = X86::EAX;
15791 SDValue OutChains[4];
15792 SDValue Addr, Disp;
15794 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15795 DAG.getConstant(10, dl, MVT::i32));
15796 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15798 // This is storing the opcode for MOV32ri.
15799 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15800 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15801 OutChains[0] = DAG.getStore(Root, dl,
15802 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
15803 Trmp, MachinePointerInfo(TrmpAddr),
15806 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15807 DAG.getConstant(1, dl, MVT::i32));
15808 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15809 MachinePointerInfo(TrmpAddr, 1),
15812 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15813 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15814 DAG.getConstant(5, dl, MVT::i32));
15815 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
15816 Addr, MachinePointerInfo(TrmpAddr, 5),
15819 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15820 DAG.getConstant(6, dl, MVT::i32));
15821 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15822 MachinePointerInfo(TrmpAddr, 6),
15825 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15829 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15830 SelectionDAG &DAG) const {
15832 The rounding mode is in bits 11:10 of FPSR, and has the following
15834 00 Round to nearest
15839 FLT_ROUNDS, on the other hand, expects the following:
15846 To perform the conversion, we do:
15847 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15850 MachineFunction &MF = DAG.getMachineFunction();
15851 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15852 unsigned StackAlignment = TFI.getStackAlignment();
15853 MVT VT = Op.getSimpleValueType();
15856 // Save FP Control Word to stack slot
15857 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15858 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15860 MachineMemOperand *MMO =
15861 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15862 MachineMemOperand::MOStore, 2, 2);
15864 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15865 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15866 DAG.getVTList(MVT::Other),
15867 Ops, MVT::i16, MMO);
15869 // Load FP Control Word from stack slot
15870 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15871 MachinePointerInfo(), false, false, false, 0);
15873 // Transform as necessary
15875 DAG.getNode(ISD::SRL, DL, MVT::i16,
15876 DAG.getNode(ISD::AND, DL, MVT::i16,
15877 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
15878 DAG.getConstant(11, DL, MVT::i8));
15880 DAG.getNode(ISD::SRL, DL, MVT::i16,
15881 DAG.getNode(ISD::AND, DL, MVT::i16,
15882 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
15883 DAG.getConstant(9, DL, MVT::i8));
15886 DAG.getNode(ISD::AND, DL, MVT::i16,
15887 DAG.getNode(ISD::ADD, DL, MVT::i16,
15888 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15889 DAG.getConstant(1, DL, MVT::i16)),
15890 DAG.getConstant(3, DL, MVT::i16));
15892 return DAG.getNode((VT.getSizeInBits() < 16 ?
15893 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15896 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15897 MVT VT = Op.getSimpleValueType();
15899 unsigned NumBits = VT.getSizeInBits();
15902 Op = Op.getOperand(0);
15903 if (VT == MVT::i8) {
15904 // Zero extend to i32 since there is not an i8 bsr.
15906 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15909 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15910 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15911 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15913 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15916 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
15917 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15920 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15922 // Finally xor with NumBits-1.
15923 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15924 DAG.getConstant(NumBits - 1, dl, OpVT));
15927 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15931 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15932 MVT VT = Op.getSimpleValueType();
15934 unsigned NumBits = VT.getSizeInBits();
15937 Op = Op.getOperand(0);
15938 if (VT == MVT::i8) {
15939 // Zero extend to i32 since there is not an i8 bsr.
15941 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15944 // Issue a bsr (scan bits in reverse).
15945 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15946 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15948 // And xor with NumBits-1.
15949 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
15950 DAG.getConstant(NumBits - 1, dl, OpVT));
15953 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15957 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15958 MVT VT = Op.getSimpleValueType();
15959 unsigned NumBits = VT.getSizeInBits();
15961 Op = Op.getOperand(0);
15963 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15964 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15965 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15967 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15970 DAG.getConstant(NumBits, dl, VT),
15971 DAG.getConstant(X86::COND_E, dl, MVT::i8),
15974 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15977 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15978 // ones, and then concatenate the result back.
15979 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15980 MVT VT = Op.getSimpleValueType();
15982 assert(VT.is256BitVector() && VT.isInteger() &&
15983 "Unsupported value type for operation");
15985 unsigned NumElems = VT.getVectorNumElements();
15988 // Extract the LHS vectors
15989 SDValue LHS = Op.getOperand(0);
15990 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15991 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15993 // Extract the RHS vectors
15994 SDValue RHS = Op.getOperand(1);
15995 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15996 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15998 MVT EltVT = VT.getVectorElementType();
15999 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16001 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16002 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16003 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16006 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16007 assert(Op.getSimpleValueType().is256BitVector() &&
16008 Op.getSimpleValueType().isInteger() &&
16009 "Only handle AVX 256-bit vector integer operation");
16010 return Lower256IntArith(Op, DAG);
16013 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16014 assert(Op.getSimpleValueType().is256BitVector() &&
16015 Op.getSimpleValueType().isInteger() &&
16016 "Only handle AVX 256-bit vector integer operation");
16017 return Lower256IntArith(Op, DAG);
16020 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16021 SelectionDAG &DAG) {
16023 MVT VT = Op.getSimpleValueType();
16025 // Decompose 256-bit ops into smaller 128-bit ops.
16026 if (VT.is256BitVector() && !Subtarget->hasInt256())
16027 return Lower256IntArith(Op, DAG);
16029 SDValue A = Op.getOperand(0);
16030 SDValue B = Op.getOperand(1);
16032 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16033 // pairs, multiply and truncate.
16034 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16035 if (Subtarget->hasInt256()) {
16036 if (VT == MVT::v32i8) {
16037 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16038 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16039 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16040 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16041 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16042 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16043 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16044 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16045 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16046 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16049 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16050 return DAG.getNode(
16051 ISD::TRUNCATE, dl, VT,
16052 DAG.getNode(ISD::MUL, dl, ExVT,
16053 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16054 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16057 assert(VT == MVT::v16i8 &&
16058 "Pre-AVX2 support only supports v16i8 multiplication");
16059 MVT ExVT = MVT::v8i16;
16061 // Extract the lo parts and sign extend to i16
16063 if (Subtarget->hasSSE41()) {
16064 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16065 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16067 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16068 -1, 4, -1, 5, -1, 6, -1, 7};
16069 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16070 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16071 ALo = DAG.getNode(ISD::BITCAST, dl, ExVT, ALo);
16072 BLo = DAG.getNode(ISD::BITCAST, dl, ExVT, BLo);
16073 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16074 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16077 // Extract the hi parts and sign extend to i16
16079 if (Subtarget->hasSSE41()) {
16080 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16081 -1, -1, -1, -1, -1, -1, -1, -1};
16082 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16083 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16084 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16085 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16087 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16088 -1, 12, -1, 13, -1, 14, -1, 15};
16089 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16090 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16091 AHi = DAG.getNode(ISD::BITCAST, dl, ExVT, AHi);
16092 BHi = DAG.getNode(ISD::BITCAST, dl, ExVT, BHi);
16093 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16094 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16097 // Multiply, mask the lower 8bits of the lo/hi results and pack
16098 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16099 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16100 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16101 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16102 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16105 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16106 if (VT == MVT::v4i32) {
16107 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16108 "Should not custom lower when pmuldq is available!");
16110 // Extract the odd parts.
16111 static const int UnpackMask[] = { 1, -1, 3, -1 };
16112 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16113 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16115 // Multiply the even parts.
16116 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16117 // Now multiply odd parts.
16118 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16120 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16121 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16123 // Merge the two vectors back together with a shuffle. This expands into 2
16125 static const int ShufMask[] = { 0, 4, 2, 6 };
16126 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16129 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16130 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16132 // Ahi = psrlqi(a, 32);
16133 // Bhi = psrlqi(b, 32);
16135 // AloBlo = pmuludq(a, b);
16136 // AloBhi = pmuludq(a, Bhi);
16137 // AhiBlo = pmuludq(Ahi, b);
16139 // AloBhi = psllqi(AloBhi, 32);
16140 // AhiBlo = psllqi(AhiBlo, 32);
16141 // return AloBlo + AloBhi + AhiBlo;
16143 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16144 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16146 // Bit cast to 32-bit vectors for MULUDQ
16147 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16148 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16149 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16150 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16151 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16152 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16154 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16155 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16156 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16158 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16159 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16161 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16162 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16165 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16166 assert(Subtarget->isTargetWin64() && "Unexpected target");
16167 EVT VT = Op.getValueType();
16168 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16169 "Unexpected return type for lowering");
16173 switch (Op->getOpcode()) {
16174 default: llvm_unreachable("Unexpected request for libcall!");
16175 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16176 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16177 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16178 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16179 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16180 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16184 SDValue InChain = DAG.getEntryNode();
16186 TargetLowering::ArgListTy Args;
16187 TargetLowering::ArgListEntry Entry;
16188 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16189 EVT ArgVT = Op->getOperand(i).getValueType();
16190 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16191 "Unexpected argument type for lowering");
16192 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16193 Entry.Node = StackPtr;
16194 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16196 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16197 Entry.Ty = PointerType::get(ArgTy,0);
16198 Entry.isSExt = false;
16199 Entry.isZExt = false;
16200 Args.push_back(Entry);
16203 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16206 TargetLowering::CallLoweringInfo CLI(DAG);
16207 CLI.setDebugLoc(dl).setChain(InChain)
16208 .setCallee(getLibcallCallingConv(LC),
16209 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16210 Callee, std::move(Args), 0)
16211 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16213 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16214 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16217 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16218 SelectionDAG &DAG) {
16219 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16220 EVT VT = Op0.getValueType();
16223 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16224 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16226 // PMULxD operations multiply each even value (starting at 0) of LHS with
16227 // the related value of RHS and produce a widen result.
16228 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16229 // => <2 x i64> <ae|cg>
16231 // In other word, to have all the results, we need to perform two PMULxD:
16232 // 1. one with the even values.
16233 // 2. one with the odd values.
16234 // To achieve #2, with need to place the odd values at an even position.
16236 // Place the odd value at an even position (basically, shift all values 1
16237 // step to the left):
16238 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16239 // <a|b|c|d> => <b|undef|d|undef>
16240 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16241 // <e|f|g|h> => <f|undef|h|undef>
16242 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16244 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16246 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16247 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16249 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16250 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16251 // => <2 x i64> <ae|cg>
16252 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16253 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16254 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16255 // => <2 x i64> <bf|dh>
16256 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16257 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16259 // Shuffle it back into the right order.
16260 SDValue Highs, Lows;
16261 if (VT == MVT::v8i32) {
16262 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16263 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16264 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16265 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16267 const int HighMask[] = {1, 5, 3, 7};
16268 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16269 const int LowMask[] = {0, 4, 2, 6};
16270 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16273 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16274 // unsigned multiply.
16275 if (IsSigned && !Subtarget->hasSSE41()) {
16277 DAG.getConstant(31, dl,
16278 DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16279 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16280 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16281 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16282 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16284 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16285 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16288 // The first result of MUL_LOHI is actually the low value, followed by the
16290 SDValue Ops[] = {Lows, Highs};
16291 return DAG.getMergeValues(Ops, dl);
16294 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16295 const X86Subtarget *Subtarget) {
16296 MVT VT = Op.getSimpleValueType();
16298 SDValue R = Op.getOperand(0);
16299 SDValue Amt = Op.getOperand(1);
16301 // Optimize shl/srl/sra with constant shift amount.
16302 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16303 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16304 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16306 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16307 (Subtarget->hasInt256() &&
16308 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16309 (Subtarget->hasAVX512() &&
16310 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16311 if (Op.getOpcode() == ISD::SHL)
16312 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16314 if (Op.getOpcode() == ISD::SRL)
16315 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16317 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16318 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16322 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16323 unsigned NumElts = VT.getVectorNumElements();
16324 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16326 if (Op.getOpcode() == ISD::SHL) {
16327 // Make a large shift.
16328 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16330 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16331 // Zero out the rightmost bits.
16332 SmallVector<SDValue, 32> V(
16333 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16334 return DAG.getNode(ISD::AND, dl, VT, SHL,
16335 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16337 if (Op.getOpcode() == ISD::SRL) {
16338 // Make a large shift.
16339 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16341 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16342 // Zero out the leftmost bits.
16343 SmallVector<SDValue, 32> V(
16344 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16345 return DAG.getNode(ISD::AND, dl, VT, SRL,
16346 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16348 if (Op.getOpcode() == ISD::SRA) {
16349 if (ShiftAmt == 7) {
16350 // R s>> 7 === R s< 0
16351 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16352 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16355 // R s>> a === ((R u>> a) ^ m) - m
16356 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16357 SmallVector<SDValue, 32> V(NumElts,
16358 DAG.getConstant(128 >> ShiftAmt, dl,
16360 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16361 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16362 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16365 llvm_unreachable("Unknown shift opcode.");
16370 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16371 if (!Subtarget->is64Bit() &&
16372 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16373 Amt.getOpcode() == ISD::BITCAST &&
16374 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16375 Amt = Amt.getOperand(0);
16376 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16377 VT.getVectorNumElements();
16378 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16379 uint64_t ShiftAmt = 0;
16380 for (unsigned i = 0; i != Ratio; ++i) {
16381 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16385 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16387 // Check remaining shift amounts.
16388 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16389 uint64_t ShAmt = 0;
16390 for (unsigned j = 0; j != Ratio; ++j) {
16391 ConstantSDNode *C =
16392 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16396 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16398 if (ShAmt != ShiftAmt)
16401 switch (Op.getOpcode()) {
16403 llvm_unreachable("Unknown shift opcode!");
16405 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16408 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16411 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16419 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16420 const X86Subtarget* Subtarget) {
16421 MVT VT = Op.getSimpleValueType();
16423 SDValue R = Op.getOperand(0);
16424 SDValue Amt = Op.getOperand(1);
16426 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16427 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16428 (Subtarget->hasInt256() &&
16429 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16430 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16431 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16433 EVT EltVT = VT.getVectorElementType();
16435 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16436 // Check if this build_vector node is doing a splat.
16437 // If so, then set BaseShAmt equal to the splat value.
16438 BaseShAmt = BV->getSplatValue();
16439 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16440 BaseShAmt = SDValue();
16442 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16443 Amt = Amt.getOperand(0);
16445 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16446 if (SVN && SVN->isSplat()) {
16447 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16448 SDValue InVec = Amt.getOperand(0);
16449 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16450 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16451 "Unexpected shuffle index found!");
16452 BaseShAmt = InVec.getOperand(SplatIdx);
16453 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16454 if (ConstantSDNode *C =
16455 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16456 if (C->getZExtValue() == SplatIdx)
16457 BaseShAmt = InVec.getOperand(1);
16462 // Avoid introducing an extract element from a shuffle.
16463 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16464 DAG.getIntPtrConstant(SplatIdx, dl));
16468 if (BaseShAmt.getNode()) {
16469 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16470 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16471 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16472 else if (EltVT.bitsLT(MVT::i32))
16473 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16475 switch (Op.getOpcode()) {
16477 llvm_unreachable("Unknown shift opcode!");
16479 switch (VT.SimpleTy) {
16480 default: return SDValue();
16489 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16492 switch (VT.SimpleTy) {
16493 default: return SDValue();
16500 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16503 switch (VT.SimpleTy) {
16504 default: return SDValue();
16513 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16519 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16520 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
16521 Amt.getOpcode() == ISD::BITCAST &&
16522 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16523 Amt = Amt.getOperand(0);
16524 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16525 VT.getVectorNumElements();
16526 std::vector<SDValue> Vals(Ratio);
16527 for (unsigned i = 0; i != Ratio; ++i)
16528 Vals[i] = Amt.getOperand(i);
16529 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16530 for (unsigned j = 0; j != Ratio; ++j)
16531 if (Vals[j] != Amt.getOperand(i + j))
16534 switch (Op.getOpcode()) {
16536 llvm_unreachable("Unknown shift opcode!");
16538 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16540 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16542 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16549 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16550 SelectionDAG &DAG) {
16551 MVT VT = Op.getSimpleValueType();
16553 SDValue R = Op.getOperand(0);
16554 SDValue Amt = Op.getOperand(1);
16556 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16557 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16559 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16562 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16565 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16568 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16569 if (Subtarget->hasInt256()) {
16570 if (Op.getOpcode() == ISD::SRL &&
16571 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16572 VT == MVT::v4i64 || VT == MVT::v8i32))
16574 if (Op.getOpcode() == ISD::SHL &&
16575 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16576 VT == MVT::v4i64 || VT == MVT::v8i32))
16578 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16582 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16583 // shifts per-lane and then shuffle the partial results back together.
16584 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16585 // Splat the shift amounts so the scalar shifts above will catch it.
16586 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16587 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16588 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16589 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16590 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16593 // If possible, lower this packed shift into a vector multiply instead of
16594 // expanding it into a sequence of scalar shifts.
16595 // Do this only if the vector shift count is a constant build_vector.
16596 if (Op.getOpcode() == ISD::SHL &&
16597 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16598 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16599 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16600 SmallVector<SDValue, 8> Elts;
16601 EVT SVT = VT.getScalarType();
16602 unsigned SVTBits = SVT.getSizeInBits();
16603 const APInt &One = APInt(SVTBits, 1);
16604 unsigned NumElems = VT.getVectorNumElements();
16606 for (unsigned i=0; i !=NumElems; ++i) {
16607 SDValue Op = Amt->getOperand(i);
16608 if (Op->getOpcode() == ISD::UNDEF) {
16609 Elts.push_back(Op);
16613 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16614 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16615 uint64_t ShAmt = C.getZExtValue();
16616 if (ShAmt >= SVTBits) {
16617 Elts.push_back(DAG.getUNDEF(SVT));
16620 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
16622 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16623 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16626 // Lower SHL with variable shift amount.
16627 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16628 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
16630 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
16631 DAG.getConstant(0x3f800000U, dl, VT));
16632 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16633 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16634 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16637 // If possible, lower this shift as a sequence of two shifts by
16638 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16640 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16642 // Could be rewritten as:
16643 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16645 // The advantage is that the two shifts from the example would be
16646 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16647 // the vector shift into four scalar shifts plus four pairs of vector
16649 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16650 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16651 unsigned TargetOpcode = X86ISD::MOVSS;
16652 bool CanBeSimplified;
16653 // The splat value for the first packed shift (the 'X' from the example).
16654 SDValue Amt1 = Amt->getOperand(0);
16655 // The splat value for the second packed shift (the 'Y' from the example).
16656 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16657 Amt->getOperand(2);
16659 // See if it is possible to replace this node with a sequence of
16660 // two shifts followed by a MOVSS/MOVSD
16661 if (VT == MVT::v4i32) {
16662 // Check if it is legal to use a MOVSS.
16663 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16664 Amt2 == Amt->getOperand(3);
16665 if (!CanBeSimplified) {
16666 // Otherwise, check if we can still simplify this node using a MOVSD.
16667 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16668 Amt->getOperand(2) == Amt->getOperand(3);
16669 TargetOpcode = X86ISD::MOVSD;
16670 Amt2 = Amt->getOperand(2);
16673 // Do similar checks for the case where the machine value type
16675 CanBeSimplified = Amt1 == Amt->getOperand(1);
16676 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16677 CanBeSimplified = Amt2 == Amt->getOperand(i);
16679 if (!CanBeSimplified) {
16680 TargetOpcode = X86ISD::MOVSD;
16681 CanBeSimplified = true;
16682 Amt2 = Amt->getOperand(4);
16683 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16684 CanBeSimplified = Amt1 == Amt->getOperand(i);
16685 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16686 CanBeSimplified = Amt2 == Amt->getOperand(j);
16690 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16691 isa<ConstantSDNode>(Amt2)) {
16692 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16693 EVT CastVT = MVT::v4i32;
16695 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
16696 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16698 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
16699 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16700 if (TargetOpcode == X86ISD::MOVSD)
16701 CastVT = MVT::v2i64;
16702 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16703 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16704 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16706 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16710 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16711 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
16712 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, dl, VT));
16714 SDValue VSelM = DAG.getConstant(0x80, dl, VT);
16715 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16716 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16718 // r = VSELECT(r, shl(r, 4), a);
16719 SDValue M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(4, dl, VT));
16720 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16723 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16724 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16725 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16727 // r = VSELECT(r, shl(r, 2), a);
16728 M = DAG.getNode(ISD::SHL, dl, VT, R, DAG.getConstant(2, dl, VT));
16729 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16732 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16733 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16734 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16736 // return VSELECT(r, r+r, a);
16737 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16738 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16742 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16743 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16744 // solution better.
16745 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16746 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16748 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16749 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16750 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16751 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16752 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16755 // Decompose 256-bit shifts into smaller 128-bit shifts.
16756 if (VT.is256BitVector()) {
16757 unsigned NumElems = VT.getVectorNumElements();
16758 MVT EltVT = VT.getVectorElementType();
16759 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16761 // Extract the two vectors
16762 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16763 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16765 // Recreate the shift amount vectors
16766 SDValue Amt1, Amt2;
16767 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16768 // Constant shift amount
16769 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
16770 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
16771 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
16773 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16774 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16776 // Variable shift amount
16777 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16778 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16781 // Issue new vector shifts for the smaller types
16782 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16783 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16785 // Concatenate the result back
16786 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16792 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16793 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16794 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16795 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16796 // has only one use.
16797 SDNode *N = Op.getNode();
16798 SDValue LHS = N->getOperand(0);
16799 SDValue RHS = N->getOperand(1);
16800 unsigned BaseOp = 0;
16803 switch (Op.getOpcode()) {
16804 default: llvm_unreachable("Unknown ovf instruction!");
16806 // A subtract of one will be selected as a INC. Note that INC doesn't
16807 // set CF, so we can't do this for UADDO.
16808 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16810 BaseOp = X86ISD::INC;
16811 Cond = X86::COND_O;
16814 BaseOp = X86ISD::ADD;
16815 Cond = X86::COND_O;
16818 BaseOp = X86ISD::ADD;
16819 Cond = X86::COND_B;
16822 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16823 // set CF, so we can't do this for USUBO.
16824 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16826 BaseOp = X86ISD::DEC;
16827 Cond = X86::COND_O;
16830 BaseOp = X86ISD::SUB;
16831 Cond = X86::COND_O;
16834 BaseOp = X86ISD::SUB;
16835 Cond = X86::COND_B;
16838 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
16839 Cond = X86::COND_O;
16841 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16842 if (N->getValueType(0) == MVT::i8) {
16843 BaseOp = X86ISD::UMUL8;
16844 Cond = X86::COND_O;
16847 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16849 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16852 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16853 DAG.getConstant(X86::COND_O, DL, MVT::i32),
16854 SDValue(Sum.getNode(), 2));
16856 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16860 // Also sets EFLAGS.
16861 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16862 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16865 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16866 DAG.getConstant(Cond, DL, MVT::i32),
16867 SDValue(Sum.getNode(), 1));
16869 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16872 /// Returns true if the operand type is exactly twice the native width, and
16873 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16874 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16875 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16876 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16877 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16880 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16881 else if (OpWidth == 128)
16882 return Subtarget->hasCmpxchg16b();
16887 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16888 return needsCmpXchgNb(SI->getValueOperand()->getType());
16891 // Note: this turns large loads into lock cmpxchg8b/16b.
16892 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
16893 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16894 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
16895 return needsCmpXchgNb(PTy->getElementType());
16898 TargetLoweringBase::AtomicRMWExpansionKind
16899 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16900 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16901 const Type *MemType = AI->getType();
16903 // If the operand is too big, we must see if cmpxchg8/16b is available
16904 // and default to library calls otherwise.
16905 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
16906 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
16907 : AtomicRMWExpansionKind::None;
16910 AtomicRMWInst::BinOp Op = AI->getOperation();
16913 llvm_unreachable("Unknown atomic operation");
16914 case AtomicRMWInst::Xchg:
16915 case AtomicRMWInst::Add:
16916 case AtomicRMWInst::Sub:
16917 // It's better to use xadd, xsub or xchg for these in all cases.
16918 return AtomicRMWExpansionKind::None;
16919 case AtomicRMWInst::Or:
16920 case AtomicRMWInst::And:
16921 case AtomicRMWInst::Xor:
16922 // If the atomicrmw's result isn't actually used, we can just add a "lock"
16923 // prefix to a normal instruction for these operations.
16924 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
16925 : AtomicRMWExpansionKind::None;
16926 case AtomicRMWInst::Nand:
16927 case AtomicRMWInst::Max:
16928 case AtomicRMWInst::Min:
16929 case AtomicRMWInst::UMax:
16930 case AtomicRMWInst::UMin:
16931 // These always require a non-trivial set of data operations on x86. We must
16932 // use a cmpxchg loop.
16933 return AtomicRMWExpansionKind::CmpXChg;
16937 static bool hasMFENCE(const X86Subtarget& Subtarget) {
16938 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16939 // no-sse2). There isn't any reason to disable it if the target processor
16941 return Subtarget.hasSSE2() || Subtarget.is64Bit();
16945 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16946 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
16947 const Type *MemType = AI->getType();
16948 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
16949 // there is no benefit in turning such RMWs into loads, and it is actually
16950 // harmful as it introduces a mfence.
16951 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16954 auto Builder = IRBuilder<>(AI);
16955 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16956 auto SynchScope = AI->getSynchScope();
16957 // We must restrict the ordering to avoid generating loads with Release or
16958 // ReleaseAcquire orderings.
16959 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
16960 auto Ptr = AI->getPointerOperand();
16962 // Before the load we need a fence. Here is an example lifted from
16963 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
16966 // x.store(1, relaxed);
16967 // r1 = y.fetch_add(0, release);
16969 // y.fetch_add(42, acquire);
16970 // r2 = x.load(relaxed);
16971 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
16972 // lowered to just a load without a fence. A mfence flushes the store buffer,
16973 // making the optimization clearly correct.
16974 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
16975 // otherwise, we might be able to be more agressive on relaxed idempotent
16976 // rmw. In practice, they do not look useful, so we don't try to be
16977 // especially clever.
16978 if (SynchScope == SingleThread) {
16979 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
16980 // the IR level, so we must wrap it in an intrinsic.
16982 } else if (hasMFENCE(*Subtarget)) {
16983 Function *MFence = llvm::Intrinsic::getDeclaration(M,
16984 Intrinsic::x86_sse2_mfence);
16985 Builder.CreateCall(MFence);
16987 // FIXME: it might make sense to use a locked operation here but on a
16988 // different cache-line to prevent cache-line bouncing. In practice it
16989 // is probably a small win, and x86 processors without mfence are rare
16990 // enough that we do not bother.
16994 // Finally we can emit the atomic load.
16995 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
16996 AI->getType()->getPrimitiveSizeInBits());
16997 Loaded->setAtomic(Order, SynchScope);
16998 AI->replaceAllUsesWith(Loaded);
16999 AI->eraseFromParent();
17003 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17004 SelectionDAG &DAG) {
17006 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17007 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17008 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17009 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17011 // The only fence that needs an instruction is a sequentially-consistent
17012 // cross-thread fence.
17013 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17014 if (hasMFENCE(*Subtarget))
17015 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17017 SDValue Chain = Op.getOperand(0);
17018 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17020 DAG.getRegister(X86::ESP, MVT::i32), // Base
17021 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
17022 DAG.getRegister(0, MVT::i32), // Index
17023 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
17024 DAG.getRegister(0, MVT::i32), // Segment.
17028 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17029 return SDValue(Res, 0);
17032 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17033 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17036 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17037 SelectionDAG &DAG) {
17038 MVT T = Op.getSimpleValueType();
17042 switch(T.SimpleTy) {
17043 default: llvm_unreachable("Invalid value type!");
17044 case MVT::i8: Reg = X86::AL; size = 1; break;
17045 case MVT::i16: Reg = X86::AX; size = 2; break;
17046 case MVT::i32: Reg = X86::EAX; size = 4; break;
17048 assert(Subtarget->is64Bit() && "Node not type legal!");
17049 Reg = X86::RAX; size = 8;
17052 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17053 Op.getOperand(2), SDValue());
17054 SDValue Ops[] = { cpIn.getValue(0),
17057 DAG.getTargetConstant(size, DL, MVT::i8),
17058 cpIn.getValue(1) };
17059 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17060 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17061 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17065 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17066 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17067 MVT::i32, cpOut.getValue(2));
17068 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17069 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17072 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17073 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17074 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17078 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17079 SelectionDAG &DAG) {
17080 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17081 MVT DstVT = Op.getSimpleValueType();
17083 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17084 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17085 if (DstVT != MVT::f64)
17086 // This conversion needs to be expanded.
17089 SDValue InVec = Op->getOperand(0);
17091 unsigned NumElts = SrcVT.getVectorNumElements();
17092 EVT SVT = SrcVT.getVectorElementType();
17094 // Widen the vector in input in the case of MVT::v2i32.
17095 // Example: from MVT::v2i32 to MVT::v4i32.
17096 SmallVector<SDValue, 16> Elts;
17097 for (unsigned i = 0, e = NumElts; i != e; ++i)
17098 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17099 DAG.getIntPtrConstant(i, dl)));
17101 // Explicitly mark the extra elements as Undef.
17102 Elts.append(NumElts, DAG.getUNDEF(SVT));
17104 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17105 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17106 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17107 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17108 DAG.getIntPtrConstant(0, dl));
17111 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17112 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17113 assert((DstVT == MVT::i64 ||
17114 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17115 "Unexpected custom BITCAST");
17116 // i64 <=> MMX conversions are Legal.
17117 if (SrcVT==MVT::i64 && DstVT.isVector())
17119 if (DstVT==MVT::i64 && SrcVT.isVector())
17121 // MMX <=> MMX conversions are Legal.
17122 if (SrcVT.isVector() && DstVT.isVector())
17124 // All other conversions need to be expanded.
17128 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17129 SelectionDAG &DAG) {
17130 SDNode *Node = Op.getNode();
17133 Op = Op.getOperand(0);
17134 EVT VT = Op.getValueType();
17135 assert((VT.is128BitVector() || VT.is256BitVector()) &&
17136 "CTPOP lowering only implemented for 128/256-bit wide vector types");
17138 unsigned NumElts = VT.getVectorNumElements();
17139 EVT EltVT = VT.getVectorElementType();
17140 unsigned Len = EltVT.getSizeInBits();
17142 // This is the vectorized version of the "best" algorithm from
17143 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17144 // with a minor tweak to use a series of adds + shifts instead of vector
17145 // multiplications. Implemented for the v2i64, v4i64, v4i32, v8i32 types:
17147 // v2i64, v4i64, v4i32 => Only profitable w/ popcnt disabled
17148 // v8i32 => Always profitable
17150 // FIXME: There a couple of possible improvements:
17152 // 1) Support for i8 and i16 vectors (needs measurements if popcnt enabled).
17153 // 2) Use strategies from http://wm.ite.pl/articles/sse-popcount.html
17155 assert(EltVT.isInteger() && (Len == 32 || Len == 64) && Len % 8 == 0 &&
17156 "CTPOP not implemented for this vector element type.");
17158 // X86 canonicalize ANDs to vXi64, generate the appropriate bitcasts to avoid
17159 // extra legalization.
17160 bool NeedsBitcast = EltVT == MVT::i32;
17161 MVT BitcastVT = VT.is256BitVector() ? MVT::v4i64 : MVT::v2i64;
17163 SDValue Cst55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl,
17165 SDValue Cst33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl,
17167 SDValue Cst0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl,
17170 // v = v - ((v >> 1) & 0x55555555...)
17171 SmallVector<SDValue, 8> Ones(NumElts, DAG.getConstant(1, dl, EltVT));
17172 SDValue OnesV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ones);
17173 SDValue Srl = DAG.getNode(ISD::SRL, dl, VT, Op, OnesV);
17175 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17177 SmallVector<SDValue, 8> Mask55(NumElts, Cst55);
17178 SDValue M55 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask55);
17180 M55 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M55);
17182 SDValue And = DAG.getNode(ISD::AND, dl, Srl.getValueType(), Srl, M55);
17183 if (VT != And.getValueType())
17184 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17185 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Op, And);
17187 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17188 SmallVector<SDValue, 8> Mask33(NumElts, Cst33);
17189 SDValue M33 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask33);
17190 SmallVector<SDValue, 8> Twos(NumElts, DAG.getConstant(2, dl, EltVT));
17191 SDValue TwosV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Twos);
17193 Srl = DAG.getNode(ISD::SRL, dl, VT, Sub, TwosV);
17194 if (NeedsBitcast) {
17195 Srl = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Srl);
17196 M33 = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M33);
17197 Sub = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Sub);
17200 SDValue AndRHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Srl, M33);
17201 SDValue AndLHS = DAG.getNode(ISD::AND, dl, M33.getValueType(), Sub, M33);
17202 if (VT != AndRHS.getValueType()) {
17203 AndRHS = DAG.getNode(ISD::BITCAST, dl, VT, AndRHS);
17204 AndLHS = DAG.getNode(ISD::BITCAST, dl, VT, AndLHS);
17206 SDValue Add = DAG.getNode(ISD::ADD, dl, VT, AndLHS, AndRHS);
17208 // v = (v + (v >> 4)) & 0x0F0F0F0F...
17209 SmallVector<SDValue, 8> Fours(NumElts, DAG.getConstant(4, dl, EltVT));
17210 SDValue FoursV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Fours);
17211 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, FoursV);
17212 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17214 SmallVector<SDValue, 8> Mask0F(NumElts, Cst0F);
17215 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Mask0F);
17216 if (NeedsBitcast) {
17217 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17218 M0F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M0F);
17220 And = DAG.getNode(ISD::AND, dl, M0F.getValueType(), Add, M0F);
17221 if (VT != And.getValueType())
17222 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17224 // The algorithm mentioned above uses:
17225 // v = (v * 0x01010101...) >> (Len - 8)
17227 // Change it to use vector adds + vector shifts which yield faster results on
17228 // Haswell than using vector integer multiplication.
17230 // For i32 elements:
17231 // v = v + (v >> 8)
17232 // v = v + (v >> 16)
17234 // For i64 elements:
17235 // v = v + (v >> 8)
17236 // v = v + (v >> 16)
17237 // v = v + (v >> 32)
17240 SmallVector<SDValue, 8> Csts;
17241 for (unsigned i = 8; i <= Len/2; i *= 2) {
17242 Csts.assign(NumElts, DAG.getConstant(i, dl, EltVT));
17243 SDValue CstsV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Csts);
17244 Srl = DAG.getNode(ISD::SRL, dl, VT, Add, CstsV);
17245 Add = DAG.getNode(ISD::ADD, dl, VT, Add, Srl);
17249 // The result is on the least significant 6-bits on i32 and 7-bits on i64.
17250 SDValue Cst3F = DAG.getConstant(APInt(Len, Len == 32 ? 0x3F : 0x7F), dl,
17252 SmallVector<SDValue, 8> Cst3FV(NumElts, Cst3F);
17253 SDValue M3F = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Cst3FV);
17254 if (NeedsBitcast) {
17255 Add = DAG.getNode(ISD::BITCAST, dl, BitcastVT, Add);
17256 M3F = DAG.getNode(ISD::BITCAST, dl, BitcastVT, M3F);
17258 And = DAG.getNode(ISD::AND, dl, M3F.getValueType(), Add, M3F);
17259 if (VT != And.getValueType())
17260 And = DAG.getNode(ISD::BITCAST, dl, VT, And);
17265 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17266 SDNode *Node = Op.getNode();
17268 EVT T = Node->getValueType(0);
17269 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17270 DAG.getConstant(0, dl, T), Node->getOperand(2));
17271 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17272 cast<AtomicSDNode>(Node)->getMemoryVT(),
17273 Node->getOperand(0),
17274 Node->getOperand(1), negOp,
17275 cast<AtomicSDNode>(Node)->getMemOperand(),
17276 cast<AtomicSDNode>(Node)->getOrdering(),
17277 cast<AtomicSDNode>(Node)->getSynchScope());
17280 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17281 SDNode *Node = Op.getNode();
17283 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17285 // Convert seq_cst store -> xchg
17286 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17287 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17288 // (The only way to get a 16-byte store is cmpxchg16b)
17289 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17290 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17291 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17292 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17293 cast<AtomicSDNode>(Node)->getMemoryVT(),
17294 Node->getOperand(0),
17295 Node->getOperand(1), Node->getOperand(2),
17296 cast<AtomicSDNode>(Node)->getMemOperand(),
17297 cast<AtomicSDNode>(Node)->getOrdering(),
17298 cast<AtomicSDNode>(Node)->getSynchScope());
17299 return Swap.getValue(1);
17301 // Other atomic stores have a simple pattern.
17305 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17306 EVT VT = Op.getNode()->getSimpleValueType(0);
17308 // Let legalize expand this if it isn't a legal type yet.
17309 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17312 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17315 bool ExtraOp = false;
17316 switch (Op.getOpcode()) {
17317 default: llvm_unreachable("Invalid code");
17318 case ISD::ADDC: Opc = X86ISD::ADD; break;
17319 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17320 case ISD::SUBC: Opc = X86ISD::SUB; break;
17321 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17325 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17327 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17328 Op.getOperand(1), Op.getOperand(2));
17331 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17332 SelectionDAG &DAG) {
17333 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17335 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17336 // which returns the values as { float, float } (in XMM0) or
17337 // { double, double } (which is returned in XMM0, XMM1).
17339 SDValue Arg = Op.getOperand(0);
17340 EVT ArgVT = Arg.getValueType();
17341 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17343 TargetLowering::ArgListTy Args;
17344 TargetLowering::ArgListEntry Entry;
17348 Entry.isSExt = false;
17349 Entry.isZExt = false;
17350 Args.push_back(Entry);
17352 bool isF64 = ArgVT == MVT::f64;
17353 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17354 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17355 // the results are returned via SRet in memory.
17356 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17358 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17360 Type *RetTy = isF64
17361 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
17362 : (Type*)VectorType::get(ArgTy, 4);
17364 TargetLowering::CallLoweringInfo CLI(DAG);
17365 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17366 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17368 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17371 // Returned in xmm0 and xmm1.
17372 return CallResult.first;
17374 // Returned in bits 0:31 and 32:64 xmm0.
17375 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17376 CallResult.first, DAG.getIntPtrConstant(0, dl));
17377 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17378 CallResult.first, DAG.getIntPtrConstant(1, dl));
17379 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17380 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17383 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
17384 SelectionDAG &DAG) {
17385 assert(Subtarget->hasAVX512() &&
17386 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17388 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
17389 EVT VT = N->getValue().getValueType();
17390 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
17393 // X86 scatter kills mask register, so its type should be added to
17394 // the list of return values
17395 if (N->getNumValues() == 1) {
17396 SDValue Index = N->getIndex();
17397 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17398 !Index.getValueType().is512BitVector())
17399 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17401 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
17402 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17403 N->getOperand(3), Index };
17405 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
17406 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
17407 return SDValue(NewScatter.getNode(), 0);
17412 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
17413 SelectionDAG &DAG) {
17414 assert(Subtarget->hasAVX512() &&
17415 "MGATHER/MSCATTER are supported on AVX-512 arch only");
17417 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
17418 EVT VT = Op.getValueType();
17419 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
17422 SDValue Index = N->getIndex();
17423 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
17424 !Index.getValueType().is512BitVector()) {
17425 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
17426 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
17427 N->getOperand(3), Index };
17428 DAG.UpdateNodeOperands(N, Ops);
17433 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
17434 SelectionDAG &DAG) const {
17435 // TODO: Eventually, the lowering of these nodes should be informed by or
17436 // deferred to the GC strategy for the function in which they appear. For
17437 // now, however, they must be lowered to something. Since they are logically
17438 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17439 // require special handling for these nodes), lower them as literal NOOPs for
17441 SmallVector<SDValue, 2> Ops;
17443 Ops.push_back(Op.getOperand(0));
17444 if (Op->getGluedNode())
17445 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17448 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17449 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17454 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
17455 SelectionDAG &DAG) const {
17456 // TODO: Eventually, the lowering of these nodes should be informed by or
17457 // deferred to the GC strategy for the function in which they appear. For
17458 // now, however, they must be lowered to something. Since they are logically
17459 // no-ops in the case of a null GC strategy (or a GC strategy which does not
17460 // require special handling for these nodes), lower them as literal NOOPs for
17462 SmallVector<SDValue, 2> Ops;
17464 Ops.push_back(Op.getOperand(0));
17465 if (Op->getGluedNode())
17466 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
17469 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
17470 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
17475 /// LowerOperation - Provide custom lowering hooks for some operations.
17477 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17478 switch (Op.getOpcode()) {
17479 default: llvm_unreachable("Should not custom lower this!");
17480 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17481 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17482 return LowerCMP_SWAP(Op, Subtarget, DAG);
17483 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
17484 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17485 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17486 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17487 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
17488 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
17489 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17490 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17491 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17492 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17493 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17494 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17495 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17496 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17497 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17498 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17499 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17500 case ISD::SHL_PARTS:
17501 case ISD::SRA_PARTS:
17502 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17503 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17504 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17505 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17506 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17507 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17508 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17509 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17510 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17511 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17512 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17514 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17515 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17516 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17517 case ISD::SETCC: return LowerSETCC(Op, DAG);
17518 case ISD::SELECT: return LowerSELECT(Op, DAG);
17519 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17520 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17521 case ISD::VASTART: return LowerVASTART(Op, DAG);
17522 case ISD::VAARG: return LowerVAARG(Op, DAG);
17523 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17524 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
17525 case ISD::INTRINSIC_VOID:
17526 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17527 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17528 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17529 case ISD::FRAME_TO_ARGS_OFFSET:
17530 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17531 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17532 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17533 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17534 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17535 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17536 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17537 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17538 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17539 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17540 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17541 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17542 case ISD::UMUL_LOHI:
17543 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17546 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17552 case ISD::UMULO: return LowerXALUO(Op, DAG);
17553 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17554 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17558 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17559 case ISD::ADD: return LowerADD(Op, DAG);
17560 case ISD::SUB: return LowerSUB(Op, DAG);
17561 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17562 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
17563 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
17564 case ISD::GC_TRANSITION_START:
17565 return LowerGC_TRANSITION_START(Op, DAG);
17566 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
17570 /// ReplaceNodeResults - Replace a node with an illegal result type
17571 /// with a new node built out of custom code.
17572 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17573 SmallVectorImpl<SDValue>&Results,
17574 SelectionDAG &DAG) const {
17576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17577 switch (N->getOpcode()) {
17579 llvm_unreachable("Do not know how to custom type legalize this operation!");
17580 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
17581 case X86ISD::FMINC:
17583 case X86ISD::FMAXC:
17584 case X86ISD::FMAX: {
17585 EVT VT = N->getValueType(0);
17586 if (VT != MVT::v2f32)
17587 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
17588 SDValue UNDEF = DAG.getUNDEF(VT);
17589 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17590 N->getOperand(0), UNDEF);
17591 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
17592 N->getOperand(1), UNDEF);
17593 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
17596 case ISD::SIGN_EXTEND_INREG:
17601 // We don't want to expand or promote these.
17608 case ISD::UDIVREM: {
17609 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17610 Results.push_back(V);
17613 case ISD::FP_TO_SINT:
17614 case ISD::FP_TO_UINT: {
17615 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17617 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17620 std::pair<SDValue,SDValue> Vals =
17621 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17622 SDValue FIST = Vals.first, StackSlot = Vals.second;
17623 if (FIST.getNode()) {
17624 EVT VT = N->getValueType(0);
17625 // Return a load from the stack slot.
17626 if (StackSlot.getNode())
17627 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17628 MachinePointerInfo(),
17629 false, false, false, 0));
17631 Results.push_back(FIST);
17635 case ISD::UINT_TO_FP: {
17636 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17637 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17638 N->getValueType(0) != MVT::v2f32)
17640 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17642 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
17644 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17645 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17646 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17647 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17648 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17649 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17652 case ISD::FP_ROUND: {
17653 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17655 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17656 Results.push_back(V);
17659 case ISD::INTRINSIC_W_CHAIN: {
17660 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17662 default : llvm_unreachable("Do not know how to custom type "
17663 "legalize this intrinsic operation!");
17664 case Intrinsic::x86_rdtsc:
17665 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17667 case Intrinsic::x86_rdtscp:
17668 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17670 case Intrinsic::x86_rdpmc:
17671 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17674 case ISD::READCYCLECOUNTER: {
17675 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17678 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17679 EVT T = N->getValueType(0);
17680 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17681 bool Regs64bit = T == MVT::i128;
17682 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17683 SDValue cpInL, cpInH;
17684 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17685 DAG.getConstant(0, dl, HalfT));
17686 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17687 DAG.getConstant(1, dl, HalfT));
17688 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17689 Regs64bit ? X86::RAX : X86::EAX,
17691 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17692 Regs64bit ? X86::RDX : X86::EDX,
17693 cpInH, cpInL.getValue(1));
17694 SDValue swapInL, swapInH;
17695 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17696 DAG.getConstant(0, dl, HalfT));
17697 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17698 DAG.getConstant(1, dl, HalfT));
17699 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17700 Regs64bit ? X86::RBX : X86::EBX,
17701 swapInL, cpInH.getValue(1));
17702 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17703 Regs64bit ? X86::RCX : X86::ECX,
17704 swapInH, swapInL.getValue(1));
17705 SDValue Ops[] = { swapInH.getValue(0),
17707 swapInH.getValue(1) };
17708 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17709 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17710 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17711 X86ISD::LCMPXCHG8_DAG;
17712 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17713 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17714 Regs64bit ? X86::RAX : X86::EAX,
17715 HalfT, Result.getValue(1));
17716 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17717 Regs64bit ? X86::RDX : X86::EDX,
17718 HalfT, cpOutL.getValue(2));
17719 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17721 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17722 MVT::i32, cpOutH.getValue(2));
17724 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17725 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
17726 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17728 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17729 Results.push_back(Success);
17730 Results.push_back(EFLAGS.getValue(1));
17733 case ISD::ATOMIC_SWAP:
17734 case ISD::ATOMIC_LOAD_ADD:
17735 case ISD::ATOMIC_LOAD_SUB:
17736 case ISD::ATOMIC_LOAD_AND:
17737 case ISD::ATOMIC_LOAD_OR:
17738 case ISD::ATOMIC_LOAD_XOR:
17739 case ISD::ATOMIC_LOAD_NAND:
17740 case ISD::ATOMIC_LOAD_MIN:
17741 case ISD::ATOMIC_LOAD_MAX:
17742 case ISD::ATOMIC_LOAD_UMIN:
17743 case ISD::ATOMIC_LOAD_UMAX:
17744 case ISD::ATOMIC_LOAD: {
17745 // Delegate to generic TypeLegalization. Situations we can really handle
17746 // should have already been dealt with by AtomicExpandPass.cpp.
17749 case ISD::BITCAST: {
17750 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17751 EVT DstVT = N->getValueType(0);
17752 EVT SrcVT = N->getOperand(0)->getValueType(0);
17754 if (SrcVT != MVT::f64 ||
17755 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17758 unsigned NumElts = DstVT.getVectorNumElements();
17759 EVT SVT = DstVT.getVectorElementType();
17760 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17761 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17762 MVT::v2f64, N->getOperand(0));
17763 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17765 if (ExperimentalVectorWideningLegalization) {
17766 // If we are legalizing vectors by widening, we already have the desired
17767 // legal vector type, just return it.
17768 Results.push_back(ToVecInt);
17772 SmallVector<SDValue, 8> Elts;
17773 for (unsigned i = 0, e = NumElts; i != e; ++i)
17774 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17775 ToVecInt, DAG.getIntPtrConstant(i, dl)));
17777 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17782 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17783 switch ((X86ISD::NodeType)Opcode) {
17784 case X86ISD::FIRST_NUMBER: break;
17785 case X86ISD::BSF: return "X86ISD::BSF";
17786 case X86ISD::BSR: return "X86ISD::BSR";
17787 case X86ISD::SHLD: return "X86ISD::SHLD";
17788 case X86ISD::SHRD: return "X86ISD::SHRD";
17789 case X86ISD::FAND: return "X86ISD::FAND";
17790 case X86ISD::FANDN: return "X86ISD::FANDN";
17791 case X86ISD::FOR: return "X86ISD::FOR";
17792 case X86ISD::FXOR: return "X86ISD::FXOR";
17793 case X86ISD::FSRL: return "X86ISD::FSRL";
17794 case X86ISD::FILD: return "X86ISD::FILD";
17795 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17796 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17797 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17798 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17799 case X86ISD::FLD: return "X86ISD::FLD";
17800 case X86ISD::FST: return "X86ISD::FST";
17801 case X86ISD::CALL: return "X86ISD::CALL";
17802 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17803 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17804 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17805 case X86ISD::BT: return "X86ISD::BT";
17806 case X86ISD::CMP: return "X86ISD::CMP";
17807 case X86ISD::COMI: return "X86ISD::COMI";
17808 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17809 case X86ISD::CMPM: return "X86ISD::CMPM";
17810 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17811 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
17812 case X86ISD::SETCC: return "X86ISD::SETCC";
17813 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17814 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17815 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
17816 case X86ISD::CMOV: return "X86ISD::CMOV";
17817 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17818 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17819 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17820 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17821 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17822 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17823 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17824 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
17825 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
17826 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
17827 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17828 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17829 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17830 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17831 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17832 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
17833 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17834 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17835 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17836 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17837 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
17838 case X86ISD::ADDUS: return "X86ISD::ADDUS";
17839 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17840 case X86ISD::HADD: return "X86ISD::HADD";
17841 case X86ISD::HSUB: return "X86ISD::HSUB";
17842 case X86ISD::FHADD: return "X86ISD::FHADD";
17843 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17844 case X86ISD::UMAX: return "X86ISD::UMAX";
17845 case X86ISD::UMIN: return "X86ISD::UMIN";
17846 case X86ISD::SMAX: return "X86ISD::SMAX";
17847 case X86ISD::SMIN: return "X86ISD::SMIN";
17848 case X86ISD::FMAX: return "X86ISD::FMAX";
17849 case X86ISD::FMIN: return "X86ISD::FMIN";
17850 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17851 case X86ISD::FMINC: return "X86ISD::FMINC";
17852 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17853 case X86ISD::FRCP: return "X86ISD::FRCP";
17854 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17855 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17856 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17857 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17858 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17859 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17860 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17861 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17862 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17863 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17864 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17865 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17866 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17867 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17868 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17869 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17870 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17871 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17872 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17873 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17874 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17875 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17876 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17877 case X86ISD::VSHL: return "X86ISD::VSHL";
17878 case X86ISD::VSRL: return "X86ISD::VSRL";
17879 case X86ISD::VSRA: return "X86ISD::VSRA";
17880 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17881 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17882 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17883 case X86ISD::CMPP: return "X86ISD::CMPP";
17884 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17885 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17886 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17887 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17888 case X86ISD::ADD: return "X86ISD::ADD";
17889 case X86ISD::SUB: return "X86ISD::SUB";
17890 case X86ISD::ADC: return "X86ISD::ADC";
17891 case X86ISD::SBB: return "X86ISD::SBB";
17892 case X86ISD::SMUL: return "X86ISD::SMUL";
17893 case X86ISD::UMUL: return "X86ISD::UMUL";
17894 case X86ISD::SMUL8: return "X86ISD::SMUL8";
17895 case X86ISD::UMUL8: return "X86ISD::UMUL8";
17896 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
17897 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
17898 case X86ISD::INC: return "X86ISD::INC";
17899 case X86ISD::DEC: return "X86ISD::DEC";
17900 case X86ISD::OR: return "X86ISD::OR";
17901 case X86ISD::XOR: return "X86ISD::XOR";
17902 case X86ISD::AND: return "X86ISD::AND";
17903 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17904 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17905 case X86ISD::PTEST: return "X86ISD::PTEST";
17906 case X86ISD::TESTP: return "X86ISD::TESTP";
17907 case X86ISD::TESTM: return "X86ISD::TESTM";
17908 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17909 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17910 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17911 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17912 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17913 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17914 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17915 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17916 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17917 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17918 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17919 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17920 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17921 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17922 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17923 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17924 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17925 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17926 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17927 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17928 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17929 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17930 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17931 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17932 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
17933 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
17934 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17935 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17936 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17937 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17938 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17939 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17940 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17941 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17942 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17943 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17944 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17945 case X86ISD::MFENCE: return "X86ISD::MFENCE";
17946 case X86ISD::SFENCE: return "X86ISD::SFENCE";
17947 case X86ISD::LFENCE: return "X86ISD::LFENCE";
17948 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17949 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17950 case X86ISD::SAHF: return "X86ISD::SAHF";
17951 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17952 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17953 case X86ISD::FMADD: return "X86ISD::FMADD";
17954 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17955 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17956 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17957 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17958 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17959 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
17960 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
17961 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
17962 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
17963 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
17964 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
17965 case X86ISD::RNDSCALE: return "X86ISD::RNDSCALE";
17966 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17967 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17968 case X86ISD::XTEST: return "X86ISD::XTEST";
17969 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
17970 case X86ISD::EXPAND: return "X86ISD::EXPAND";
17971 case X86ISD::SELECT: return "X86ISD::SELECT";
17972 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
17973 case X86ISD::RCP28: return "X86ISD::RCP28";
17974 case X86ISD::EXP2: return "X86ISD::EXP2";
17975 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
17976 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
17977 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
17978 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
17979 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
17980 case X86ISD::ADDS: return "X86ISD::ADDS";
17981 case X86ISD::SUBS: return "X86ISD::SUBS";
17986 // isLegalAddressingMode - Return true if the addressing mode represented
17987 // by AM is legal for this target, for a load/store of the specified type.
17988 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17990 // X86 supports extremely general addressing modes.
17991 CodeModel::Model M = getTargetMachine().getCodeModel();
17992 Reloc::Model R = getTargetMachine().getRelocationModel();
17994 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17995 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18000 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18002 // If a reference to this global requires an extra load, we can't fold it.
18003 if (isGlobalStubReference(GVFlags))
18006 // If BaseGV requires a register for the PIC base, we cannot also have a
18007 // BaseReg specified.
18008 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18011 // If lower 4G is not available, then we must use rip-relative addressing.
18012 if ((M != CodeModel::Small || R != Reloc::Static) &&
18013 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18017 switch (AM.Scale) {
18023 // These scales always work.
18028 // These scales are formed with basereg+scalereg. Only accept if there is
18033 default: // Other stuff never works.
18040 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18041 unsigned Bits = Ty->getScalarSizeInBits();
18043 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18044 // particularly cheaper than those without.
18048 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18049 // variable shifts just as cheap as scalar ones.
18050 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18053 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18054 // fully general vector.
18058 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18059 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18061 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18062 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18063 return NumBits1 > NumBits2;
18066 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18067 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18070 if (!isTypeLegal(EVT::getEVT(Ty1)))
18073 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18075 // Assuming the caller doesn't have a zeroext or signext return parameter,
18076 // truncation all the way down to i1 is valid.
18080 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18081 return isInt<32>(Imm);
18084 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18085 // Can also use sub to handle negated immediates.
18086 return isInt<32>(Imm);
18089 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18090 if (!VT1.isInteger() || !VT2.isInteger())
18092 unsigned NumBits1 = VT1.getSizeInBits();
18093 unsigned NumBits2 = VT2.getSizeInBits();
18094 return NumBits1 > NumBits2;
18097 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18098 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18099 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18102 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18103 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18104 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18107 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18108 EVT VT1 = Val.getValueType();
18109 if (isZExtFree(VT1, VT2))
18112 if (Val.getOpcode() != ISD::LOAD)
18115 if (!VT1.isSimple() || !VT1.isInteger() ||
18116 !VT2.isSimple() || !VT2.isInteger())
18119 switch (VT1.getSimpleVT().SimpleTy) {
18124 // X86 has 8, 16, and 32-bit zero-extending loads.
18131 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18134 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18135 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18138 VT = VT.getScalarType();
18140 if (!VT.isSimple())
18143 switch (VT.getSimpleVT().SimpleTy) {
18154 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18155 // i16 instructions are longer (0x66 prefix) and potentially slower.
18156 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18159 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18160 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18161 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18162 /// are assumed to be legal.
18164 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18166 if (!VT.isSimple())
18169 // Very little shuffling can be done for 64-bit vectors right now.
18170 if (VT.getSizeInBits() == 64)
18173 // We only care that the types being shuffled are legal. The lowering can
18174 // handle any possible shuffle mask that results.
18175 return isTypeLegal(VT.getSimpleVT());
18179 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18181 // Just delegate to the generic legality, clear masks aren't special.
18182 return isShuffleMaskLegal(Mask, VT);
18185 //===----------------------------------------------------------------------===//
18186 // X86 Scheduler Hooks
18187 //===----------------------------------------------------------------------===//
18189 /// Utility function to emit xbegin specifying the start of an RTM region.
18190 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18191 const TargetInstrInfo *TII) {
18192 DebugLoc DL = MI->getDebugLoc();
18194 const BasicBlock *BB = MBB->getBasicBlock();
18195 MachineFunction::iterator I = MBB;
18198 // For the v = xbegin(), we generate
18209 MachineBasicBlock *thisMBB = MBB;
18210 MachineFunction *MF = MBB->getParent();
18211 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18212 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18213 MF->insert(I, mainMBB);
18214 MF->insert(I, sinkMBB);
18216 // Transfer the remainder of BB and its successor edges to sinkMBB.
18217 sinkMBB->splice(sinkMBB->begin(), MBB,
18218 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18219 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18223 // # fallthrough to mainMBB
18224 // # abortion to sinkMBB
18225 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18226 thisMBB->addSuccessor(mainMBB);
18227 thisMBB->addSuccessor(sinkMBB);
18231 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18232 mainMBB->addSuccessor(sinkMBB);
18235 // EAX is live into the sinkMBB
18236 sinkMBB->addLiveIn(X86::EAX);
18237 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18238 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18241 MI->eraseFromParent();
18245 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18246 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18247 // in the .td file.
18248 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18249 const TargetInstrInfo *TII) {
18251 switch (MI->getOpcode()) {
18252 default: llvm_unreachable("illegal opcode!");
18253 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
18254 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18255 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
18256 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18257 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
18258 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18259 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
18260 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18263 DebugLoc dl = MI->getDebugLoc();
18264 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18266 unsigned NumArgs = MI->getNumOperands();
18267 for (unsigned i = 1; i < NumArgs; ++i) {
18268 MachineOperand &Op = MI->getOperand(i);
18269 if (!(Op.isReg() && Op.isImplicit()))
18270 MIB.addOperand(Op);
18272 if (MI->hasOneMemOperand())
18273 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18275 BuildMI(*BB, MI, dl,
18276 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18277 .addReg(X86::XMM0);
18279 MI->eraseFromParent();
18283 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18284 // defs in an instruction pattern
18285 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18286 const TargetInstrInfo *TII) {
18288 switch (MI->getOpcode()) {
18289 default: llvm_unreachable("illegal opcode!");
18290 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18291 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18292 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18293 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18294 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18295 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18296 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18297 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18300 DebugLoc dl = MI->getDebugLoc();
18301 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18303 unsigned NumArgs = MI->getNumOperands(); // remove the results
18304 for (unsigned i = 1; i < NumArgs; ++i) {
18305 MachineOperand &Op = MI->getOperand(i);
18306 if (!(Op.isReg() && Op.isImplicit()))
18307 MIB.addOperand(Op);
18309 if (MI->hasOneMemOperand())
18310 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18312 BuildMI(*BB, MI, dl,
18313 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18316 MI->eraseFromParent();
18320 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18321 const X86Subtarget *Subtarget) {
18322 DebugLoc dl = MI->getDebugLoc();
18323 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18324 // Address into RAX/EAX, other two args into ECX, EDX.
18325 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18326 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18327 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18328 for (int i = 0; i < X86::AddrNumOperands; ++i)
18329 MIB.addOperand(MI->getOperand(i));
18331 unsigned ValOps = X86::AddrNumOperands;
18332 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18333 .addReg(MI->getOperand(ValOps).getReg());
18334 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18335 .addReg(MI->getOperand(ValOps+1).getReg());
18337 // The instruction doesn't actually take any operands though.
18338 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18340 MI->eraseFromParent(); // The pseudo is gone now.
18344 MachineBasicBlock *
18345 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
18346 MachineBasicBlock *MBB) const {
18347 // Emit va_arg instruction on X86-64.
18349 // Operands to this pseudo-instruction:
18350 // 0 ) Output : destination address (reg)
18351 // 1-5) Input : va_list address (addr, i64mem)
18352 // 6 ) ArgSize : Size (in bytes) of vararg type
18353 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18354 // 8 ) Align : Alignment of type
18355 // 9 ) EFLAGS (implicit-def)
18357 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18358 static_assert(X86::AddrNumOperands == 5,
18359 "VAARG_64 assumes 5 address operands");
18361 unsigned DestReg = MI->getOperand(0).getReg();
18362 MachineOperand &Base = MI->getOperand(1);
18363 MachineOperand &Scale = MI->getOperand(2);
18364 MachineOperand &Index = MI->getOperand(3);
18365 MachineOperand &Disp = MI->getOperand(4);
18366 MachineOperand &Segment = MI->getOperand(5);
18367 unsigned ArgSize = MI->getOperand(6).getImm();
18368 unsigned ArgMode = MI->getOperand(7).getImm();
18369 unsigned Align = MI->getOperand(8).getImm();
18371 // Memory Reference
18372 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18373 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18374 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18376 // Machine Information
18377 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18378 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18379 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18380 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18381 DebugLoc DL = MI->getDebugLoc();
18383 // struct va_list {
18386 // i64 overflow_area (address)
18387 // i64 reg_save_area (address)
18389 // sizeof(va_list) = 24
18390 // alignment(va_list) = 8
18392 unsigned TotalNumIntRegs = 6;
18393 unsigned TotalNumXMMRegs = 8;
18394 bool UseGPOffset = (ArgMode == 1);
18395 bool UseFPOffset = (ArgMode == 2);
18396 unsigned MaxOffset = TotalNumIntRegs * 8 +
18397 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18399 /* Align ArgSize to a multiple of 8 */
18400 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18401 bool NeedsAlign = (Align > 8);
18403 MachineBasicBlock *thisMBB = MBB;
18404 MachineBasicBlock *overflowMBB;
18405 MachineBasicBlock *offsetMBB;
18406 MachineBasicBlock *endMBB;
18408 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18409 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18410 unsigned OffsetReg = 0;
18412 if (!UseGPOffset && !UseFPOffset) {
18413 // If we only pull from the overflow region, we don't create a branch.
18414 // We don't need to alter control flow.
18415 OffsetDestReg = 0; // unused
18416 OverflowDestReg = DestReg;
18418 offsetMBB = nullptr;
18419 overflowMBB = thisMBB;
18422 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18423 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18424 // If not, pull from overflow_area. (branch to overflowMBB)
18429 // offsetMBB overflowMBB
18434 // Registers for the PHI in endMBB
18435 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18436 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18438 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18439 MachineFunction *MF = MBB->getParent();
18440 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18441 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18442 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18444 MachineFunction::iterator MBBIter = MBB;
18447 // Insert the new basic blocks
18448 MF->insert(MBBIter, offsetMBB);
18449 MF->insert(MBBIter, overflowMBB);
18450 MF->insert(MBBIter, endMBB);
18452 // Transfer the remainder of MBB and its successor edges to endMBB.
18453 endMBB->splice(endMBB->begin(), thisMBB,
18454 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18455 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18457 // Make offsetMBB and overflowMBB successors of thisMBB
18458 thisMBB->addSuccessor(offsetMBB);
18459 thisMBB->addSuccessor(overflowMBB);
18461 // endMBB is a successor of both offsetMBB and overflowMBB
18462 offsetMBB->addSuccessor(endMBB);
18463 overflowMBB->addSuccessor(endMBB);
18465 // Load the offset value into a register
18466 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18467 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18471 .addDisp(Disp, UseFPOffset ? 4 : 0)
18472 .addOperand(Segment)
18473 .setMemRefs(MMOBegin, MMOEnd);
18475 // Check if there is enough room left to pull this argument.
18476 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18478 .addImm(MaxOffset + 8 - ArgSizeA8);
18480 // Branch to "overflowMBB" if offset >= max
18481 // Fall through to "offsetMBB" otherwise
18482 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18483 .addMBB(overflowMBB);
18486 // In offsetMBB, emit code to use the reg_save_area.
18488 assert(OffsetReg != 0);
18490 // Read the reg_save_area address.
18491 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18492 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18497 .addOperand(Segment)
18498 .setMemRefs(MMOBegin, MMOEnd);
18500 // Zero-extend the offset
18501 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18502 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18505 .addImm(X86::sub_32bit);
18507 // Add the offset to the reg_save_area to get the final address.
18508 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18509 .addReg(OffsetReg64)
18510 .addReg(RegSaveReg);
18512 // Compute the offset for the next argument
18513 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18514 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18516 .addImm(UseFPOffset ? 16 : 8);
18518 // Store it back into the va_list.
18519 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18523 .addDisp(Disp, UseFPOffset ? 4 : 0)
18524 .addOperand(Segment)
18525 .addReg(NextOffsetReg)
18526 .setMemRefs(MMOBegin, MMOEnd);
18529 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
18534 // Emit code to use overflow area
18537 // Load the overflow_area address into a register.
18538 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18539 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18544 .addOperand(Segment)
18545 .setMemRefs(MMOBegin, MMOEnd);
18547 // If we need to align it, do so. Otherwise, just copy the address
18548 // to OverflowDestReg.
18550 // Align the overflow address
18551 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18552 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18554 // aligned_addr = (addr + (align-1)) & ~(align-1)
18555 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18556 .addReg(OverflowAddrReg)
18559 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18561 .addImm(~(uint64_t)(Align-1));
18563 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18564 .addReg(OverflowAddrReg);
18567 // Compute the next overflow address after this argument.
18568 // (the overflow address should be kept 8-byte aligned)
18569 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18570 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18571 .addReg(OverflowDestReg)
18572 .addImm(ArgSizeA8);
18574 // Store the new overflow address.
18575 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18580 .addOperand(Segment)
18581 .addReg(NextAddrReg)
18582 .setMemRefs(MMOBegin, MMOEnd);
18584 // If we branched, emit the PHI to the front of endMBB.
18586 BuildMI(*endMBB, endMBB->begin(), DL,
18587 TII->get(X86::PHI), DestReg)
18588 .addReg(OffsetDestReg).addMBB(offsetMBB)
18589 .addReg(OverflowDestReg).addMBB(overflowMBB);
18592 // Erase the pseudo instruction
18593 MI->eraseFromParent();
18598 MachineBasicBlock *
18599 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18601 MachineBasicBlock *MBB) const {
18602 // Emit code to save XMM registers to the stack. The ABI says that the
18603 // number of registers to save is given in %al, so it's theoretically
18604 // possible to do an indirect jump trick to avoid saving all of them,
18605 // however this code takes a simpler approach and just executes all
18606 // of the stores if %al is non-zero. It's less code, and it's probably
18607 // easier on the hardware branch predictor, and stores aren't all that
18608 // expensive anyway.
18610 // Create the new basic blocks. One block contains all the XMM stores,
18611 // and one block is the final destination regardless of whether any
18612 // stores were performed.
18613 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18614 MachineFunction *F = MBB->getParent();
18615 MachineFunction::iterator MBBIter = MBB;
18617 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18618 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18619 F->insert(MBBIter, XMMSaveMBB);
18620 F->insert(MBBIter, EndMBB);
18622 // Transfer the remainder of MBB and its successor edges to EndMBB.
18623 EndMBB->splice(EndMBB->begin(), MBB,
18624 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18625 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18627 // The original block will now fall through to the XMM save block.
18628 MBB->addSuccessor(XMMSaveMBB);
18629 // The XMMSaveMBB will fall through to the end block.
18630 XMMSaveMBB->addSuccessor(EndMBB);
18632 // Now add the instructions.
18633 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18634 DebugLoc DL = MI->getDebugLoc();
18636 unsigned CountReg = MI->getOperand(0).getReg();
18637 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18638 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18640 if (!Subtarget->isTargetWin64()) {
18641 // If %al is 0, branch around the XMM save block.
18642 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18643 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
18644 MBB->addSuccessor(EndMBB);
18647 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18648 // that was just emitted, but clearly shouldn't be "saved".
18649 assert((MI->getNumOperands() <= 3 ||
18650 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18651 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18652 && "Expected last argument to be EFLAGS");
18653 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18654 // In the XMM save block, save all the XMM argument registers.
18655 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18656 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18657 MachineMemOperand *MMO =
18658 F->getMachineMemOperand(
18659 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18660 MachineMemOperand::MOStore,
18661 /*Size=*/16, /*Align=*/16);
18662 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18663 .addFrameIndex(RegSaveFrameIndex)
18664 .addImm(/*Scale=*/1)
18665 .addReg(/*IndexReg=*/0)
18666 .addImm(/*Disp=*/Offset)
18667 .addReg(/*Segment=*/0)
18668 .addReg(MI->getOperand(i).getReg())
18669 .addMemOperand(MMO);
18672 MI->eraseFromParent(); // The pseudo instruction is gone now.
18677 // The EFLAGS operand of SelectItr might be missing a kill marker
18678 // because there were multiple uses of EFLAGS, and ISel didn't know
18679 // which to mark. Figure out whether SelectItr should have had a
18680 // kill marker, and set it if it should. Returns the correct kill
18682 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18683 MachineBasicBlock* BB,
18684 const TargetRegisterInfo* TRI) {
18685 // Scan forward through BB for a use/def of EFLAGS.
18686 MachineBasicBlock::iterator miI(std::next(SelectItr));
18687 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18688 const MachineInstr& mi = *miI;
18689 if (mi.readsRegister(X86::EFLAGS))
18691 if (mi.definesRegister(X86::EFLAGS))
18692 break; // Should have kill-flag - update below.
18695 // If we hit the end of the block, check whether EFLAGS is live into a
18697 if (miI == BB->end()) {
18698 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18699 sEnd = BB->succ_end();
18700 sItr != sEnd; ++sItr) {
18701 MachineBasicBlock* succ = *sItr;
18702 if (succ->isLiveIn(X86::EFLAGS))
18707 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18708 // out. SelectMI should have a kill flag on EFLAGS.
18709 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18713 MachineBasicBlock *
18714 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18715 MachineBasicBlock *BB) const {
18716 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18717 DebugLoc DL = MI->getDebugLoc();
18719 // To "insert" a SELECT_CC instruction, we actually have to insert the
18720 // diamond control-flow pattern. The incoming instruction knows the
18721 // destination vreg to set, the condition code register to branch on, the
18722 // true/false values to select between, and a branch opcode to use.
18723 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18724 MachineFunction::iterator It = BB;
18730 // cmpTY ccX, r1, r2
18732 // fallthrough --> copy0MBB
18733 MachineBasicBlock *thisMBB = BB;
18734 MachineFunction *F = BB->getParent();
18736 // We also lower double CMOVs:
18737 // (CMOV (CMOV F, T, cc1), T, cc2)
18738 // to two successives branches. For that, we look for another CMOV as the
18739 // following instruction.
18741 // Without this, we would add a PHI between the two jumps, which ends up
18742 // creating a few copies all around. For instance, for
18744 // (sitofp (zext (fcmp une)))
18746 // we would generate:
18748 // ucomiss %xmm1, %xmm0
18749 // movss <1.0f>, %xmm0
18750 // movaps %xmm0, %xmm1
18752 // xorps %xmm1, %xmm1
18755 // movaps %xmm1, %xmm0
18759 // because this custom-inserter would have generated:
18771 // A: X = ...; Y = ...
18773 // C: Z = PHI [X, A], [Y, B]
18775 // E: PHI [X, C], [Z, D]
18777 // If we lower both CMOVs in a single step, we can instead generate:
18789 // A: X = ...; Y = ...
18791 // E: PHI [X, A], [X, C], [Y, D]
18793 // Which, in our sitofp/fcmp example, gives us something like:
18795 // ucomiss %xmm1, %xmm0
18796 // movss <1.0f>, %xmm0
18799 // xorps %xmm0, %xmm0
18803 MachineInstr *NextCMOV = nullptr;
18804 MachineBasicBlock::iterator NextMIIt =
18805 std::next(MachineBasicBlock::iterator(MI));
18806 if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
18807 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
18808 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
18809 NextCMOV = &*NextMIIt;
18811 MachineBasicBlock *jcc1MBB = nullptr;
18813 // If we have a double CMOV, we lower it to two successive branches to
18814 // the same block. EFLAGS is used by both, so mark it as live in the second.
18816 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
18817 F->insert(It, jcc1MBB);
18818 jcc1MBB->addLiveIn(X86::EFLAGS);
18821 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18822 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18823 F->insert(It, copy0MBB);
18824 F->insert(It, sinkMBB);
18826 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18827 // live into the sink and copy blocks.
18828 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
18830 MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
18831 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
18832 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
18833 copy0MBB->addLiveIn(X86::EFLAGS);
18834 sinkMBB->addLiveIn(X86::EFLAGS);
18837 // Transfer the remainder of BB and its successor edges to sinkMBB.
18838 sinkMBB->splice(sinkMBB->begin(), BB,
18839 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18840 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18842 // Add the true and fallthrough blocks as its successors.
18844 // The fallthrough block may be jcc1MBB, if we have a double CMOV.
18845 BB->addSuccessor(jcc1MBB);
18847 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
18848 // jump to the sinkMBB.
18849 jcc1MBB->addSuccessor(copy0MBB);
18850 jcc1MBB->addSuccessor(sinkMBB);
18852 BB->addSuccessor(copy0MBB);
18855 // The true block target of the first (or only) branch is always sinkMBB.
18856 BB->addSuccessor(sinkMBB);
18858 // Create the conditional branch instruction.
18860 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18861 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18864 unsigned Opc2 = X86::GetCondBranchFromCond(
18865 (X86::CondCode)NextCMOV->getOperand(3).getImm());
18866 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
18870 // %FalseValue = ...
18871 // # fallthrough to sinkMBB
18872 copy0MBB->addSuccessor(sinkMBB);
18875 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18877 MachineInstrBuilder MIB =
18878 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
18879 MI->getOperand(0).getReg())
18880 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18881 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18883 // If we have a double CMOV, the second Jcc provides the same incoming
18884 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
18886 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
18887 // Copy the PHI result to the register defined by the second CMOV.
18888 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
18889 DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
18890 .addReg(MI->getOperand(0).getReg());
18891 NextCMOV->eraseFromParent();
18894 MI->eraseFromParent(); // The pseudo instruction is gone now.
18898 MachineBasicBlock *
18899 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
18900 MachineBasicBlock *BB) const {
18901 MachineFunction *MF = BB->getParent();
18902 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18903 DebugLoc DL = MI->getDebugLoc();
18904 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18906 assert(MF->shouldSplitStack());
18908 const bool Is64Bit = Subtarget->is64Bit();
18909 const bool IsLP64 = Subtarget->isTarget64BitLP64();
18911 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18912 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
18915 // ... [Till the alloca]
18916 // If stacklet is not large enough, jump to mallocMBB
18919 // Allocate by subtracting from RSP
18920 // Jump to continueMBB
18923 // Allocate by call to runtime
18927 // [rest of original BB]
18930 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18931 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18932 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18934 MachineRegisterInfo &MRI = MF->getRegInfo();
18935 const TargetRegisterClass *AddrRegClass =
18936 getRegClassFor(getPointerTy());
18938 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18939 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18940 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18941 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18942 sizeVReg = MI->getOperand(1).getReg(),
18943 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
18945 MachineFunction::iterator MBBIter = BB;
18948 MF->insert(MBBIter, bumpMBB);
18949 MF->insert(MBBIter, mallocMBB);
18950 MF->insert(MBBIter, continueMBB);
18952 continueMBB->splice(continueMBB->begin(), BB,
18953 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18954 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18956 // Add code to the main basic block to check if the stack limit has been hit,
18957 // and if so, jump to mallocMBB otherwise to bumpMBB.
18958 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18959 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18960 .addReg(tmpSPVReg).addReg(sizeVReg);
18961 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
18962 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18963 .addReg(SPLimitVReg);
18964 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
18966 // bumpMBB simply decreases the stack pointer, since we know the current
18967 // stacklet has enough space.
18968 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18969 .addReg(SPLimitVReg);
18970 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18971 .addReg(SPLimitVReg);
18972 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
18974 // Calls into a routine in libgcc to allocate more space from the heap.
18975 const uint32_t *RegMask =
18976 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
18978 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18980 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18981 .addExternalSymbol("__morestack_allocate_stack_space")
18982 .addRegMask(RegMask)
18983 .addReg(X86::RDI, RegState::Implicit)
18984 .addReg(X86::RAX, RegState::ImplicitDefine);
18985 } else if (Is64Bit) {
18986 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
18988 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18989 .addExternalSymbol("__morestack_allocate_stack_space")
18990 .addRegMask(RegMask)
18991 .addReg(X86::EDI, RegState::Implicit)
18992 .addReg(X86::EAX, RegState::ImplicitDefine);
18994 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18996 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18997 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18998 .addExternalSymbol("__morestack_allocate_stack_space")
18999 .addRegMask(RegMask)
19000 .addReg(X86::EAX, RegState::ImplicitDefine);
19004 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19007 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19008 .addReg(IsLP64 ? X86::RAX : X86::EAX);
19009 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19011 // Set up the CFG correctly.
19012 BB->addSuccessor(bumpMBB);
19013 BB->addSuccessor(mallocMBB);
19014 mallocMBB->addSuccessor(continueMBB);
19015 bumpMBB->addSuccessor(continueMBB);
19017 // Take care of the PHI nodes.
19018 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19019 MI->getOperand(0).getReg())
19020 .addReg(mallocPtrVReg).addMBB(mallocMBB)
19021 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19023 // Delete the original pseudo instruction.
19024 MI->eraseFromParent();
19027 return continueMBB;
19030 MachineBasicBlock *
19031 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19032 MachineBasicBlock *BB) const {
19033 DebugLoc DL = MI->getDebugLoc();
19035 assert(!Subtarget->isTargetMachO());
19037 X86FrameLowering::emitStackProbeCall(*BB->getParent(), *BB, MI, DL);
19039 MI->eraseFromParent(); // The pseudo instruction is gone now.
19043 MachineBasicBlock *
19044 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19045 MachineBasicBlock *BB) const {
19046 // This is pretty easy. We're taking the value that we received from
19047 // our load from the relocation, sticking it in either RDI (x86-64)
19048 // or EAX and doing an indirect call. The return value will then
19049 // be in the normal return register.
19050 MachineFunction *F = BB->getParent();
19051 const X86InstrInfo *TII = Subtarget->getInstrInfo();
19052 DebugLoc DL = MI->getDebugLoc();
19054 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19055 assert(MI->getOperand(3).isGlobal() && "This should be a global");
19057 // Get a register mask for the lowered call.
19058 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19059 // proper register mask.
19060 const uint32_t *RegMask =
19061 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19062 if (Subtarget->is64Bit()) {
19063 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19064 TII->get(X86::MOV64rm), X86::RDI)
19066 .addImm(0).addReg(0)
19067 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19068 MI->getOperand(3).getTargetFlags())
19070 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19071 addDirectMem(MIB, X86::RDI);
19072 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19073 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19074 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19075 TII->get(X86::MOV32rm), X86::EAX)
19077 .addImm(0).addReg(0)
19078 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19079 MI->getOperand(3).getTargetFlags())
19081 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19082 addDirectMem(MIB, X86::EAX);
19083 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19085 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19086 TII->get(X86::MOV32rm), X86::EAX)
19087 .addReg(TII->getGlobalBaseReg(F))
19088 .addImm(0).addReg(0)
19089 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19090 MI->getOperand(3).getTargetFlags())
19092 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19093 addDirectMem(MIB, X86::EAX);
19094 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19097 MI->eraseFromParent(); // The pseudo instruction is gone now.
19101 MachineBasicBlock *
19102 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19103 MachineBasicBlock *MBB) const {
19104 DebugLoc DL = MI->getDebugLoc();
19105 MachineFunction *MF = MBB->getParent();
19106 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19107 MachineRegisterInfo &MRI = MF->getRegInfo();
19109 const BasicBlock *BB = MBB->getBasicBlock();
19110 MachineFunction::iterator I = MBB;
19113 // Memory Reference
19114 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19115 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19118 unsigned MemOpndSlot = 0;
19120 unsigned CurOp = 0;
19122 DstReg = MI->getOperand(CurOp++).getReg();
19123 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19124 assert(RC->hasType(MVT::i32) && "Invalid destination!");
19125 unsigned mainDstReg = MRI.createVirtualRegister(RC);
19126 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19128 MemOpndSlot = CurOp;
19130 MVT PVT = getPointerTy();
19131 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19132 "Invalid Pointer Size!");
19134 // For v = setjmp(buf), we generate
19137 // buf[LabelOffset] = restoreMBB
19138 // SjLjSetup restoreMBB
19144 // v = phi(main, restore)
19147 // if base pointer being used, load it from frame
19150 MachineBasicBlock *thisMBB = MBB;
19151 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19152 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19153 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19154 MF->insert(I, mainMBB);
19155 MF->insert(I, sinkMBB);
19156 MF->push_back(restoreMBB);
19158 MachineInstrBuilder MIB;
19160 // Transfer the remainder of BB and its successor edges to sinkMBB.
19161 sinkMBB->splice(sinkMBB->begin(), MBB,
19162 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19163 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19166 unsigned PtrStoreOpc = 0;
19167 unsigned LabelReg = 0;
19168 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19169 Reloc::Model RM = MF->getTarget().getRelocationModel();
19170 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19171 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19173 // Prepare IP either in reg or imm.
19174 if (!UseImmLabel) {
19175 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19176 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19177 LabelReg = MRI.createVirtualRegister(PtrRC);
19178 if (Subtarget->is64Bit()) {
19179 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19183 .addMBB(restoreMBB)
19186 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19187 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19188 .addReg(XII->getGlobalBaseReg(MF))
19191 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19195 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19197 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19198 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19199 if (i == X86::AddrDisp)
19200 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19202 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19205 MIB.addReg(LabelReg);
19207 MIB.addMBB(restoreMBB);
19208 MIB.setMemRefs(MMOBegin, MMOEnd);
19210 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19211 .addMBB(restoreMBB);
19213 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19214 MIB.addRegMask(RegInfo->getNoPreservedMask());
19215 thisMBB->addSuccessor(mainMBB);
19216 thisMBB->addSuccessor(restoreMBB);
19220 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19221 mainMBB->addSuccessor(sinkMBB);
19224 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19225 TII->get(X86::PHI), DstReg)
19226 .addReg(mainDstReg).addMBB(mainMBB)
19227 .addReg(restoreDstReg).addMBB(restoreMBB);
19230 if (RegInfo->hasBasePointer(*MF)) {
19231 const bool Uses64BitFramePtr =
19232 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19233 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19234 X86FI->setRestoreBasePointer(MF);
19235 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19236 unsigned BasePtr = RegInfo->getBaseRegister();
19237 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19238 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19239 FramePtr, true, X86FI->getRestoreBasePointerOffset())
19240 .setMIFlag(MachineInstr::FrameSetup);
19242 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19243 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19244 restoreMBB->addSuccessor(sinkMBB);
19246 MI->eraseFromParent();
19250 MachineBasicBlock *
19251 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19252 MachineBasicBlock *MBB) const {
19253 DebugLoc DL = MI->getDebugLoc();
19254 MachineFunction *MF = MBB->getParent();
19255 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19256 MachineRegisterInfo &MRI = MF->getRegInfo();
19258 // Memory Reference
19259 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19260 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19262 MVT PVT = getPointerTy();
19263 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19264 "Invalid Pointer Size!");
19266 const TargetRegisterClass *RC =
19267 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19268 unsigned Tmp = MRI.createVirtualRegister(RC);
19269 // Since FP is only updated here but NOT referenced, it's treated as GPR.
19270 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19271 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19272 unsigned SP = RegInfo->getStackRegister();
19274 MachineInstrBuilder MIB;
19276 const int64_t LabelOffset = 1 * PVT.getStoreSize();
19277 const int64_t SPOffset = 2 * PVT.getStoreSize();
19279 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19280 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19283 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19284 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19285 MIB.addOperand(MI->getOperand(i));
19286 MIB.setMemRefs(MMOBegin, MMOEnd);
19288 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19289 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19290 if (i == X86::AddrDisp)
19291 MIB.addDisp(MI->getOperand(i), LabelOffset);
19293 MIB.addOperand(MI->getOperand(i));
19295 MIB.setMemRefs(MMOBegin, MMOEnd);
19297 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19298 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19299 if (i == X86::AddrDisp)
19300 MIB.addDisp(MI->getOperand(i), SPOffset);
19302 MIB.addOperand(MI->getOperand(i));
19304 MIB.setMemRefs(MMOBegin, MMOEnd);
19306 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19308 MI->eraseFromParent();
19312 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19313 // accumulator loops. Writing back to the accumulator allows the coalescer
19314 // to remove extra copies in the loop.
19315 MachineBasicBlock *
19316 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19317 MachineBasicBlock *MBB) const {
19318 MachineOperand &AddendOp = MI->getOperand(3);
19320 // Bail out early if the addend isn't a register - we can't switch these.
19321 if (!AddendOp.isReg())
19324 MachineFunction &MF = *MBB->getParent();
19325 MachineRegisterInfo &MRI = MF.getRegInfo();
19327 // Check whether the addend is defined by a PHI:
19328 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19329 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19330 if (!AddendDef.isPHI())
19333 // Look for the following pattern:
19335 // %addend = phi [%entry, 0], [%loop, %result]
19337 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19341 // %addend = phi [%entry, 0], [%loop, %result]
19343 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19345 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19346 assert(AddendDef.getOperand(i).isReg());
19347 MachineOperand PHISrcOp = AddendDef.getOperand(i);
19348 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19349 if (&PHISrcInst == MI) {
19350 // Found a matching instruction.
19351 unsigned NewFMAOpc = 0;
19352 switch (MI->getOpcode()) {
19353 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19354 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19355 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19356 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19357 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19358 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19359 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19360 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19361 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19362 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19363 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19364 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19365 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19366 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19367 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19368 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19369 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
19370 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
19371 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
19372 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
19374 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19375 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19376 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19377 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19378 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19379 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19380 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19381 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19382 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
19383 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
19384 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
19385 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
19386 default: llvm_unreachable("Unrecognized FMA variant.");
19389 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
19390 MachineInstrBuilder MIB =
19391 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19392 .addOperand(MI->getOperand(0))
19393 .addOperand(MI->getOperand(3))
19394 .addOperand(MI->getOperand(2))
19395 .addOperand(MI->getOperand(1));
19396 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19397 MI->eraseFromParent();
19404 MachineBasicBlock *
19405 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19406 MachineBasicBlock *BB) const {
19407 switch (MI->getOpcode()) {
19408 default: llvm_unreachable("Unexpected instr type to insert");
19409 case X86::TAILJMPd64:
19410 case X86::TAILJMPr64:
19411 case X86::TAILJMPm64:
19412 case X86::TAILJMPd64_REX:
19413 case X86::TAILJMPr64_REX:
19414 case X86::TAILJMPm64_REX:
19415 llvm_unreachable("TAILJMP64 would not be touched here.");
19416 case X86::TCRETURNdi64:
19417 case X86::TCRETURNri64:
19418 case X86::TCRETURNmi64:
19420 case X86::WIN_ALLOCA:
19421 return EmitLoweredWinAlloca(MI, BB);
19422 case X86::SEG_ALLOCA_32:
19423 case X86::SEG_ALLOCA_64:
19424 return EmitLoweredSegAlloca(MI, BB);
19425 case X86::TLSCall_32:
19426 case X86::TLSCall_64:
19427 return EmitLoweredTLSCall(MI, BB);
19428 case X86::CMOV_GR8:
19429 case X86::CMOV_FR32:
19430 case X86::CMOV_FR64:
19431 case X86::CMOV_V4F32:
19432 case X86::CMOV_V2F64:
19433 case X86::CMOV_V2I64:
19434 case X86::CMOV_V8F32:
19435 case X86::CMOV_V4F64:
19436 case X86::CMOV_V4I64:
19437 case X86::CMOV_V16F32:
19438 case X86::CMOV_V8F64:
19439 case X86::CMOV_V8I64:
19440 case X86::CMOV_GR16:
19441 case X86::CMOV_GR32:
19442 case X86::CMOV_RFP32:
19443 case X86::CMOV_RFP64:
19444 case X86::CMOV_RFP80:
19445 return EmitLoweredSelect(MI, BB);
19447 case X86::FP32_TO_INT16_IN_MEM:
19448 case X86::FP32_TO_INT32_IN_MEM:
19449 case X86::FP32_TO_INT64_IN_MEM:
19450 case X86::FP64_TO_INT16_IN_MEM:
19451 case X86::FP64_TO_INT32_IN_MEM:
19452 case X86::FP64_TO_INT64_IN_MEM:
19453 case X86::FP80_TO_INT16_IN_MEM:
19454 case X86::FP80_TO_INT32_IN_MEM:
19455 case X86::FP80_TO_INT64_IN_MEM: {
19456 MachineFunction *F = BB->getParent();
19457 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19458 DebugLoc DL = MI->getDebugLoc();
19460 // Change the floating point control register to use "round towards zero"
19461 // mode when truncating to an integer value.
19462 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19463 addFrameReference(BuildMI(*BB, MI, DL,
19464 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19466 // Load the old value of the high byte of the control word...
19468 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19469 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19472 // Set the high part to be round to zero...
19473 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19476 // Reload the modified control word now...
19477 addFrameReference(BuildMI(*BB, MI, DL,
19478 TII->get(X86::FLDCW16m)), CWFrameIdx);
19480 // Restore the memory image of control word to original value
19481 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19484 // Get the X86 opcode to use.
19486 switch (MI->getOpcode()) {
19487 default: llvm_unreachable("illegal opcode!");
19488 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19489 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19490 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19491 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19492 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19493 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19494 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19495 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19496 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19500 MachineOperand &Op = MI->getOperand(0);
19502 AM.BaseType = X86AddressMode::RegBase;
19503 AM.Base.Reg = Op.getReg();
19505 AM.BaseType = X86AddressMode::FrameIndexBase;
19506 AM.Base.FrameIndex = Op.getIndex();
19508 Op = MI->getOperand(1);
19510 AM.Scale = Op.getImm();
19511 Op = MI->getOperand(2);
19513 AM.IndexReg = Op.getImm();
19514 Op = MI->getOperand(3);
19515 if (Op.isGlobal()) {
19516 AM.GV = Op.getGlobal();
19518 AM.Disp = Op.getImm();
19520 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19521 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19523 // Reload the original control word now.
19524 addFrameReference(BuildMI(*BB, MI, DL,
19525 TII->get(X86::FLDCW16m)), CWFrameIdx);
19527 MI->eraseFromParent(); // The pseudo instruction is gone now.
19530 // String/text processing lowering.
19531 case X86::PCMPISTRM128REG:
19532 case X86::VPCMPISTRM128REG:
19533 case X86::PCMPISTRM128MEM:
19534 case X86::VPCMPISTRM128MEM:
19535 case X86::PCMPESTRM128REG:
19536 case X86::VPCMPESTRM128REG:
19537 case X86::PCMPESTRM128MEM:
19538 case X86::VPCMPESTRM128MEM:
19539 assert(Subtarget->hasSSE42() &&
19540 "Target must have SSE4.2 or AVX features enabled");
19541 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
19543 // String/text processing lowering.
19544 case X86::PCMPISTRIREG:
19545 case X86::VPCMPISTRIREG:
19546 case X86::PCMPISTRIMEM:
19547 case X86::VPCMPISTRIMEM:
19548 case X86::PCMPESTRIREG:
19549 case X86::VPCMPESTRIREG:
19550 case X86::PCMPESTRIMEM:
19551 case X86::VPCMPESTRIMEM:
19552 assert(Subtarget->hasSSE42() &&
19553 "Target must have SSE4.2 or AVX features enabled");
19554 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
19556 // Thread synchronization.
19558 return EmitMonitor(MI, BB, Subtarget);
19562 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
19564 case X86::VASTART_SAVE_XMM_REGS:
19565 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19567 case X86::VAARG_64:
19568 return EmitVAARG64WithCustomInserter(MI, BB);
19570 case X86::EH_SjLj_SetJmp32:
19571 case X86::EH_SjLj_SetJmp64:
19572 return emitEHSjLjSetJmp(MI, BB);
19574 case X86::EH_SjLj_LongJmp32:
19575 case X86::EH_SjLj_LongJmp64:
19576 return emitEHSjLjLongJmp(MI, BB);
19578 case TargetOpcode::STATEPOINT:
19579 // As an implementation detail, STATEPOINT shares the STACKMAP format at
19580 // this point in the process. We diverge later.
19581 return emitPatchPoint(MI, BB);
19583 case TargetOpcode::STACKMAP:
19584 case TargetOpcode::PATCHPOINT:
19585 return emitPatchPoint(MI, BB);
19587 case X86::VFMADDPDr213r:
19588 case X86::VFMADDPSr213r:
19589 case X86::VFMADDSDr213r:
19590 case X86::VFMADDSSr213r:
19591 case X86::VFMSUBPDr213r:
19592 case X86::VFMSUBPSr213r:
19593 case X86::VFMSUBSDr213r:
19594 case X86::VFMSUBSSr213r:
19595 case X86::VFNMADDPDr213r:
19596 case X86::VFNMADDPSr213r:
19597 case X86::VFNMADDSDr213r:
19598 case X86::VFNMADDSSr213r:
19599 case X86::VFNMSUBPDr213r:
19600 case X86::VFNMSUBPSr213r:
19601 case X86::VFNMSUBSDr213r:
19602 case X86::VFNMSUBSSr213r:
19603 case X86::VFMADDSUBPDr213r:
19604 case X86::VFMADDSUBPSr213r:
19605 case X86::VFMSUBADDPDr213r:
19606 case X86::VFMSUBADDPSr213r:
19607 case X86::VFMADDPDr213rY:
19608 case X86::VFMADDPSr213rY:
19609 case X86::VFMSUBPDr213rY:
19610 case X86::VFMSUBPSr213rY:
19611 case X86::VFNMADDPDr213rY:
19612 case X86::VFNMADDPSr213rY:
19613 case X86::VFNMSUBPDr213rY:
19614 case X86::VFNMSUBPSr213rY:
19615 case X86::VFMADDSUBPDr213rY:
19616 case X86::VFMADDSUBPSr213rY:
19617 case X86::VFMSUBADDPDr213rY:
19618 case X86::VFMSUBADDPSr213rY:
19619 return emitFMA3Instr(MI, BB);
19623 //===----------------------------------------------------------------------===//
19624 // X86 Optimization Hooks
19625 //===----------------------------------------------------------------------===//
19627 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19630 const SelectionDAG &DAG,
19631 unsigned Depth) const {
19632 unsigned BitWidth = KnownZero.getBitWidth();
19633 unsigned Opc = Op.getOpcode();
19634 assert((Opc >= ISD::BUILTIN_OP_END ||
19635 Opc == ISD::INTRINSIC_WO_CHAIN ||
19636 Opc == ISD::INTRINSIC_W_CHAIN ||
19637 Opc == ISD::INTRINSIC_VOID) &&
19638 "Should use MaskedValueIsZero if you don't know whether Op"
19639 " is a target node!");
19641 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19655 // These nodes' second result is a boolean.
19656 if (Op.getResNo() == 0)
19659 case X86ISD::SETCC:
19660 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19662 case ISD::INTRINSIC_WO_CHAIN: {
19663 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19664 unsigned NumLoBits = 0;
19667 case Intrinsic::x86_sse_movmsk_ps:
19668 case Intrinsic::x86_avx_movmsk_ps_256:
19669 case Intrinsic::x86_sse2_movmsk_pd:
19670 case Intrinsic::x86_avx_movmsk_pd_256:
19671 case Intrinsic::x86_mmx_pmovmskb:
19672 case Intrinsic::x86_sse2_pmovmskb_128:
19673 case Intrinsic::x86_avx2_pmovmskb: {
19674 // High bits of movmskp{s|d}, pmovmskb are known zero.
19676 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19677 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19678 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19679 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19680 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19681 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19682 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19683 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19685 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19694 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19696 const SelectionDAG &,
19697 unsigned Depth) const {
19698 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19699 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19700 return Op.getValueType().getScalarType().getSizeInBits();
19706 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19707 /// node is a GlobalAddress + offset.
19708 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19709 const GlobalValue* &GA,
19710 int64_t &Offset) const {
19711 if (N->getOpcode() == X86ISD::Wrapper) {
19712 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19713 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19714 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19718 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19721 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19722 /// same as extracting the high 128-bit part of 256-bit vector and then
19723 /// inserting the result into the low part of a new 256-bit vector
19724 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19725 EVT VT = SVOp->getValueType(0);
19726 unsigned NumElems = VT.getVectorNumElements();
19728 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19729 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19730 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19731 SVOp->getMaskElt(j) >= 0)
19737 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19738 /// same as extracting the low 128-bit part of 256-bit vector and then
19739 /// inserting the result into the high part of a new 256-bit vector
19740 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19741 EVT VT = SVOp->getValueType(0);
19742 unsigned NumElems = VT.getVectorNumElements();
19744 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19745 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19746 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19747 SVOp->getMaskElt(j) >= 0)
19753 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19754 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19755 TargetLowering::DAGCombinerInfo &DCI,
19756 const X86Subtarget* Subtarget) {
19758 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19759 SDValue V1 = SVOp->getOperand(0);
19760 SDValue V2 = SVOp->getOperand(1);
19761 EVT VT = SVOp->getValueType(0);
19762 unsigned NumElems = VT.getVectorNumElements();
19764 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19765 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19769 // V UNDEF BUILD_VECTOR UNDEF
19771 // CONCAT_VECTOR CONCAT_VECTOR
19774 // RESULT: V + zero extended
19776 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19777 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19778 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19781 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19784 // To match the shuffle mask, the first half of the mask should
19785 // be exactly the first vector, and all the rest a splat with the
19786 // first element of the second one.
19787 for (unsigned i = 0; i != NumElems/2; ++i)
19788 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19789 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19792 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19793 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19794 if (Ld->hasNUsesOfValue(1, 0)) {
19795 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19796 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19798 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19800 Ld->getPointerInfo(),
19801 Ld->getAlignment(),
19802 false/*isVolatile*/, true/*ReadMem*/,
19803 false/*WriteMem*/);
19805 // Make sure the newly-created LOAD is in the same position as Ld in
19806 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19807 // and update uses of Ld's output chain to use the TokenFactor.
19808 if (Ld->hasAnyUseOfValue(1)) {
19809 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19810 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19811 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19812 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19813 SDValue(ResNode.getNode(), 1));
19816 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19820 // Emit a zeroed vector and insert the desired subvector on its
19822 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19823 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19824 return DCI.CombineTo(N, InsV);
19827 //===--------------------------------------------------------------------===//
19828 // Combine some shuffles into subvector extracts and inserts:
19831 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19832 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19833 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19834 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19835 return DCI.CombineTo(N, InsV);
19838 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19839 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19840 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19841 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19842 return DCI.CombineTo(N, InsV);
19848 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19851 /// This is the leaf of the recursive combinine below. When we have found some
19852 /// chain of single-use x86 shuffle instructions and accumulated the combined
19853 /// shuffle mask represented by them, this will try to pattern match that mask
19854 /// into either a single instruction if there is a special purpose instruction
19855 /// for this operation, or into a PSHUFB instruction which is a fully general
19856 /// instruction but should only be used to replace chains over a certain depth.
19857 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19858 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19859 TargetLowering::DAGCombinerInfo &DCI,
19860 const X86Subtarget *Subtarget) {
19861 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19863 // Find the operand that enters the chain. Note that multiple uses are OK
19864 // here, we're not going to remove the operand we find.
19865 SDValue Input = Op.getOperand(0);
19866 while (Input.getOpcode() == ISD::BITCAST)
19867 Input = Input.getOperand(0);
19869 MVT VT = Input.getSimpleValueType();
19870 MVT RootVT = Root.getSimpleValueType();
19873 // Just remove no-op shuffle masks.
19874 if (Mask.size() == 1) {
19875 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19880 // Use the float domain if the operand type is a floating point type.
19881 bool FloatDomain = VT.isFloatingPoint();
19883 // For floating point shuffles, we don't have free copies in the shuffle
19884 // instructions or the ability to load as part of the instruction, so
19885 // canonicalize their shuffles to UNPCK or MOV variants.
19887 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19888 // vectors because it can have a load folded into it that UNPCK cannot. This
19889 // doesn't preclude something switching to the shorter encoding post-RA.
19891 // FIXME: Should teach these routines about AVX vector widths.
19892 if (FloatDomain && VT.getSizeInBits() == 128) {
19893 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
19894 bool Lo = Mask.equals({0, 0});
19897 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19898 // is no slower than UNPCKLPD but has the option to fold the input operand
19899 // into even an unaligned memory load.
19900 if (Lo && Subtarget->hasSSE3()) {
19901 Shuffle = X86ISD::MOVDDUP;
19902 ShuffleVT = MVT::v2f64;
19904 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19905 // than the UNPCK variants.
19906 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19907 ShuffleVT = MVT::v4f32;
19909 if (Depth == 1 && Root->getOpcode() == Shuffle)
19910 return false; // Nothing to do!
19911 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19912 DCI.AddToWorklist(Op.getNode());
19913 if (Shuffle == X86ISD::MOVDDUP)
19914 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19916 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19917 DCI.AddToWorklist(Op.getNode());
19918 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19922 if (Subtarget->hasSSE3() &&
19923 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
19924 bool Lo = Mask.equals({0, 0, 2, 2});
19925 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19926 MVT ShuffleVT = MVT::v4f32;
19927 if (Depth == 1 && Root->getOpcode() == Shuffle)
19928 return false; // Nothing to do!
19929 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19930 DCI.AddToWorklist(Op.getNode());
19931 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19932 DCI.AddToWorklist(Op.getNode());
19933 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19937 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
19938 bool Lo = Mask.equals({0, 0, 1, 1});
19939 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19940 MVT ShuffleVT = MVT::v4f32;
19941 if (Depth == 1 && Root->getOpcode() == Shuffle)
19942 return false; // Nothing to do!
19943 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19944 DCI.AddToWorklist(Op.getNode());
19945 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19946 DCI.AddToWorklist(Op.getNode());
19947 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19953 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19954 // variants as none of these have single-instruction variants that are
19955 // superior to the UNPCK formulation.
19956 if (!FloatDomain && VT.getSizeInBits() == 128 &&
19957 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
19958 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
19959 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
19961 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
19962 bool Lo = Mask[0] == 0;
19963 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19964 if (Depth == 1 && Root->getOpcode() == Shuffle)
19965 return false; // Nothing to do!
19967 switch (Mask.size()) {
19969 ShuffleVT = MVT::v8i16;
19972 ShuffleVT = MVT::v16i8;
19975 llvm_unreachable("Impossible mask size!");
19977 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19978 DCI.AddToWorklist(Op.getNode());
19979 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19980 DCI.AddToWorklist(Op.getNode());
19981 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19986 // Don't try to re-form single instruction chains under any circumstances now
19987 // that we've done encoding canonicalization for them.
19991 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19992 // can replace them with a single PSHUFB instruction profitably. Intel's
19993 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19994 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19995 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19996 SmallVector<SDValue, 16> PSHUFBMask;
19997 int NumBytes = VT.getSizeInBits() / 8;
19998 int Ratio = NumBytes / Mask.size();
19999 for (int i = 0; i < NumBytes; ++i) {
20000 if (Mask[i / Ratio] == SM_SentinelUndef) {
20001 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20004 int M = Mask[i / Ratio] != SM_SentinelZero
20005 ? Ratio * Mask[i / Ratio] + i % Ratio
20007 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20009 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20010 Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Input);
20011 DCI.AddToWorklist(Op.getNode());
20012 SDValue PSHUFBMaskOp =
20013 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20014 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20015 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20016 DCI.AddToWorklist(Op.getNode());
20017 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20022 // Failed to find any combines.
20026 /// \brief Fully generic combining of x86 shuffle instructions.
20028 /// This should be the last combine run over the x86 shuffle instructions. Once
20029 /// they have been fully optimized, this will recursively consider all chains
20030 /// of single-use shuffle instructions, build a generic model of the cumulative
20031 /// shuffle operation, and check for simpler instructions which implement this
20032 /// operation. We use this primarily for two purposes:
20034 /// 1) Collapse generic shuffles to specialized single instructions when
20035 /// equivalent. In most cases, this is just an encoding size win, but
20036 /// sometimes we will collapse multiple generic shuffles into a single
20037 /// special-purpose shuffle.
20038 /// 2) Look for sequences of shuffle instructions with 3 or more total
20039 /// instructions, and replace them with the slightly more expensive SSSE3
20040 /// PSHUFB instruction if available. We do this as the last combining step
20041 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
20042 /// a suitable short sequence of other instructions. The PHUFB will either
20043 /// use a register or have to read from memory and so is slightly (but only
20044 /// slightly) more expensive than the other shuffle instructions.
20046 /// Because this is inherently a quadratic operation (for each shuffle in
20047 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20048 /// This should never be an issue in practice as the shuffle lowering doesn't
20049 /// produce sequences of more than 8 instructions.
20051 /// FIXME: We will currently miss some cases where the redundant shuffling
20052 /// would simplify under the threshold for PSHUFB formation because of
20053 /// combine-ordering. To fix this, we should do the redundant instruction
20054 /// combining in this recursive walk.
20055 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20056 ArrayRef<int> RootMask,
20057 int Depth, bool HasPSHUFB,
20059 TargetLowering::DAGCombinerInfo &DCI,
20060 const X86Subtarget *Subtarget) {
20061 // Bound the depth of our recursive combine because this is ultimately
20062 // quadratic in nature.
20066 // Directly rip through bitcasts to find the underlying operand.
20067 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20068 Op = Op.getOperand(0);
20070 MVT VT = Op.getSimpleValueType();
20071 if (!VT.isVector())
20072 return false; // Bail if we hit a non-vector.
20074 assert(Root.getSimpleValueType().isVector() &&
20075 "Shuffles operate on vector types!");
20076 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20077 "Can only combine shuffles of the same vector register size.");
20079 if (!isTargetShuffle(Op.getOpcode()))
20081 SmallVector<int, 16> OpMask;
20083 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20084 // We only can combine unary shuffles which we can decode the mask for.
20085 if (!HaveMask || !IsUnary)
20088 assert(VT.getVectorNumElements() == OpMask.size() &&
20089 "Different mask size from vector size!");
20090 assert(((RootMask.size() > OpMask.size() &&
20091 RootMask.size() % OpMask.size() == 0) ||
20092 (OpMask.size() > RootMask.size() &&
20093 OpMask.size() % RootMask.size() == 0) ||
20094 OpMask.size() == RootMask.size()) &&
20095 "The smaller number of elements must divide the larger.");
20096 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20097 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20098 assert(((RootRatio == 1 && OpRatio == 1) ||
20099 (RootRatio == 1) != (OpRatio == 1)) &&
20100 "Must not have a ratio for both incoming and op masks!");
20102 SmallVector<int, 16> Mask;
20103 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20105 // Merge this shuffle operation's mask into our accumulated mask. Note that
20106 // this shuffle's mask will be the first applied to the input, followed by the
20107 // root mask to get us all the way to the root value arrangement. The reason
20108 // for this order is that we are recursing up the operation chain.
20109 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20110 int RootIdx = i / RootRatio;
20111 if (RootMask[RootIdx] < 0) {
20112 // This is a zero or undef lane, we're done.
20113 Mask.push_back(RootMask[RootIdx]);
20117 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20118 int OpIdx = RootMaskedIdx / OpRatio;
20119 if (OpMask[OpIdx] < 0) {
20120 // The incoming lanes are zero or undef, it doesn't matter which ones we
20122 Mask.push_back(OpMask[OpIdx]);
20126 // Ok, we have non-zero lanes, map them through.
20127 Mask.push_back(OpMask[OpIdx] * OpRatio +
20128 RootMaskedIdx % OpRatio);
20131 // See if we can recurse into the operand to combine more things.
20132 switch (Op.getOpcode()) {
20133 case X86ISD::PSHUFB:
20135 case X86ISD::PSHUFD:
20136 case X86ISD::PSHUFHW:
20137 case X86ISD::PSHUFLW:
20138 if (Op.getOperand(0).hasOneUse() &&
20139 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20140 HasPSHUFB, DAG, DCI, Subtarget))
20144 case X86ISD::UNPCKL:
20145 case X86ISD::UNPCKH:
20146 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20147 // We can't check for single use, we have to check that this shuffle is the only user.
20148 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20149 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20150 HasPSHUFB, DAG, DCI, Subtarget))
20155 // Minor canonicalization of the accumulated shuffle mask to make it easier
20156 // to match below. All this does is detect masks with squential pairs of
20157 // elements, and shrink them to the half-width mask. It does this in a loop
20158 // so it will reduce the size of the mask to the minimal width mask which
20159 // performs an equivalent shuffle.
20160 SmallVector<int, 16> WidenedMask;
20161 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20162 Mask = std::move(WidenedMask);
20163 WidenedMask.clear();
20166 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20170 /// \brief Get the PSHUF-style mask from PSHUF node.
20172 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20173 /// PSHUF-style masks that can be reused with such instructions.
20174 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20175 MVT VT = N.getSimpleValueType();
20176 SmallVector<int, 4> Mask;
20178 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20182 // If we have more than 128-bits, only the low 128-bits of shuffle mask
20183 // matter. Check that the upper masks are repeats and remove them.
20184 if (VT.getSizeInBits() > 128) {
20185 int LaneElts = 128 / VT.getScalarSizeInBits();
20187 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20188 for (int j = 0; j < LaneElts; ++j)
20189 assert(Mask[j] == Mask[i * LaneElts + j] - LaneElts &&
20190 "Mask doesn't repeat in high 128-bit lanes!");
20192 Mask.resize(LaneElts);
20195 switch (N.getOpcode()) {
20196 case X86ISD::PSHUFD:
20198 case X86ISD::PSHUFLW:
20201 case X86ISD::PSHUFHW:
20202 Mask.erase(Mask.begin(), Mask.begin() + 4);
20203 for (int &M : Mask)
20207 llvm_unreachable("No valid shuffle instruction found!");
20211 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20213 /// We walk up the chain and look for a combinable shuffle, skipping over
20214 /// shuffles that we could hoist this shuffle's transformation past without
20215 /// altering anything.
20217 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20219 TargetLowering::DAGCombinerInfo &DCI) {
20220 assert(N.getOpcode() == X86ISD::PSHUFD &&
20221 "Called with something other than an x86 128-bit half shuffle!");
20224 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20225 // of the shuffles in the chain so that we can form a fresh chain to replace
20227 SmallVector<SDValue, 8> Chain;
20228 SDValue V = N.getOperand(0);
20229 for (; V.hasOneUse(); V = V.getOperand(0)) {
20230 switch (V.getOpcode()) {
20232 return SDValue(); // Nothing combined!
20235 // Skip bitcasts as we always know the type for the target specific
20239 case X86ISD::PSHUFD:
20240 // Found another dword shuffle.
20243 case X86ISD::PSHUFLW:
20244 // Check that the low words (being shuffled) are the identity in the
20245 // dword shuffle, and the high words are self-contained.
20246 if (Mask[0] != 0 || Mask[1] != 1 ||
20247 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20250 Chain.push_back(V);
20253 case X86ISD::PSHUFHW:
20254 // Check that the high words (being shuffled) are the identity in the
20255 // dword shuffle, and the low words are self-contained.
20256 if (Mask[2] != 2 || Mask[3] != 3 ||
20257 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20260 Chain.push_back(V);
20263 case X86ISD::UNPCKL:
20264 case X86ISD::UNPCKH:
20265 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20266 // shuffle into a preceding word shuffle.
20267 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20268 V.getSimpleValueType().getScalarType() != MVT::i16)
20271 // Search for a half-shuffle which we can combine with.
20272 unsigned CombineOp =
20273 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20274 if (V.getOperand(0) != V.getOperand(1) ||
20275 !V->isOnlyUserOf(V.getOperand(0).getNode()))
20277 Chain.push_back(V);
20278 V = V.getOperand(0);
20280 switch (V.getOpcode()) {
20282 return SDValue(); // Nothing to combine.
20284 case X86ISD::PSHUFLW:
20285 case X86ISD::PSHUFHW:
20286 if (V.getOpcode() == CombineOp)
20289 Chain.push_back(V);
20293 V = V.getOperand(0);
20297 } while (V.hasOneUse());
20300 // Break out of the loop if we break out of the switch.
20304 if (!V.hasOneUse())
20305 // We fell out of the loop without finding a viable combining instruction.
20308 // Merge this node's mask and our incoming mask.
20309 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20310 for (int &M : Mask)
20312 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20313 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20315 // Rebuild the chain around this new shuffle.
20316 while (!Chain.empty()) {
20317 SDValue W = Chain.pop_back_val();
20319 if (V.getValueType() != W.getOperand(0).getValueType())
20320 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20322 switch (W.getOpcode()) {
20324 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20326 case X86ISD::UNPCKL:
20327 case X86ISD::UNPCKH:
20328 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20331 case X86ISD::PSHUFD:
20332 case X86ISD::PSHUFLW:
20333 case X86ISD::PSHUFHW:
20334 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20338 if (V.getValueType() != N.getValueType())
20339 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20341 // Return the new chain to replace N.
20345 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20347 /// We walk up the chain, skipping shuffles of the other half and looking
20348 /// through shuffles which switch halves trying to find a shuffle of the same
20349 /// pair of dwords.
20350 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20352 TargetLowering::DAGCombinerInfo &DCI) {
20354 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20355 "Called with something other than an x86 128-bit half shuffle!");
20357 unsigned CombineOpcode = N.getOpcode();
20359 // Walk up a single-use chain looking for a combinable shuffle.
20360 SDValue V = N.getOperand(0);
20361 for (; V.hasOneUse(); V = V.getOperand(0)) {
20362 switch (V.getOpcode()) {
20364 return false; // Nothing combined!
20367 // Skip bitcasts as we always know the type for the target specific
20371 case X86ISD::PSHUFLW:
20372 case X86ISD::PSHUFHW:
20373 if (V.getOpcode() == CombineOpcode)
20376 // Other-half shuffles are no-ops.
20379 // Break out of the loop if we break out of the switch.
20383 if (!V.hasOneUse())
20384 // We fell out of the loop without finding a viable combining instruction.
20387 // Combine away the bottom node as its shuffle will be accumulated into
20388 // a preceding shuffle.
20389 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20391 // Record the old value.
20394 // Merge this node's mask and our incoming mask (adjusted to account for all
20395 // the pshufd instructions encountered).
20396 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20397 for (int &M : Mask)
20399 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20400 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20402 // Check that the shuffles didn't cancel each other out. If not, we need to
20403 // combine to the new one.
20405 // Replace the combinable shuffle with the combined one, updating all users
20406 // so that we re-evaluate the chain here.
20407 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20412 /// \brief Try to combine x86 target specific shuffles.
20413 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20414 TargetLowering::DAGCombinerInfo &DCI,
20415 const X86Subtarget *Subtarget) {
20417 MVT VT = N.getSimpleValueType();
20418 SmallVector<int, 4> Mask;
20420 switch (N.getOpcode()) {
20421 case X86ISD::PSHUFD:
20422 case X86ISD::PSHUFLW:
20423 case X86ISD::PSHUFHW:
20424 Mask = getPSHUFShuffleMask(N);
20425 assert(Mask.size() == 4);
20431 // Nuke no-op shuffles that show up after combining.
20432 if (isNoopShuffleMask(Mask))
20433 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20435 // Look for simplifications involving one or two shuffle instructions.
20436 SDValue V = N.getOperand(0);
20437 switch (N.getOpcode()) {
20440 case X86ISD::PSHUFLW:
20441 case X86ISD::PSHUFHW:
20442 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
20444 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20445 return SDValue(); // We combined away this shuffle, so we're done.
20447 // See if this reduces to a PSHUFD which is no more expensive and can
20448 // combine with more operations. Note that it has to at least flip the
20449 // dwords as otherwise it would have been removed as a no-op.
20450 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
20451 int DMask[] = {0, 1, 2, 3};
20452 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20453 DMask[DOffset + 0] = DOffset + 1;
20454 DMask[DOffset + 1] = DOffset + 0;
20455 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
20456 V = DAG.getNode(ISD::BITCAST, DL, DVT, V);
20457 DCI.AddToWorklist(V.getNode());
20458 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
20459 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
20460 DCI.AddToWorklist(V.getNode());
20461 return DAG.getNode(ISD::BITCAST, DL, VT, V);
20464 // Look for shuffle patterns which can be implemented as a single unpack.
20465 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20466 // only works when we have a PSHUFD followed by two half-shuffles.
20467 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20468 (V.getOpcode() == X86ISD::PSHUFLW ||
20469 V.getOpcode() == X86ISD::PSHUFHW) &&
20470 V.getOpcode() != N.getOpcode() &&
20472 SDValue D = V.getOperand(0);
20473 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20474 D = D.getOperand(0);
20475 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20476 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20477 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20478 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20479 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20481 for (int i = 0; i < 4; ++i) {
20482 WordMask[i + NOffset] = Mask[i] + NOffset;
20483 WordMask[i + VOffset] = VMask[i] + VOffset;
20485 // Map the word mask through the DWord mask.
20487 for (int i = 0; i < 8; ++i)
20488 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20489 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20490 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
20491 // We can replace all three shuffles with an unpack.
20492 V = DAG.getNode(ISD::BITCAST, DL, VT, D.getOperand(0));
20493 DCI.AddToWorklist(V.getNode());
20494 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20503 case X86ISD::PSHUFD:
20504 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20513 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20515 /// We combine this directly on the abstract vector shuffle nodes so it is
20516 /// easier to generically match. We also insert dummy vector shuffle nodes for
20517 /// the operands which explicitly discard the lanes which are unused by this
20518 /// operation to try to flow through the rest of the combiner the fact that
20519 /// they're unused.
20520 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20522 EVT VT = N->getValueType(0);
20524 // We only handle target-independent shuffles.
20525 // FIXME: It would be easy and harmless to use the target shuffle mask
20526 // extraction tool to support more.
20527 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20530 auto *SVN = cast<ShuffleVectorSDNode>(N);
20531 ArrayRef<int> Mask = SVN->getMask();
20532 SDValue V1 = N->getOperand(0);
20533 SDValue V2 = N->getOperand(1);
20535 // We require the first shuffle operand to be the SUB node, and the second to
20536 // be the ADD node.
20537 // FIXME: We should support the commuted patterns.
20538 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20541 // If there are other uses of these operations we can't fold them.
20542 if (!V1->hasOneUse() || !V2->hasOneUse())
20545 // Ensure that both operations have the same operands. Note that we can
20546 // commute the FADD operands.
20547 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20548 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20549 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20552 // We're looking for blends between FADD and FSUB nodes. We insist on these
20553 // nodes being lined up in a specific expected pattern.
20554 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
20555 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
20556 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
20559 // Only specific types are legal at this point, assert so we notice if and
20560 // when these change.
20561 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20562 VT == MVT::v4f64) &&
20563 "Unknown vector type encountered!");
20565 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20568 /// PerformShuffleCombine - Performs several different shuffle combines.
20569 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20570 TargetLowering::DAGCombinerInfo &DCI,
20571 const X86Subtarget *Subtarget) {
20573 SDValue N0 = N->getOperand(0);
20574 SDValue N1 = N->getOperand(1);
20575 EVT VT = N->getValueType(0);
20577 // Don't create instructions with illegal types after legalize types has run.
20578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20579 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20582 // If we have legalized the vector types, look for blends of FADD and FSUB
20583 // nodes that we can fuse into an ADDSUB node.
20584 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20585 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20588 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20589 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20590 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20591 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20593 // During Type Legalization, when promoting illegal vector types,
20594 // the backend might introduce new shuffle dag nodes and bitcasts.
20596 // This code performs the following transformation:
20597 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20598 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20600 // We do this only if both the bitcast and the BINOP dag nodes have
20601 // one use. Also, perform this transformation only if the new binary
20602 // operation is legal. This is to avoid introducing dag nodes that
20603 // potentially need to be further expanded (or custom lowered) into a
20604 // less optimal sequence of dag nodes.
20605 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20606 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20607 N0.getOpcode() == ISD::BITCAST) {
20608 SDValue BC0 = N0.getOperand(0);
20609 EVT SVT = BC0.getValueType();
20610 unsigned Opcode = BC0.getOpcode();
20611 unsigned NumElts = VT.getVectorNumElements();
20613 if (BC0.hasOneUse() && SVT.isVector() &&
20614 SVT.getVectorNumElements() * 2 == NumElts &&
20615 TLI.isOperationLegal(Opcode, VT)) {
20616 bool CanFold = false;
20628 unsigned SVTNumElts = SVT.getVectorNumElements();
20629 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20630 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20631 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20632 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20633 CanFold = SVOp->getMaskElt(i) < 0;
20636 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20637 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20638 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20639 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20644 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20645 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20646 // consecutive, non-overlapping, and in the right order.
20647 SmallVector<SDValue, 16> Elts;
20648 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20649 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20651 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20655 if (isTargetShuffle(N->getOpcode())) {
20657 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20658 if (Shuffle.getNode())
20661 // Try recursively combining arbitrary sequences of x86 shuffle
20662 // instructions into higher-order shuffles. We do this after combining
20663 // specific PSHUF instruction sequences into their minimal form so that we
20664 // can evaluate how many specialized shuffle instructions are involved in
20665 // a particular chain.
20666 SmallVector<int, 1> NonceMask; // Just a placeholder.
20667 NonceMask.push_back(0);
20668 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20669 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20671 return SDValue(); // This routine will use CombineTo to replace N.
20677 /// PerformTruncateCombine - Converts truncate operation to
20678 /// a sequence of vector shuffle operations.
20679 /// It is possible when we truncate 256-bit vector to 128-bit vector
20680 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20681 TargetLowering::DAGCombinerInfo &DCI,
20682 const X86Subtarget *Subtarget) {
20686 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20687 /// specific shuffle of a load can be folded into a single element load.
20688 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20689 /// shuffles have been custom lowered so we need to handle those here.
20690 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20691 TargetLowering::DAGCombinerInfo &DCI) {
20692 if (DCI.isBeforeLegalizeOps())
20695 SDValue InVec = N->getOperand(0);
20696 SDValue EltNo = N->getOperand(1);
20698 if (!isa<ConstantSDNode>(EltNo))
20701 EVT OriginalVT = InVec.getValueType();
20703 if (InVec.getOpcode() == ISD::BITCAST) {
20704 // Don't duplicate a load with other uses.
20705 if (!InVec.hasOneUse())
20707 EVT BCVT = InVec.getOperand(0).getValueType();
20708 if (BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
20710 InVec = InVec.getOperand(0);
20713 EVT CurrentVT = InVec.getValueType();
20715 if (!isTargetShuffle(InVec.getOpcode()))
20718 // Don't duplicate a load with other uses.
20719 if (!InVec.hasOneUse())
20722 SmallVector<int, 16> ShuffleMask;
20724 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
20725 ShuffleMask, UnaryShuffle))
20728 // Select the input vector, guarding against out of range extract vector.
20729 unsigned NumElems = CurrentVT.getVectorNumElements();
20730 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20731 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20732 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20733 : InVec.getOperand(1);
20735 // If inputs to shuffle are the same for both ops, then allow 2 uses
20736 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
20737 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20739 if (LdNode.getOpcode() == ISD::BITCAST) {
20740 // Don't duplicate a load with other uses.
20741 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20744 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20745 LdNode = LdNode.getOperand(0);
20748 if (!ISD::isNormalLoad(LdNode.getNode()))
20751 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20753 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20756 EVT EltVT = N->getValueType(0);
20757 // If there's a bitcast before the shuffle, check if the load type and
20758 // alignment is valid.
20759 unsigned Align = LN0->getAlignment();
20760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20761 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20762 EltVT.getTypeForEVT(*DAG.getContext()));
20764 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20767 // All checks match so transform back to vector_shuffle so that DAG combiner
20768 // can finish the job
20771 // Create shuffle node taking into account the case that its a unary shuffle
20772 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
20773 : InVec.getOperand(1);
20774 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
20775 InVec.getOperand(0), Shuffle,
20777 Shuffle = DAG.getNode(ISD::BITCAST, dl, OriginalVT, Shuffle);
20778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20782 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
20783 /// special and don't usually play with other vector types, it's better to
20784 /// handle them early to be sure we emit efficient code by avoiding
20785 /// store-load conversions.
20786 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
20787 if (N->getValueType(0) != MVT::x86mmx ||
20788 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
20789 N->getOperand(0)->getValueType(0) != MVT::v2i32)
20792 SDValue V = N->getOperand(0);
20793 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
20794 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
20795 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
20796 N->getValueType(0), V.getOperand(0));
20801 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20802 /// generation and convert it from being a bunch of shuffles and extracts
20803 /// into a somewhat faster sequence. For i686, the best sequence is apparently
20804 /// storing the value and loading scalars back, while for x64 we should
20805 /// use 64-bit extracts and shifts.
20806 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20807 TargetLowering::DAGCombinerInfo &DCI) {
20808 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20809 if (NewOp.getNode())
20812 SDValue InputVector = N->getOperand(0);
20814 // Detect mmx to i32 conversion through a v2i32 elt extract.
20815 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
20816 N->getValueType(0) == MVT::i32 &&
20817 InputVector.getValueType() == MVT::v2i32) {
20819 // The bitcast source is a direct mmx result.
20820 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
20821 if (MMXSrc.getValueType() == MVT::x86mmx)
20822 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20823 N->getValueType(0),
20824 InputVector.getNode()->getOperand(0));
20826 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
20827 SDValue MMXSrcOp = MMXSrc.getOperand(0);
20828 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
20829 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
20830 MMXSrcOp.getOpcode() == ISD::BITCAST &&
20831 MMXSrcOp.getValueType() == MVT::v1i64 &&
20832 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
20833 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20834 N->getValueType(0),
20835 MMXSrcOp.getOperand(0));
20838 // Only operate on vectors of 4 elements, where the alternative shuffling
20839 // gets to be more expensive.
20840 if (InputVector.getValueType() != MVT::v4i32)
20843 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20844 // single use which is a sign-extend or zero-extend, and all elements are
20846 SmallVector<SDNode *, 4> Uses;
20847 unsigned ExtractedElements = 0;
20848 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20849 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20850 if (UI.getUse().getResNo() != InputVector.getResNo())
20853 SDNode *Extract = *UI;
20854 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20857 if (Extract->getValueType(0) != MVT::i32)
20859 if (!Extract->hasOneUse())
20861 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20862 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20864 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20867 // Record which element was extracted.
20868 ExtractedElements |=
20869 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20871 Uses.push_back(Extract);
20874 // If not all the elements were used, this may not be worthwhile.
20875 if (ExtractedElements != 15)
20878 // Ok, we've now decided to do the transformation.
20879 // If 64-bit shifts are legal, use the extract-shift sequence,
20880 // otherwise bounce the vector off the cache.
20881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20883 SDLoc dl(InputVector);
20885 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
20886 SDValue Cst = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, InputVector);
20887 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
20888 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20889 DAG.getConstant(0, dl, VecIdxTy));
20890 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
20891 DAG.getConstant(1, dl, VecIdxTy));
20893 SDValue ShAmt = DAG.getConstant(32, dl,
20894 DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
20895 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
20896 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20897 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
20898 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
20899 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
20900 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
20902 // Store the value to a temporary stack slot.
20903 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20904 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20905 MachinePointerInfo(), false, false, 0);
20907 EVT ElementType = InputVector.getValueType().getVectorElementType();
20908 unsigned EltSize = ElementType.getSizeInBits() / 8;
20910 // Replace each use (extract) with a load of the appropriate element.
20911 for (unsigned i = 0; i < 4; ++i) {
20912 uint64_t Offset = EltSize * i;
20913 SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
20915 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20916 StackPtr, OffsetVal);
20918 // Load the scalar.
20919 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
20920 ScalarAddr, MachinePointerInfo(),
20921 false, false, false, 0);
20926 // Replace the extracts
20927 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20928 UE = Uses.end(); UI != UE; ++UI) {
20929 SDNode *Extract = *UI;
20931 SDValue Idx = Extract->getOperand(1);
20932 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
20933 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
20936 // The replacement was made in place; don't return anything.
20940 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20941 static std::pair<unsigned, bool>
20942 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20943 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20944 if (!VT.isVector())
20945 return std::make_pair(0, false);
20947 bool NeedSplit = false;
20948 switch (VT.getSimpleVT().SimpleTy) {
20949 default: return std::make_pair(0, false);
20952 if (!Subtarget->hasVLX())
20953 return std::make_pair(0, false);
20957 if (!Subtarget->hasBWI())
20958 return std::make_pair(0, false);
20962 if (!Subtarget->hasAVX512())
20963 return std::make_pair(0, false);
20968 if (!Subtarget->hasAVX2())
20970 if (!Subtarget->hasAVX())
20971 return std::make_pair(0, false);
20976 if (!Subtarget->hasSSE2())
20977 return std::make_pair(0, false);
20980 // SSE2 has only a small subset of the operations.
20981 bool hasUnsigned = Subtarget->hasSSE41() ||
20982 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20983 bool hasSigned = Subtarget->hasSSE41() ||
20984 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20986 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20989 // Check for x CC y ? x : y.
20990 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20991 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20996 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
20999 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21002 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21005 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21007 // Check for x CC y ? y : x -- a min/max with reversed arms.
21008 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21009 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21014 Opc = hasUnsigned ? X86ISD::UMAX : 0u; break;
21017 Opc = hasUnsigned ? X86ISD::UMIN : 0u; break;
21020 Opc = hasSigned ? X86ISD::SMAX : 0u; break;
21023 Opc = hasSigned ? X86ISD::SMIN : 0u; break;
21027 return std::make_pair(Opc, NeedSplit);
21031 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21032 const X86Subtarget *Subtarget) {
21034 SDValue Cond = N->getOperand(0);
21035 SDValue LHS = N->getOperand(1);
21036 SDValue RHS = N->getOperand(2);
21038 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21039 SDValue CondSrc = Cond->getOperand(0);
21040 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21041 Cond = CondSrc->getOperand(0);
21044 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21047 // A vselect where all conditions and data are constants can be optimized into
21048 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21049 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21050 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21053 unsigned MaskValue = 0;
21054 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21057 MVT VT = N->getSimpleValueType(0);
21058 unsigned NumElems = VT.getVectorNumElements();
21059 SmallVector<int, 8> ShuffleMask(NumElems, -1);
21060 for (unsigned i = 0; i < NumElems; ++i) {
21061 // Be sure we emit undef where we can.
21062 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21063 ShuffleMask[i] = -1;
21065 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21068 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21069 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21071 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21074 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21076 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21077 TargetLowering::DAGCombinerInfo &DCI,
21078 const X86Subtarget *Subtarget) {
21080 SDValue Cond = N->getOperand(0);
21081 // Get the LHS/RHS of the select.
21082 SDValue LHS = N->getOperand(1);
21083 SDValue RHS = N->getOperand(2);
21084 EVT VT = LHS.getValueType();
21085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21087 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21088 // instructions match the semantics of the common C idiom x<y?x:y but not
21089 // x<=y?x:y, because of how they handle negative zero (which can be
21090 // ignored in unsafe-math mode).
21091 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21092 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21093 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21094 (Subtarget->hasSSE2() ||
21095 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21096 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21098 unsigned Opcode = 0;
21099 // Check for x CC y ? x : y.
21100 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21101 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21105 // Converting this to a min would handle NaNs incorrectly, and swapping
21106 // the operands would cause it to handle comparisons between positive
21107 // and negative zero incorrectly.
21108 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21109 if (!DAG.getTarget().Options.UnsafeFPMath &&
21110 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21112 std::swap(LHS, RHS);
21114 Opcode = X86ISD::FMIN;
21117 // Converting this to a min would handle comparisons between positive
21118 // and negative zero incorrectly.
21119 if (!DAG.getTarget().Options.UnsafeFPMath &&
21120 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21122 Opcode = X86ISD::FMIN;
21125 // Converting this to a min would handle both negative zeros and NaNs
21126 // incorrectly, but we can swap the operands to fix both.
21127 std::swap(LHS, RHS);
21131 Opcode = X86ISD::FMIN;
21135 // Converting this to a max would handle comparisons between positive
21136 // and negative zero incorrectly.
21137 if (!DAG.getTarget().Options.UnsafeFPMath &&
21138 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21140 Opcode = X86ISD::FMAX;
21143 // Converting this to a max would handle NaNs incorrectly, and swapping
21144 // the operands would cause it to handle comparisons between positive
21145 // and negative zero incorrectly.
21146 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21147 if (!DAG.getTarget().Options.UnsafeFPMath &&
21148 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21150 std::swap(LHS, RHS);
21152 Opcode = X86ISD::FMAX;
21155 // Converting this to a max would handle both negative zeros and NaNs
21156 // incorrectly, but we can swap the operands to fix both.
21157 std::swap(LHS, RHS);
21161 Opcode = X86ISD::FMAX;
21164 // Check for x CC y ? y : x -- a min/max with reversed arms.
21165 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21166 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21170 // Converting this to a min would handle comparisons between positive
21171 // and negative zero incorrectly, and swapping the operands would
21172 // cause it to handle NaNs incorrectly.
21173 if (!DAG.getTarget().Options.UnsafeFPMath &&
21174 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21175 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21177 std::swap(LHS, RHS);
21179 Opcode = X86ISD::FMIN;
21182 // Converting this to a min would handle NaNs incorrectly.
21183 if (!DAG.getTarget().Options.UnsafeFPMath &&
21184 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21186 Opcode = X86ISD::FMIN;
21189 // Converting this to a min would handle both negative zeros and NaNs
21190 // incorrectly, but we can swap the operands to fix both.
21191 std::swap(LHS, RHS);
21195 Opcode = X86ISD::FMIN;
21199 // Converting this to a max would handle NaNs incorrectly.
21200 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21202 Opcode = X86ISD::FMAX;
21205 // Converting this to a max would handle comparisons between positive
21206 // and negative zero incorrectly, and swapping the operands would
21207 // cause it to handle NaNs incorrectly.
21208 if (!DAG.getTarget().Options.UnsafeFPMath &&
21209 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21210 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21212 std::swap(LHS, RHS);
21214 Opcode = X86ISD::FMAX;
21217 // Converting this to a max would handle both negative zeros and NaNs
21218 // incorrectly, but we can swap the operands to fix both.
21219 std::swap(LHS, RHS);
21223 Opcode = X86ISD::FMAX;
21229 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21232 EVT CondVT = Cond.getValueType();
21233 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21234 CondVT.getVectorElementType() == MVT::i1) {
21235 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21236 // lowering on KNL. In this case we convert it to
21237 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21238 // The same situation for all 128 and 256-bit vectors of i8 and i16.
21239 // Since SKX these selects have a proper lowering.
21240 EVT OpVT = LHS.getValueType();
21241 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21242 (OpVT.getVectorElementType() == MVT::i8 ||
21243 OpVT.getVectorElementType() == MVT::i16) &&
21244 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21245 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21246 DCI.AddToWorklist(Cond.getNode());
21247 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21250 // If this is a select between two integer constants, try to do some
21252 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21253 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21254 // Don't do this for crazy integer types.
21255 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21256 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21257 // so that TrueC (the true value) is larger than FalseC.
21258 bool NeedsCondInvert = false;
21260 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21261 // Efficiently invertible.
21262 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
21263 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
21264 isa<ConstantSDNode>(Cond.getOperand(1))))) {
21265 NeedsCondInvert = true;
21266 std::swap(TrueC, FalseC);
21269 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
21270 if (FalseC->getAPIntValue() == 0 &&
21271 TrueC->getAPIntValue().isPowerOf2()) {
21272 if (NeedsCondInvert) // Invert the condition if needed.
21273 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21274 DAG.getConstant(1, DL, Cond.getValueType()));
21276 // Zero extend the condition if needed.
21277 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21279 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21280 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21281 DAG.getConstant(ShAmt, DL, MVT::i8));
21284 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21285 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21286 if (NeedsCondInvert) // Invert the condition if needed.
21287 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21288 DAG.getConstant(1, DL, Cond.getValueType()));
21290 // Zero extend the condition if needed.
21291 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21292 FalseC->getValueType(0), Cond);
21293 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21294 SDValue(FalseC, 0));
21297 // Optimize cases that will turn into an LEA instruction. This requires
21298 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21299 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21300 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21301 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21303 bool isFastMultiplier = false;
21305 switch ((unsigned char)Diff) {
21307 case 1: // result = add base, cond
21308 case 2: // result = lea base( , cond*2)
21309 case 3: // result = lea base(cond, cond*2)
21310 case 4: // result = lea base( , cond*4)
21311 case 5: // result = lea base(cond, cond*4)
21312 case 8: // result = lea base( , cond*8)
21313 case 9: // result = lea base(cond, cond*8)
21314 isFastMultiplier = true;
21319 if (isFastMultiplier) {
21320 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21321 if (NeedsCondInvert) // Invert the condition if needed.
21322 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21323 DAG.getConstant(1, DL, Cond.getValueType()));
21325 // Zero extend the condition if needed.
21326 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21328 // Scale the condition by the difference.
21330 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21331 DAG.getConstant(Diff, DL,
21332 Cond.getValueType()));
21334 // Add the base if non-zero.
21335 if (FalseC->getAPIntValue() != 0)
21336 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21337 SDValue(FalseC, 0));
21344 // Canonicalize max and min:
21345 // (x > y) ? x : y -> (x >= y) ? x : y
21346 // (x < y) ? x : y -> (x <= y) ? x : y
21347 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21348 // the need for an extra compare
21349 // against zero. e.g.
21350 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21352 // testl %edi, %edi
21354 // cmovgl %edi, %eax
21358 // cmovsl %eax, %edi
21359 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21360 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21361 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21362 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21367 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21368 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21369 Cond.getOperand(0), Cond.getOperand(1), NewCC);
21370 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21375 // Early exit check
21376 if (!TLI.isTypeLegal(VT))
21379 // Match VSELECTs into subs with unsigned saturation.
21380 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21381 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21382 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21383 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21384 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21386 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21387 // left side invert the predicate to simplify logic below.
21389 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21391 CC = ISD::getSetCCInverse(CC, true);
21392 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21396 if (Other.getNode() && Other->getNumOperands() == 2 &&
21397 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21398 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21399 SDValue CondRHS = Cond->getOperand(1);
21401 // Look for a general sub with unsigned saturation first.
21402 // x >= y ? x-y : 0 --> subus x, y
21403 // x > y ? x-y : 0 --> subus x, y
21404 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21405 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21406 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21408 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21409 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21410 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21411 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21412 // If the RHS is a constant we have to reverse the const
21413 // canonicalization.
21414 // x > C-1 ? x+-C : 0 --> subus x, C
21415 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21416 CondRHSConst->getAPIntValue() ==
21417 (-OpRHSConst->getAPIntValue() - 1))
21418 return DAG.getNode(
21419 X86ISD::SUBUS, DL, VT, OpLHS,
21420 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
21422 // Another special case: If C was a sign bit, the sub has been
21423 // canonicalized into a xor.
21424 // FIXME: Would it be better to use computeKnownBits to determine
21425 // whether it's safe to decanonicalize the xor?
21426 // x s< 0 ? x^C : 0 --> subus x, C
21427 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21428 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21429 OpRHSConst->getAPIntValue().isSignBit())
21430 // Note that we have to rebuild the RHS constant here to ensure we
21431 // don't rely on particular values of undef lanes.
21432 return DAG.getNode(
21433 X86ISD::SUBUS, DL, VT, OpLHS,
21434 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
21439 // Try to match a min/max vector operation.
21440 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21441 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21442 unsigned Opc = ret.first;
21443 bool NeedSplit = ret.second;
21445 if (Opc && NeedSplit) {
21446 unsigned NumElems = VT.getVectorNumElements();
21447 // Extract the LHS vectors
21448 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21449 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21451 // Extract the RHS vectors
21452 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21453 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21455 // Create min/max for each subvector
21456 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21457 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21459 // Merge the result
21460 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21462 return DAG.getNode(Opc, DL, VT, LHS, RHS);
21465 // Simplify vector selection if condition value type matches vselect
21467 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
21468 assert(Cond.getValueType().isVector() &&
21469 "vector select expects a vector selector!");
21471 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21472 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21474 // Try invert the condition if true value is not all 1s and false value
21476 if (!TValIsAllOnes && !FValIsAllZeros &&
21477 // Check if the selector will be produced by CMPP*/PCMP*
21478 Cond.getOpcode() == ISD::SETCC &&
21479 // Check if SETCC has already been promoted
21480 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
21481 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21482 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21484 if (TValIsAllZeros || FValIsAllOnes) {
21485 SDValue CC = Cond.getOperand(2);
21486 ISD::CondCode NewCC =
21487 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21488 Cond.getOperand(0).getValueType().isInteger());
21489 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21490 std::swap(LHS, RHS);
21491 TValIsAllOnes = FValIsAllOnes;
21492 FValIsAllZeros = TValIsAllZeros;
21496 if (TValIsAllOnes || FValIsAllZeros) {
21499 if (TValIsAllOnes && FValIsAllZeros)
21501 else if (TValIsAllOnes)
21502 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21503 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21504 else if (FValIsAllZeros)
21505 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21506 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21508 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21512 // We should generate an X86ISD::BLENDI from a vselect if its argument
21513 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21514 // constants. This specific pattern gets generated when we split a
21515 // selector for a 512 bit vector in a machine without AVX512 (but with
21516 // 256-bit vectors), during legalization:
21518 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21520 // Iff we find this pattern and the build_vectors are built from
21521 // constants, we translate the vselect into a shuffle_vector that we
21522 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21523 if ((N->getOpcode() == ISD::VSELECT ||
21524 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
21525 !DCI.isBeforeLegalize()) {
21526 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21527 if (Shuffle.getNode())
21531 // If this is a *dynamic* select (non-constant condition) and we can match
21532 // this node with one of the variable blend instructions, restructure the
21533 // condition so that the blends can use the high bit of each element and use
21534 // SimplifyDemandedBits to simplify the condition operand.
21535 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21536 !DCI.isBeforeLegalize() &&
21537 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
21538 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21540 // Don't optimize vector selects that map to mask-registers.
21544 // We can only handle the cases where VSELECT is directly legal on the
21545 // subtarget. We custom lower VSELECT nodes with constant conditions and
21546 // this makes it hard to see whether a dynamic VSELECT will correctly
21547 // lower, so we both check the operation's status and explicitly handle the
21548 // cases where a *dynamic* blend will fail even though a constant-condition
21549 // blend could be custom lowered.
21550 // FIXME: We should find a better way to handle this class of problems.
21551 // Potentially, we should combine constant-condition vselect nodes
21552 // pre-legalization into shuffles and not mark as many types as custom
21554 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
21556 // FIXME: We don't support i16-element blends currently. We could and
21557 // should support them by making *all* the bits in the condition be set
21558 // rather than just the high bit and using an i8-element blend.
21559 if (VT.getScalarType() == MVT::i16)
21561 // Dynamic blending was only available from SSE4.1 onward.
21562 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
21564 // Byte blends are only available in AVX2
21565 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
21566 !Subtarget->hasAVX2())
21569 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21570 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21572 APInt KnownZero, KnownOne;
21573 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21574 DCI.isBeforeLegalizeOps());
21575 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21576 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
21578 // If we changed the computation somewhere in the DAG, this change
21579 // will affect all users of Cond.
21580 // Make sure it is fine and update all the nodes so that we do not
21581 // use the generic VSELECT anymore. Otherwise, we may perform
21582 // wrong optimizations as we messed up with the actual expectation
21583 // for the vector boolean values.
21584 if (Cond != TLO.Old) {
21585 // Check all uses of that condition operand to check whether it will be
21586 // consumed by non-BLEND instructions, which may depend on all bits are
21588 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21590 if (I->getOpcode() != ISD::VSELECT)
21591 // TODO: Add other opcodes eventually lowered into BLEND.
21594 // Update all the users of the condition, before committing the change,
21595 // so that the VSELECT optimizations that expect the correct vector
21596 // boolean value will not be triggered.
21597 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
21599 DAG.ReplaceAllUsesOfValueWith(
21601 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
21602 Cond, I->getOperand(1), I->getOperand(2)));
21603 DCI.CommitTargetLoweringOpt(TLO);
21606 // At this point, only Cond is changed. Change the condition
21607 // just for N to keep the opportunity to optimize all other
21608 // users their own way.
21609 DAG.ReplaceAllUsesOfValueWith(
21611 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
21612 TLO.New, N->getOperand(1), N->getOperand(2)));
21620 // Check whether a boolean test is testing a boolean value generated by
21621 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21624 // Simplify the following patterns:
21625 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21626 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21627 // to (Op EFLAGS Cond)
21629 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21630 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21631 // to (Op EFLAGS !Cond)
21633 // where Op could be BRCOND or CMOV.
21635 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21636 // Quit if not CMP and SUB with its value result used.
21637 if (Cmp.getOpcode() != X86ISD::CMP &&
21638 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21641 // Quit if not used as a boolean value.
21642 if (CC != X86::COND_E && CC != X86::COND_NE)
21645 // Check CMP operands. One of them should be 0 or 1 and the other should be
21646 // an SetCC or extended from it.
21647 SDValue Op1 = Cmp.getOperand(0);
21648 SDValue Op2 = Cmp.getOperand(1);
21651 const ConstantSDNode* C = nullptr;
21652 bool needOppositeCond = (CC == X86::COND_E);
21653 bool checkAgainstTrue = false; // Is it a comparison against 1?
21655 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21657 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21659 else // Quit if all operands are not constants.
21662 if (C->getZExtValue() == 1) {
21663 needOppositeCond = !needOppositeCond;
21664 checkAgainstTrue = true;
21665 } else if (C->getZExtValue() != 0)
21666 // Quit if the constant is neither 0 or 1.
21669 bool truncatedToBoolWithAnd = false;
21670 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21671 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21672 SetCC.getOpcode() == ISD::TRUNCATE ||
21673 SetCC.getOpcode() == ISD::AND) {
21674 if (SetCC.getOpcode() == ISD::AND) {
21676 ConstantSDNode *CS;
21677 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21678 CS->getZExtValue() == 1)
21680 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21681 CS->getZExtValue() == 1)
21685 SetCC = SetCC.getOperand(OpIdx);
21686 truncatedToBoolWithAnd = true;
21688 SetCC = SetCC.getOperand(0);
21691 switch (SetCC.getOpcode()) {
21692 case X86ISD::SETCC_CARRY:
21693 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21694 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21695 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21696 // truncated to i1 using 'and'.
21697 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21699 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21700 "Invalid use of SETCC_CARRY!");
21702 case X86ISD::SETCC:
21703 // Set the condition code or opposite one if necessary.
21704 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21705 if (needOppositeCond)
21706 CC = X86::GetOppositeBranchCondition(CC);
21707 return SetCC.getOperand(1);
21708 case X86ISD::CMOV: {
21709 // Check whether false/true value has canonical one, i.e. 0 or 1.
21710 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21711 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21712 // Quit if true value is not a constant.
21715 // Quit if false value is not a constant.
21717 SDValue Op = SetCC.getOperand(0);
21718 // Skip 'zext' or 'trunc' node.
21719 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21720 Op.getOpcode() == ISD::TRUNCATE)
21721 Op = Op.getOperand(0);
21722 // A special case for rdrand/rdseed, where 0 is set if false cond is
21724 if ((Op.getOpcode() != X86ISD::RDRAND &&
21725 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21728 // Quit if false value is not the constant 0 or 1.
21729 bool FValIsFalse = true;
21730 if (FVal && FVal->getZExtValue() != 0) {
21731 if (FVal->getZExtValue() != 1)
21733 // If FVal is 1, opposite cond is needed.
21734 needOppositeCond = !needOppositeCond;
21735 FValIsFalse = false;
21737 // Quit if TVal is not the constant opposite of FVal.
21738 if (FValIsFalse && TVal->getZExtValue() != 1)
21740 if (!FValIsFalse && TVal->getZExtValue() != 0)
21742 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21743 if (needOppositeCond)
21744 CC = X86::GetOppositeBranchCondition(CC);
21745 return SetCC.getOperand(3);
21752 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
21754 /// (X86or (X86setcc) (X86setcc))
21755 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
21756 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
21757 X86::CondCode &CC1, SDValue &Flags,
21759 if (Cond->getOpcode() == X86ISD::CMP) {
21760 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
21761 if (!CondOp1C || !CondOp1C->isNullValue())
21764 Cond = Cond->getOperand(0);
21769 SDValue SetCC0, SetCC1;
21770 switch (Cond->getOpcode()) {
21771 default: return false;
21778 SetCC0 = Cond->getOperand(0);
21779 SetCC1 = Cond->getOperand(1);
21783 // Make sure we have SETCC nodes, using the same flags value.
21784 if (SetCC0.getOpcode() != X86ISD::SETCC ||
21785 SetCC1.getOpcode() != X86ISD::SETCC ||
21786 SetCC0->getOperand(1) != SetCC1->getOperand(1))
21789 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
21790 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
21791 Flags = SetCC0->getOperand(1);
21795 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21796 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21797 TargetLowering::DAGCombinerInfo &DCI,
21798 const X86Subtarget *Subtarget) {
21801 // If the flag operand isn't dead, don't touch this CMOV.
21802 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21805 SDValue FalseOp = N->getOperand(0);
21806 SDValue TrueOp = N->getOperand(1);
21807 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21808 SDValue Cond = N->getOperand(3);
21810 if (CC == X86::COND_E || CC == X86::COND_NE) {
21811 switch (Cond.getOpcode()) {
21815 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21816 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21817 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21823 Flags = checkBoolTestSetCCCombine(Cond, CC);
21824 if (Flags.getNode() &&
21825 // Extra check as FCMOV only supports a subset of X86 cond.
21826 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21827 SDValue Ops[] = { FalseOp, TrueOp,
21828 DAG.getConstant(CC, DL, MVT::i8), Flags };
21829 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21832 // If this is a select between two integer constants, try to do some
21833 // optimizations. Note that the operands are ordered the opposite of SELECT
21835 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21836 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21837 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21838 // larger than FalseC (the false value).
21839 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21840 CC = X86::GetOppositeBranchCondition(CC);
21841 std::swap(TrueC, FalseC);
21842 std::swap(TrueOp, FalseOp);
21845 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21846 // This is efficient for any integer data type (including i8/i16) and
21848 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21849 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21850 DAG.getConstant(CC, DL, MVT::i8), Cond);
21852 // Zero extend the condition if needed.
21853 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21855 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21856 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21857 DAG.getConstant(ShAmt, DL, MVT::i8));
21858 if (N->getNumValues() == 2) // Dead flag value?
21859 return DCI.CombineTo(N, Cond, SDValue());
21863 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21864 // for any integer data type, including i8/i16.
21865 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21866 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21867 DAG.getConstant(CC, DL, MVT::i8), Cond);
21869 // Zero extend the condition if needed.
21870 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21871 FalseC->getValueType(0), Cond);
21872 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21873 SDValue(FalseC, 0));
21875 if (N->getNumValues() == 2) // Dead flag value?
21876 return DCI.CombineTo(N, Cond, SDValue());
21880 // Optimize cases that will turn into an LEA instruction. This requires
21881 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21882 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21883 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21884 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21886 bool isFastMultiplier = false;
21888 switch ((unsigned char)Diff) {
21890 case 1: // result = add base, cond
21891 case 2: // result = lea base( , cond*2)
21892 case 3: // result = lea base(cond, cond*2)
21893 case 4: // result = lea base( , cond*4)
21894 case 5: // result = lea base(cond, cond*4)
21895 case 8: // result = lea base( , cond*8)
21896 case 9: // result = lea base(cond, cond*8)
21897 isFastMultiplier = true;
21902 if (isFastMultiplier) {
21903 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21904 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21905 DAG.getConstant(CC, DL, MVT::i8), Cond);
21906 // Zero extend the condition if needed.
21907 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21909 // Scale the condition by the difference.
21911 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21912 DAG.getConstant(Diff, DL, Cond.getValueType()));
21914 // Add the base if non-zero.
21915 if (FalseC->getAPIntValue() != 0)
21916 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21917 SDValue(FalseC, 0));
21918 if (N->getNumValues() == 2) // Dead flag value?
21919 return DCI.CombineTo(N, Cond, SDValue());
21926 // Handle these cases:
21927 // (select (x != c), e, c) -> select (x != c), e, x),
21928 // (select (x == c), c, e) -> select (x == c), x, e)
21929 // where the c is an integer constant, and the "select" is the combination
21930 // of CMOV and CMP.
21932 // The rationale for this change is that the conditional-move from a constant
21933 // needs two instructions, however, conditional-move from a register needs
21934 // only one instruction.
21936 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21937 // some instruction-combining opportunities. This opt needs to be
21938 // postponed as late as possible.
21940 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21941 // the DCI.xxxx conditions are provided to postpone the optimization as
21942 // late as possible.
21944 ConstantSDNode *CmpAgainst = nullptr;
21945 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21946 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21947 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21949 if (CC == X86::COND_NE &&
21950 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21951 CC = X86::GetOppositeBranchCondition(CC);
21952 std::swap(TrueOp, FalseOp);
21955 if (CC == X86::COND_E &&
21956 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21957 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21958 DAG.getConstant(CC, DL, MVT::i8), Cond };
21959 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21964 // Fold and/or of setcc's to double CMOV:
21965 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
21966 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
21968 // This combine lets us generate:
21969 // cmovcc1 (jcc1 if we don't have CMOV)
21975 // cmovne (jne if we don't have CMOV)
21976 // When we can't use the CMOV instruction, it might increase branch
21978 // When we can use CMOV, or when there is no mispredict, this improves
21979 // throughput and reduces register pressure.
21981 if (CC == X86::COND_NE) {
21983 X86::CondCode CC0, CC1;
21985 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
21987 std::swap(FalseOp, TrueOp);
21988 CC0 = X86::GetOppositeBranchCondition(CC0);
21989 CC1 = X86::GetOppositeBranchCondition(CC1);
21992 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
21994 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
21995 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
21996 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21997 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22005 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22006 const X86Subtarget *Subtarget) {
22007 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22009 default: return SDValue();
22010 // SSE/AVX/AVX2 blend intrinsics.
22011 case Intrinsic::x86_avx2_pblendvb:
22012 // Don't try to simplify this intrinsic if we don't have AVX2.
22013 if (!Subtarget->hasAVX2())
22016 case Intrinsic::x86_avx_blendv_pd_256:
22017 case Intrinsic::x86_avx_blendv_ps_256:
22018 // Don't try to simplify this intrinsic if we don't have AVX.
22019 if (!Subtarget->hasAVX())
22022 case Intrinsic::x86_sse41_blendvps:
22023 case Intrinsic::x86_sse41_blendvpd:
22024 case Intrinsic::x86_sse41_pblendvb: {
22025 SDValue Op0 = N->getOperand(1);
22026 SDValue Op1 = N->getOperand(2);
22027 SDValue Mask = N->getOperand(3);
22029 // Don't try to simplify this intrinsic if we don't have SSE4.1.
22030 if (!Subtarget->hasSSE41())
22033 // fold (blend A, A, Mask) -> A
22036 // fold (blend A, B, allZeros) -> A
22037 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22039 // fold (blend A, B, allOnes) -> B
22040 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22043 // Simplify the case where the mask is a constant i32 value.
22044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22045 if (C->isNullValue())
22047 if (C->isAllOnesValue())
22054 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22055 case Intrinsic::x86_sse2_psrai_w:
22056 case Intrinsic::x86_sse2_psrai_d:
22057 case Intrinsic::x86_avx2_psrai_w:
22058 case Intrinsic::x86_avx2_psrai_d:
22059 case Intrinsic::x86_sse2_psra_w:
22060 case Intrinsic::x86_sse2_psra_d:
22061 case Intrinsic::x86_avx2_psra_w:
22062 case Intrinsic::x86_avx2_psra_d: {
22063 SDValue Op0 = N->getOperand(1);
22064 SDValue Op1 = N->getOperand(2);
22065 EVT VT = Op0.getValueType();
22066 assert(VT.isVector() && "Expected a vector type!");
22068 if (isa<BuildVectorSDNode>(Op1))
22069 Op1 = Op1.getOperand(0);
22071 if (!isa<ConstantSDNode>(Op1))
22074 EVT SVT = VT.getVectorElementType();
22075 unsigned SVTBits = SVT.getSizeInBits();
22077 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22078 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22079 uint64_t ShAmt = C.getZExtValue();
22081 // Don't try to convert this shift into a ISD::SRA if the shift
22082 // count is bigger than or equal to the element size.
22083 if (ShAmt >= SVTBits)
22086 // Trivial case: if the shift count is zero, then fold this
22087 // into the first operand.
22091 // Replace this packed shift intrinsic with a target independent
22094 SDValue Splat = DAG.getConstant(C, DL, VT);
22095 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22100 /// PerformMulCombine - Optimize a single multiply with constant into two
22101 /// in order to implement it with two cheaper instructions, e.g.
22102 /// LEA + SHL, LEA + LEA.
22103 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22104 TargetLowering::DAGCombinerInfo &DCI) {
22105 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22108 EVT VT = N->getValueType(0);
22109 if (VT != MVT::i64 && VT != MVT::i32)
22112 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22115 uint64_t MulAmt = C->getZExtValue();
22116 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22119 uint64_t MulAmt1 = 0;
22120 uint64_t MulAmt2 = 0;
22121 if ((MulAmt % 9) == 0) {
22123 MulAmt2 = MulAmt / 9;
22124 } else if ((MulAmt % 5) == 0) {
22126 MulAmt2 = MulAmt / 5;
22127 } else if ((MulAmt % 3) == 0) {
22129 MulAmt2 = MulAmt / 3;
22132 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22135 if (isPowerOf2_64(MulAmt2) &&
22136 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22137 // If second multiplifer is pow2, issue it first. We want the multiply by
22138 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22140 std::swap(MulAmt1, MulAmt2);
22143 if (isPowerOf2_64(MulAmt1))
22144 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22145 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22147 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22148 DAG.getConstant(MulAmt1, DL, VT));
22150 if (isPowerOf2_64(MulAmt2))
22151 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22152 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22154 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22155 DAG.getConstant(MulAmt2, DL, VT));
22157 // Do not add new nodes to DAG combiner worklist.
22158 DCI.CombineTo(N, NewMul, false);
22163 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22164 SDValue N0 = N->getOperand(0);
22165 SDValue N1 = N->getOperand(1);
22166 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22167 EVT VT = N0.getValueType();
22169 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22170 // since the result of setcc_c is all zero's or all ones.
22171 if (VT.isInteger() && !VT.isVector() &&
22172 N1C && N0.getOpcode() == ISD::AND &&
22173 N0.getOperand(1).getOpcode() == ISD::Constant) {
22174 SDValue N00 = N0.getOperand(0);
22175 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22176 ((N00.getOpcode() == ISD::ANY_EXTEND ||
22177 N00.getOpcode() == ISD::ZERO_EXTEND) &&
22178 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22179 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22180 APInt ShAmt = N1C->getAPIntValue();
22181 Mask = Mask.shl(ShAmt);
22184 return DAG.getNode(ISD::AND, DL, VT,
22185 N00, DAG.getConstant(Mask, DL, VT));
22190 // Hardware support for vector shifts is sparse which makes us scalarize the
22191 // vector operations in many cases. Also, on sandybridge ADD is faster than
22193 // (shl V, 1) -> add V,V
22194 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22195 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22196 assert(N0.getValueType().isVector() && "Invalid vector shift type");
22197 // We shift all of the values by one. In many cases we do not have
22198 // hardware support for this operation. This is better expressed as an ADD
22200 if (N1SplatC->getZExtValue() == 1)
22201 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22207 /// \brief Returns a vector of 0s if the node in input is a vector logical
22208 /// shift by a constant amount which is known to be bigger than or equal
22209 /// to the vector element size in bits.
22210 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22211 const X86Subtarget *Subtarget) {
22212 EVT VT = N->getValueType(0);
22214 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22215 (!Subtarget->hasInt256() ||
22216 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22219 SDValue Amt = N->getOperand(1);
22221 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22222 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22223 APInt ShiftAmt = AmtSplat->getAPIntValue();
22224 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22226 // SSE2/AVX2 logical shifts always return a vector of 0s
22227 // if the shift amount is bigger than or equal to
22228 // the element size. The constant shift amount will be
22229 // encoded as a 8-bit immediate.
22230 if (ShiftAmt.trunc(8).uge(MaxAmount))
22231 return getZeroVector(VT, Subtarget, DAG, DL);
22237 /// PerformShiftCombine - Combine shifts.
22238 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22239 TargetLowering::DAGCombinerInfo &DCI,
22240 const X86Subtarget *Subtarget) {
22241 if (N->getOpcode() == ISD::SHL) {
22242 SDValue V = PerformSHLCombine(N, DAG);
22243 if (V.getNode()) return V;
22246 if (N->getOpcode() != ISD::SRA) {
22247 // Try to fold this logical shift into a zero vector.
22248 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22249 if (V.getNode()) return V;
22255 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
22256 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22257 // and friends. Likewise for OR -> CMPNEQSS.
22258 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22259 TargetLowering::DAGCombinerInfo &DCI,
22260 const X86Subtarget *Subtarget) {
22263 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22264 // we're requiring SSE2 for both.
22265 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22266 SDValue N0 = N->getOperand(0);
22267 SDValue N1 = N->getOperand(1);
22268 SDValue CMP0 = N0->getOperand(1);
22269 SDValue CMP1 = N1->getOperand(1);
22272 // The SETCCs should both refer to the same CMP.
22273 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22276 SDValue CMP00 = CMP0->getOperand(0);
22277 SDValue CMP01 = CMP0->getOperand(1);
22278 EVT VT = CMP00.getValueType();
22280 if (VT == MVT::f32 || VT == MVT::f64) {
22281 bool ExpectingFlags = false;
22282 // Check for any users that want flags:
22283 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22284 !ExpectingFlags && UI != UE; ++UI)
22285 switch (UI->getOpcode()) {
22290 ExpectingFlags = true;
22292 case ISD::CopyToReg:
22293 case ISD::SIGN_EXTEND:
22294 case ISD::ZERO_EXTEND:
22295 case ISD::ANY_EXTEND:
22299 if (!ExpectingFlags) {
22300 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22301 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22303 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22304 X86::CondCode tmp = cc0;
22309 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
22310 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22311 // FIXME: need symbolic constants for these magic numbers.
22312 // See X86ATTInstPrinter.cpp:printSSECC().
22313 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22314 if (Subtarget->hasAVX512()) {
22315 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22317 DAG.getConstant(x86cc, DL, MVT::i8));
22318 if (N->getValueType(0) != MVT::i1)
22319 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22323 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22324 CMP00.getValueType(), CMP00, CMP01,
22325 DAG.getConstant(x86cc, DL,
22328 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22329 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22331 if (is64BitFP && !Subtarget->is64Bit()) {
22332 // On a 32-bit target, we cannot bitcast the 64-bit float to a
22333 // 64-bit integer, since that's not a legal type. Since
22334 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22335 // bits, but can do this little dance to extract the lowest 32 bits
22336 // and work with those going forward.
22337 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22339 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22341 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22342 Vector32, DAG.getIntPtrConstant(0, DL));
22346 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT,
22348 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22349 DAG.getConstant(1, DL, IntVT));
22350 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
22352 return OneBitOfTruth;
22360 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22361 /// so it can be folded inside ANDNP.
22362 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22363 EVT VT = N->getValueType(0);
22365 // Match direct AllOnes for 128 and 256-bit vectors
22366 if (ISD::isBuildVectorAllOnes(N))
22369 // Look through a bit convert.
22370 if (N->getOpcode() == ISD::BITCAST)
22371 N = N->getOperand(0).getNode();
22373 // Sometimes the operand may come from a insert_subvector building a 256-bit
22375 if (VT.is256BitVector() &&
22376 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22377 SDValue V1 = N->getOperand(0);
22378 SDValue V2 = N->getOperand(1);
22380 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22381 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22382 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22383 ISD::isBuildVectorAllOnes(V2.getNode()))
22390 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22391 // register. In most cases we actually compare or select YMM-sized registers
22392 // and mixing the two types creates horrible code. This method optimizes
22393 // some of the transition sequences.
22394 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22395 TargetLowering::DAGCombinerInfo &DCI,
22396 const X86Subtarget *Subtarget) {
22397 EVT VT = N->getValueType(0);
22398 if (!VT.is256BitVector())
22401 assert((N->getOpcode() == ISD::ANY_EXTEND ||
22402 N->getOpcode() == ISD::ZERO_EXTEND ||
22403 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22405 SDValue Narrow = N->getOperand(0);
22406 EVT NarrowVT = Narrow->getValueType(0);
22407 if (!NarrowVT.is128BitVector())
22410 if (Narrow->getOpcode() != ISD::XOR &&
22411 Narrow->getOpcode() != ISD::AND &&
22412 Narrow->getOpcode() != ISD::OR)
22415 SDValue N0 = Narrow->getOperand(0);
22416 SDValue N1 = Narrow->getOperand(1);
22419 // The Left side has to be a trunc.
22420 if (N0.getOpcode() != ISD::TRUNCATE)
22423 // The type of the truncated inputs.
22424 EVT WideVT = N0->getOperand(0)->getValueType(0);
22428 // The right side has to be a 'trunc' or a constant vector.
22429 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22430 ConstantSDNode *RHSConstSplat = nullptr;
22431 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22432 RHSConstSplat = RHSBV->getConstantSplatNode();
22433 if (!RHSTrunc && !RHSConstSplat)
22436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22438 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22441 // Set N0 and N1 to hold the inputs to the new wide operation.
22442 N0 = N0->getOperand(0);
22443 if (RHSConstSplat) {
22444 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22445 SDValue(RHSConstSplat, 0));
22446 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22447 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22448 } else if (RHSTrunc) {
22449 N1 = N1->getOperand(0);
22452 // Generate the wide operation.
22453 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22454 unsigned Opcode = N->getOpcode();
22456 case ISD::ANY_EXTEND:
22458 case ISD::ZERO_EXTEND: {
22459 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22460 APInt Mask = APInt::getAllOnesValue(InBits);
22461 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22462 return DAG.getNode(ISD::AND, DL, VT,
22463 Op, DAG.getConstant(Mask, DL, VT));
22465 case ISD::SIGN_EXTEND:
22466 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22467 Op, DAG.getValueType(NarrowVT));
22469 llvm_unreachable("Unexpected opcode");
22473 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
22474 TargetLowering::DAGCombinerInfo &DCI,
22475 const X86Subtarget *Subtarget) {
22476 SDValue N0 = N->getOperand(0);
22477 SDValue N1 = N->getOperand(1);
22480 // A vector zext_in_reg may be represented as a shuffle,
22481 // feeding into a bitcast (this represents anyext) feeding into
22482 // an and with a mask.
22483 // We'd like to try to combine that into a shuffle with zero
22484 // plus a bitcast, removing the and.
22485 if (N0.getOpcode() != ISD::BITCAST ||
22486 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
22489 // The other side of the AND should be a splat of 2^C, where C
22490 // is the number of bits in the source type.
22491 if (N1.getOpcode() == ISD::BITCAST)
22492 N1 = N1.getOperand(0);
22493 if (N1.getOpcode() != ISD::BUILD_VECTOR)
22495 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
22497 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
22498 EVT SrcType = Shuffle->getValueType(0);
22500 // We expect a single-source shuffle
22501 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
22504 unsigned SrcSize = SrcType.getScalarSizeInBits();
22506 APInt SplatValue, SplatUndef;
22507 unsigned SplatBitSize;
22509 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
22510 SplatBitSize, HasAnyUndefs))
22513 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
22514 // Make sure the splat matches the mask we expect
22515 if (SplatBitSize > ResSize ||
22516 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
22519 // Make sure the input and output size make sense
22520 if (SrcSize >= ResSize || ResSize % SrcSize)
22523 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
22524 // The number of u's between each two values depends on the ratio between
22525 // the source and dest type.
22526 unsigned ZextRatio = ResSize / SrcSize;
22527 bool IsZext = true;
22528 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
22529 if (i % ZextRatio) {
22530 if (Shuffle->getMaskElt(i) > 0) {
22536 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
22537 // Expected element number
22547 // Ok, perform the transformation - replace the shuffle with
22548 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
22549 // (instead of undef) where the k elements come from the zero vector.
22550 SmallVector<int, 8> Mask;
22551 unsigned NumElems = SrcType.getVectorNumElements();
22552 for (unsigned i = 0; i < NumElems; ++i)
22554 Mask.push_back(NumElems);
22556 Mask.push_back(i / ZextRatio);
22558 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
22559 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
22560 return DAG.getNode(ISD::BITCAST, DL, N0.getValueType(), NewShuffle);
22563 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22564 TargetLowering::DAGCombinerInfo &DCI,
22565 const X86Subtarget *Subtarget) {
22566 if (DCI.isBeforeLegalizeOps())
22569 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
22572 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
22575 EVT VT = N->getValueType(0);
22576 SDValue N0 = N->getOperand(0);
22577 SDValue N1 = N->getOperand(1);
22580 // Create BEXTR instructions
22581 // BEXTR is ((X >> imm) & (2**size-1))
22582 if (VT == MVT::i32 || VT == MVT::i64) {
22583 // Check for BEXTR.
22584 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22585 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22586 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22587 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22588 if (MaskNode && ShiftNode) {
22589 uint64_t Mask = MaskNode->getZExtValue();
22590 uint64_t Shift = ShiftNode->getZExtValue();
22591 if (isMask_64(Mask)) {
22592 uint64_t MaskSize = countPopulation(Mask);
22593 if (Shift + MaskSize <= VT.getSizeInBits())
22594 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22595 DAG.getConstant(Shift | (MaskSize << 8), DL,
22604 // Want to form ANDNP nodes:
22605 // 1) In the hopes of then easily combining them with OR and AND nodes
22606 // to form PBLEND/PSIGN.
22607 // 2) To match ANDN packed intrinsics
22608 if (VT != MVT::v2i64 && VT != MVT::v4i64)
22611 // Check LHS for vnot
22612 if (N0.getOpcode() == ISD::XOR &&
22613 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22614 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22615 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22617 // Check RHS for vnot
22618 if (N1.getOpcode() == ISD::XOR &&
22619 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22620 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22621 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22626 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22627 TargetLowering::DAGCombinerInfo &DCI,
22628 const X86Subtarget *Subtarget) {
22629 if (DCI.isBeforeLegalizeOps())
22632 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22636 SDValue N0 = N->getOperand(0);
22637 SDValue N1 = N->getOperand(1);
22638 EVT VT = N->getValueType(0);
22640 // look for psign/blend
22641 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22642 if (!Subtarget->hasSSSE3() ||
22643 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22646 // Canonicalize pandn to RHS
22647 if (N0.getOpcode() == X86ISD::ANDNP)
22649 // or (and (m, y), (pandn m, x))
22650 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22651 SDValue Mask = N1.getOperand(0);
22652 SDValue X = N1.getOperand(1);
22654 if (N0.getOperand(0) == Mask)
22655 Y = N0.getOperand(1);
22656 if (N0.getOperand(1) == Mask)
22657 Y = N0.getOperand(0);
22659 // Check to see if the mask appeared in both the AND and ANDNP and
22663 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22664 // Look through mask bitcast.
22665 if (Mask.getOpcode() == ISD::BITCAST)
22666 Mask = Mask.getOperand(0);
22667 if (X.getOpcode() == ISD::BITCAST)
22668 X = X.getOperand(0);
22669 if (Y.getOpcode() == ISD::BITCAST)
22670 Y = Y.getOperand(0);
22672 EVT MaskVT = Mask.getValueType();
22674 // Validate that the Mask operand is a vector sra node.
22675 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22676 // there is no psrai.b
22677 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22678 unsigned SraAmt = ~0;
22679 if (Mask.getOpcode() == ISD::SRA) {
22680 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22681 if (auto *AmtConst = AmtBV->getConstantSplatNode())
22682 SraAmt = AmtConst->getZExtValue();
22683 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22684 SDValue SraC = Mask.getOperand(1);
22685 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
22687 if ((SraAmt + 1) != EltBits)
22692 // Now we know we at least have a plendvb with the mask val. See if
22693 // we can form a psignb/w/d.
22694 // psign = x.type == y.type == mask.type && y = sub(0, x);
22695 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22696 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22697 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22698 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22699 "Unsupported VT for PSIGN");
22700 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22701 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22703 // PBLENDVB only available on SSE 4.1
22704 if (!Subtarget->hasSSE41())
22707 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22709 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22710 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22711 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22712 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22713 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22717 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22720 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22721 MachineFunction &MF = DAG.getMachineFunction();
22723 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
22725 // SHLD/SHRD instructions have lower register pressure, but on some
22726 // platforms they have higher latency than the equivalent
22727 // series of shifts/or that would otherwise be generated.
22728 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22729 // have higher latencies and we are not optimizing for size.
22730 if (!OptForSize && Subtarget->isSHLDSlow())
22733 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22735 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22737 if (!N0.hasOneUse() || !N1.hasOneUse())
22740 SDValue ShAmt0 = N0.getOperand(1);
22741 if (ShAmt0.getValueType() != MVT::i8)
22743 SDValue ShAmt1 = N1.getOperand(1);
22744 if (ShAmt1.getValueType() != MVT::i8)
22746 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22747 ShAmt0 = ShAmt0.getOperand(0);
22748 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22749 ShAmt1 = ShAmt1.getOperand(0);
22752 unsigned Opc = X86ISD::SHLD;
22753 SDValue Op0 = N0.getOperand(0);
22754 SDValue Op1 = N1.getOperand(0);
22755 if (ShAmt0.getOpcode() == ISD::SUB) {
22756 Opc = X86ISD::SHRD;
22757 std::swap(Op0, Op1);
22758 std::swap(ShAmt0, ShAmt1);
22761 unsigned Bits = VT.getSizeInBits();
22762 if (ShAmt1.getOpcode() == ISD::SUB) {
22763 SDValue Sum = ShAmt1.getOperand(0);
22764 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22765 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22766 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22767 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22768 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22769 return DAG.getNode(Opc, DL, VT,
22771 DAG.getNode(ISD::TRUNCATE, DL,
22774 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22775 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22777 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22778 return DAG.getNode(Opc, DL, VT,
22779 N0.getOperand(0), N1.getOperand(0),
22780 DAG.getNode(ISD::TRUNCATE, DL,
22787 // Generate NEG and CMOV for integer abs.
22788 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22789 EVT VT = N->getValueType(0);
22791 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22792 // 8-bit integer abs to NEG and CMOV.
22793 if (VT.isInteger() && VT.getSizeInBits() == 8)
22796 SDValue N0 = N->getOperand(0);
22797 SDValue N1 = N->getOperand(1);
22800 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22801 // and change it to SUB and CMOV.
22802 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22803 N0.getOpcode() == ISD::ADD &&
22804 N0.getOperand(1) == N1 &&
22805 N1.getOpcode() == ISD::SRA &&
22806 N1.getOperand(0) == N0.getOperand(0))
22807 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22808 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22809 // Generate SUB & CMOV.
22810 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22811 DAG.getConstant(0, DL, VT), N0.getOperand(0));
22813 SDValue Ops[] = { N0.getOperand(0), Neg,
22814 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
22815 SDValue(Neg.getNode(), 1) };
22816 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22821 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22822 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22823 TargetLowering::DAGCombinerInfo &DCI,
22824 const X86Subtarget *Subtarget) {
22825 if (DCI.isBeforeLegalizeOps())
22828 if (Subtarget->hasCMov()) {
22829 SDValue RV = performIntegerAbsCombine(N, DAG);
22837 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22838 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22839 TargetLowering::DAGCombinerInfo &DCI,
22840 const X86Subtarget *Subtarget) {
22841 LoadSDNode *Ld = cast<LoadSDNode>(N);
22842 EVT RegVT = Ld->getValueType(0);
22843 EVT MemVT = Ld->getMemoryVT();
22845 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22847 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
22848 // into two 16-byte operations.
22849 ISD::LoadExtType Ext = Ld->getExtensionType();
22850 unsigned Alignment = Ld->getAlignment();
22851 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22852 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
22853 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22854 unsigned NumElems = RegVT.getVectorNumElements();
22858 SDValue Ptr = Ld->getBasePtr();
22859 SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
22861 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22863 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22864 Ld->getPointerInfo(), Ld->isVolatile(),
22865 Ld->isNonTemporal(), Ld->isInvariant(),
22867 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22868 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22869 Ld->getPointerInfo(), Ld->isVolatile(),
22870 Ld->isNonTemporal(), Ld->isInvariant(),
22871 std::min(16U, Alignment));
22872 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22874 Load2.getValue(1));
22876 SDValue NewVec = DAG.getUNDEF(RegVT);
22877 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22878 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22879 return DCI.CombineTo(N, NewVec, TF, true);
22885 /// PerformMLOADCombine - Resolve extending loads
22886 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
22887 TargetLowering::DAGCombinerInfo &DCI,
22888 const X86Subtarget *Subtarget) {
22889 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
22890 if (Mld->getExtensionType() != ISD::SEXTLOAD)
22893 EVT VT = Mld->getValueType(0);
22894 unsigned NumElems = VT.getVectorNumElements();
22895 EVT LdVT = Mld->getMemoryVT();
22898 assert(LdVT != VT && "Cannot extend to the same type");
22899 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
22900 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
22901 // From, To sizes and ElemCount must be pow of two
22902 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22903 "Unexpected size for extending masked load");
22905 unsigned SizeRatio = ToSz / FromSz;
22906 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
22908 // Create a type on which we perform the shuffle
22909 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22910 LdVT.getScalarType(), NumElems*SizeRatio);
22911 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22913 // Convert Src0 value
22914 SDValue WideSrc0 = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mld->getSrc0());
22915 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
22916 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22917 for (unsigned i = 0; i != NumElems; ++i)
22918 ShuffleVec[i] = i * SizeRatio;
22920 // Can't shuffle using an illegal type.
22921 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
22922 && "WideVecVT should be legal");
22923 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
22924 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
22926 // Prepare the new mask
22928 SDValue Mask = Mld->getMask();
22929 if (Mask.getValueType() == VT) {
22930 // Mask and original value have the same type
22931 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
22932 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
22933 for (unsigned i = 0; i != NumElems; ++i)
22934 ShuffleVec[i] = i * SizeRatio;
22935 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
22936 ShuffleVec[i] = NumElems*SizeRatio;
22937 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
22938 DAG.getConstant(0, dl, WideVecVT),
22942 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
22943 unsigned WidenNumElts = NumElems*SizeRatio;
22944 unsigned MaskNumElts = VT.getVectorNumElements();
22945 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
22948 unsigned NumConcat = WidenNumElts / MaskNumElts;
22949 SmallVector<SDValue, 16> Ops(NumConcat);
22950 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
22952 for (unsigned i = 1; i != NumConcat; ++i)
22955 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
22958 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
22959 Mld->getBasePtr(), NewMask, WideSrc0,
22960 Mld->getMemoryVT(), Mld->getMemOperand(),
22962 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
22963 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
22966 /// PerformMSTORECombine - Resolve truncating stores
22967 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
22968 const X86Subtarget *Subtarget) {
22969 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
22970 if (!Mst->isTruncatingStore())
22973 EVT VT = Mst->getValue().getValueType();
22974 unsigned NumElems = VT.getVectorNumElements();
22975 EVT StVT = Mst->getMemoryVT();
22978 assert(StVT != VT && "Cannot truncate to the same type");
22979 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22980 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22982 // From, To sizes and ElemCount must be pow of two
22983 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
22984 "Unexpected size for truncating masked store");
22985 // We are going to use the original vector elt for storing.
22986 // Accumulated smaller vector elements must be a multiple of the store size.
22987 assert (((NumElems * FromSz) % ToSz) == 0 &&
22988 "Unexpected ratio for truncating masked store");
22990 unsigned SizeRatio = FromSz / ToSz;
22991 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22993 // Create a type on which we perform the shuffle
22994 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22995 StVT.getScalarType(), NumElems*SizeRatio);
22997 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22999 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mst->getValue());
23000 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23001 for (unsigned i = 0; i != NumElems; ++i)
23002 ShuffleVec[i] = i * SizeRatio;
23004 // Can't shuffle using an illegal type.
23005 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23006 && "WideVecVT should be legal");
23008 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23009 DAG.getUNDEF(WideVecVT),
23013 SDValue Mask = Mst->getMask();
23014 if (Mask.getValueType() == VT) {
23015 // Mask and original value have the same type
23016 NewMask = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Mask);
23017 for (unsigned i = 0; i != NumElems; ++i)
23018 ShuffleVec[i] = i * SizeRatio;
23019 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23020 ShuffleVec[i] = NumElems*SizeRatio;
23021 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23022 DAG.getConstant(0, dl, WideVecVT),
23026 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23027 unsigned WidenNumElts = NumElems*SizeRatio;
23028 unsigned MaskNumElts = VT.getVectorNumElements();
23029 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
23032 unsigned NumConcat = WidenNumElts / MaskNumElts;
23033 SmallVector<SDValue, 16> Ops(NumConcat);
23034 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23036 for (unsigned i = 1; i != NumConcat; ++i)
23039 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23042 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23043 NewMask, StVT, Mst->getMemOperand(), false);
23045 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23046 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23047 const X86Subtarget *Subtarget) {
23048 StoreSDNode *St = cast<StoreSDNode>(N);
23049 EVT VT = St->getValue().getValueType();
23050 EVT StVT = St->getMemoryVT();
23052 SDValue StoredVal = St->getOperand(1);
23053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23055 // If we are saving a concatenation of two XMM registers and 32-byte stores
23056 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23057 unsigned Alignment = St->getAlignment();
23058 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23059 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23060 StVT == VT && !IsAligned) {
23061 unsigned NumElems = VT.getVectorNumElements();
23065 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23066 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23068 SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23069 SDValue Ptr0 = St->getBasePtr();
23070 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23072 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23073 St->getPointerInfo(), St->isVolatile(),
23074 St->isNonTemporal(), Alignment);
23075 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23076 St->getPointerInfo(), St->isVolatile(),
23077 St->isNonTemporal(),
23078 std::min(16U, Alignment));
23079 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23082 // Optimize trunc store (of multiple scalars) to shuffle and store.
23083 // First, pack all of the elements in one place. Next, store to memory
23084 // in fewer chunks.
23085 if (St->isTruncatingStore() && VT.isVector()) {
23086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23087 unsigned NumElems = VT.getVectorNumElements();
23088 assert(StVT != VT && "Cannot truncate to the same type");
23089 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23090 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23092 // From, To sizes and ElemCount must be pow of two
23093 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23094 // We are going to use the original vector elt for storing.
23095 // Accumulated smaller vector elements must be a multiple of the store size.
23096 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23098 unsigned SizeRatio = FromSz / ToSz;
23100 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23102 // Create a type on which we perform the shuffle
23103 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23104 StVT.getScalarType(), NumElems*SizeRatio);
23106 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23108 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
23109 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23110 for (unsigned i = 0; i != NumElems; ++i)
23111 ShuffleVec[i] = i * SizeRatio;
23113 // Can't shuffle using an illegal type.
23114 if (!TLI.isTypeLegal(WideVecVT))
23117 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23118 DAG.getUNDEF(WideVecVT),
23120 // At this point all of the data is stored at the bottom of the
23121 // register. We now need to save it to mem.
23123 // Find the largest store unit
23124 MVT StoreType = MVT::i8;
23125 for (MVT Tp : MVT::integer_valuetypes()) {
23126 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23130 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23131 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23132 (64 <= NumElems * ToSz))
23133 StoreType = MVT::f64;
23135 // Bitcast the original vector into a vector of store-size units
23136 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23137 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23138 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23139 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23140 SmallVector<SDValue, 8> Chains;
23141 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23142 TLI.getPointerTy());
23143 SDValue Ptr = St->getBasePtr();
23145 // Perform one or more big stores into memory.
23146 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23147 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23148 StoreType, ShuffWide,
23149 DAG.getIntPtrConstant(i, dl));
23150 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23151 St->getPointerInfo(), St->isVolatile(),
23152 St->isNonTemporal(), St->getAlignment());
23153 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23154 Chains.push_back(Ch);
23157 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23160 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
23161 // the FP state in cases where an emms may be missing.
23162 // A preferable solution to the general problem is to figure out the right
23163 // places to insert EMMS. This qualifies as a quick hack.
23165 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23166 if (VT.getSizeInBits() != 64)
23169 const Function *F = DAG.getMachineFunction().getFunction();
23170 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23171 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23172 && Subtarget->hasSSE2();
23173 if ((VT.isVector() ||
23174 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23175 isa<LoadSDNode>(St->getValue()) &&
23176 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23177 St->getChain().hasOneUse() && !St->isVolatile()) {
23178 SDNode* LdVal = St->getValue().getNode();
23179 LoadSDNode *Ld = nullptr;
23180 int TokenFactorIndex = -1;
23181 SmallVector<SDValue, 8> Ops;
23182 SDNode* ChainVal = St->getChain().getNode();
23183 // Must be a store of a load. We currently handle two cases: the load
23184 // is a direct child, and it's under an intervening TokenFactor. It is
23185 // possible to dig deeper under nested TokenFactors.
23186 if (ChainVal == LdVal)
23187 Ld = cast<LoadSDNode>(St->getChain());
23188 else if (St->getValue().hasOneUse() &&
23189 ChainVal->getOpcode() == ISD::TokenFactor) {
23190 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23191 if (ChainVal->getOperand(i).getNode() == LdVal) {
23192 TokenFactorIndex = i;
23193 Ld = cast<LoadSDNode>(St->getValue());
23195 Ops.push_back(ChainVal->getOperand(i));
23199 if (!Ld || !ISD::isNormalLoad(Ld))
23202 // If this is not the MMX case, i.e. we are just turning i64 load/store
23203 // into f64 load/store, avoid the transformation if there are multiple
23204 // uses of the loaded value.
23205 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23210 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23211 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23213 if (Subtarget->is64Bit() || F64IsLegal) {
23214 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23215 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23216 Ld->getPointerInfo(), Ld->isVolatile(),
23217 Ld->isNonTemporal(), Ld->isInvariant(),
23218 Ld->getAlignment());
23219 SDValue NewChain = NewLd.getValue(1);
23220 if (TokenFactorIndex != -1) {
23221 Ops.push_back(NewChain);
23222 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23224 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23225 St->getPointerInfo(),
23226 St->isVolatile(), St->isNonTemporal(),
23227 St->getAlignment());
23230 // Otherwise, lower to two pairs of 32-bit loads / stores.
23231 SDValue LoAddr = Ld->getBasePtr();
23232 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23233 DAG.getConstant(4, LdDL, MVT::i32));
23235 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23236 Ld->getPointerInfo(),
23237 Ld->isVolatile(), Ld->isNonTemporal(),
23238 Ld->isInvariant(), Ld->getAlignment());
23239 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23240 Ld->getPointerInfo().getWithOffset(4),
23241 Ld->isVolatile(), Ld->isNonTemporal(),
23243 MinAlign(Ld->getAlignment(), 4));
23245 SDValue NewChain = LoLd.getValue(1);
23246 if (TokenFactorIndex != -1) {
23247 Ops.push_back(LoLd);
23248 Ops.push_back(HiLd);
23249 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23252 LoAddr = St->getBasePtr();
23253 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23254 DAG.getConstant(4, StDL, MVT::i32));
23256 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23257 St->getPointerInfo(),
23258 St->isVolatile(), St->isNonTemporal(),
23259 St->getAlignment());
23260 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23261 St->getPointerInfo().getWithOffset(4),
23263 St->isNonTemporal(),
23264 MinAlign(St->getAlignment(), 4));
23265 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23268 // This is similar to the above case, but here we handle a scalar 64-bit
23269 // integer store that is extracted from a vector on a 32-bit target.
23270 // If we have SSE2, then we can treat it like a floating-point double
23271 // to get past legalization. The execution dependencies fixup pass will
23272 // choose the optimal machine instruction for the store if this really is
23273 // an integer or v2f32 rather than an f64.
23274 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23275 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23276 SDValue OldExtract = St->getOperand(1);
23277 SDValue ExtOp0 = OldExtract.getOperand(0);
23278 unsigned VecSize = ExtOp0.getValueSizeInBits();
23279 MVT VecVT = MVT::getVectorVT(MVT::f64, VecSize / 64);
23280 SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtOp0);
23281 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23282 BitCast, OldExtract.getOperand(1));
23283 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23284 St->getPointerInfo(), St->isVolatile(),
23285 St->isNonTemporal(), St->getAlignment());
23291 /// Return 'true' if this vector operation is "horizontal"
23292 /// and return the operands for the horizontal operation in LHS and RHS. A
23293 /// horizontal operation performs the binary operation on successive elements
23294 /// of its first operand, then on successive elements of its second operand,
23295 /// returning the resulting values in a vector. For example, if
23296 /// A = < float a0, float a1, float a2, float a3 >
23298 /// B = < float b0, float b1, float b2, float b3 >
23299 /// then the result of doing a horizontal operation on A and B is
23300 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23301 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23302 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23303 /// set to A, RHS to B, and the routine returns 'true'.
23304 /// Note that the binary operation should have the property that if one of the
23305 /// operands is UNDEF then the result is UNDEF.
23306 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23307 // Look for the following pattern: if
23308 // A = < float a0, float a1, float a2, float a3 >
23309 // B = < float b0, float b1, float b2, float b3 >
23311 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23312 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23313 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23314 // which is A horizontal-op B.
23316 // At least one of the operands should be a vector shuffle.
23317 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23318 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23321 MVT VT = LHS.getSimpleValueType();
23323 assert((VT.is128BitVector() || VT.is256BitVector()) &&
23324 "Unsupported vector type for horizontal add/sub");
23326 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23327 // operate independently on 128-bit lanes.
23328 unsigned NumElts = VT.getVectorNumElements();
23329 unsigned NumLanes = VT.getSizeInBits()/128;
23330 unsigned NumLaneElts = NumElts / NumLanes;
23331 assert((NumLaneElts % 2 == 0) &&
23332 "Vector type should have an even number of elements in each lane");
23333 unsigned HalfLaneElts = NumLaneElts/2;
23335 // View LHS in the form
23336 // LHS = VECTOR_SHUFFLE A, B, LMask
23337 // If LHS is not a shuffle then pretend it is the shuffle
23338 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23339 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23342 SmallVector<int, 16> LMask(NumElts);
23343 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23344 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23345 A = LHS.getOperand(0);
23346 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23347 B = LHS.getOperand(1);
23348 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23349 std::copy(Mask.begin(), Mask.end(), LMask.begin());
23351 if (LHS.getOpcode() != ISD::UNDEF)
23353 for (unsigned i = 0; i != NumElts; ++i)
23357 // Likewise, view RHS in the form
23358 // RHS = VECTOR_SHUFFLE C, D, RMask
23360 SmallVector<int, 16> RMask(NumElts);
23361 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23362 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23363 C = RHS.getOperand(0);
23364 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23365 D = RHS.getOperand(1);
23366 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23367 std::copy(Mask.begin(), Mask.end(), RMask.begin());
23369 if (RHS.getOpcode() != ISD::UNDEF)
23371 for (unsigned i = 0; i != NumElts; ++i)
23375 // Check that the shuffles are both shuffling the same vectors.
23376 if (!(A == C && B == D) && !(A == D && B == C))
23379 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23380 if (!A.getNode() && !B.getNode())
23383 // If A and B occur in reverse order in RHS, then "swap" them (which means
23384 // rewriting the mask).
23386 ShuffleVectorSDNode::commuteMask(RMask);
23388 // At this point LHS and RHS are equivalent to
23389 // LHS = VECTOR_SHUFFLE A, B, LMask
23390 // RHS = VECTOR_SHUFFLE A, B, RMask
23391 // Check that the masks correspond to performing a horizontal operation.
23392 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23393 for (unsigned i = 0; i != NumLaneElts; ++i) {
23394 int LIdx = LMask[i+l], RIdx = RMask[i+l];
23396 // Ignore any UNDEF components.
23397 if (LIdx < 0 || RIdx < 0 ||
23398 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23399 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23402 // Check that successive elements are being operated on. If not, this is
23403 // not a horizontal operation.
23404 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23405 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23406 if (!(LIdx == Index && RIdx == Index + 1) &&
23407 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23412 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23413 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23417 /// Do target-specific dag combines on floating point adds.
23418 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23419 const X86Subtarget *Subtarget) {
23420 EVT VT = N->getValueType(0);
23421 SDValue LHS = N->getOperand(0);
23422 SDValue RHS = N->getOperand(1);
23424 // Try to synthesize horizontal adds from adds of shuffles.
23425 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23426 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23427 isHorizontalBinOp(LHS, RHS, true))
23428 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23432 /// Do target-specific dag combines on floating point subs.
23433 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23434 const X86Subtarget *Subtarget) {
23435 EVT VT = N->getValueType(0);
23436 SDValue LHS = N->getOperand(0);
23437 SDValue RHS = N->getOperand(1);
23439 // Try to synthesize horizontal subs from subs of shuffles.
23440 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23441 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23442 isHorizontalBinOp(LHS, RHS, false))
23443 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23447 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
23448 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23449 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23451 // F[X]OR(0.0, x) -> x
23452 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23453 if (C->getValueAPF().isPosZero())
23454 return N->getOperand(1);
23456 // F[X]OR(x, 0.0) -> x
23457 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23458 if (C->getValueAPF().isPosZero())
23459 return N->getOperand(0);
23463 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
23464 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23465 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23467 // Only perform optimizations if UnsafeMath is used.
23468 if (!DAG.getTarget().Options.UnsafeFPMath)
23471 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23472 // into FMINC and FMAXC, which are Commutative operations.
23473 unsigned NewOp = 0;
23474 switch (N->getOpcode()) {
23475 default: llvm_unreachable("unknown opcode");
23476 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
23477 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
23480 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23481 N->getOperand(0), N->getOperand(1));
23484 /// Do target-specific dag combines on X86ISD::FAND nodes.
23485 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23486 // FAND(0.0, x) -> 0.0
23487 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23488 if (C->getValueAPF().isPosZero())
23489 return N->getOperand(0);
23491 // FAND(x, 0.0) -> 0.0
23492 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23493 if (C->getValueAPF().isPosZero())
23494 return N->getOperand(1);
23499 /// Do target-specific dag combines on X86ISD::FANDN nodes
23500 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23501 // FANDN(0.0, x) -> x
23502 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23503 if (C->getValueAPF().isPosZero())
23504 return N->getOperand(1);
23506 // FANDN(x, 0.0) -> 0.0
23507 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23508 if (C->getValueAPF().isPosZero())
23509 return N->getOperand(1);
23514 static SDValue PerformBTCombine(SDNode *N,
23516 TargetLowering::DAGCombinerInfo &DCI) {
23517 // BT ignores high bits in the bit index operand.
23518 SDValue Op1 = N->getOperand(1);
23519 if (Op1.hasOneUse()) {
23520 unsigned BitWidth = Op1.getValueSizeInBits();
23521 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23522 APInt KnownZero, KnownOne;
23523 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23524 !DCI.isBeforeLegalizeOps());
23525 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23526 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23527 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23528 DCI.CommitTargetLoweringOpt(TLO);
23533 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23534 SDValue Op = N->getOperand(0);
23535 if (Op.getOpcode() == ISD::BITCAST)
23536 Op = Op.getOperand(0);
23537 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23538 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23539 VT.getVectorElementType().getSizeInBits() ==
23540 OpVT.getVectorElementType().getSizeInBits()) {
23541 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23546 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23547 const X86Subtarget *Subtarget) {
23548 EVT VT = N->getValueType(0);
23549 if (!VT.isVector())
23552 SDValue N0 = N->getOperand(0);
23553 SDValue N1 = N->getOperand(1);
23554 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23557 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23558 // both SSE and AVX2 since there is no sign-extended shift right
23559 // operation on a vector with 64-bit elements.
23560 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23561 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23562 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23563 N0.getOpcode() == ISD::SIGN_EXTEND)) {
23564 SDValue N00 = N0.getOperand(0);
23566 // EXTLOAD has a better solution on AVX2,
23567 // it may be replaced with X86ISD::VSEXT node.
23568 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23569 if (!ISD::isNormalLoad(N00.getNode()))
23572 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23573 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23575 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23581 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23582 TargetLowering::DAGCombinerInfo &DCI,
23583 const X86Subtarget *Subtarget) {
23584 SDValue N0 = N->getOperand(0);
23585 EVT VT = N->getValueType(0);
23587 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
23588 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
23589 // This exposes the sext to the sdivrem lowering, so that it directly extends
23590 // from AH (which we otherwise need to do contortions to access).
23591 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
23592 N0.getValueType() == MVT::i8 && VT == MVT::i32) {
23594 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23595 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, dl, NodeTys,
23596 N0.getOperand(0), N0.getOperand(1));
23597 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23598 return R.getValue(1);
23601 if (!DCI.isBeforeLegalizeOps())
23604 if (!Subtarget->hasFp256())
23607 if (VT.isVector() && VT.getSizeInBits() == 256) {
23608 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23616 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23617 const X86Subtarget* Subtarget) {
23619 EVT VT = N->getValueType(0);
23621 // Let legalize expand this if it isn't a legal type yet.
23622 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23625 EVT ScalarVT = VT.getScalarType();
23626 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23627 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23630 SDValue A = N->getOperand(0);
23631 SDValue B = N->getOperand(1);
23632 SDValue C = N->getOperand(2);
23634 bool NegA = (A.getOpcode() == ISD::FNEG);
23635 bool NegB = (B.getOpcode() == ISD::FNEG);
23636 bool NegC = (C.getOpcode() == ISD::FNEG);
23638 // Negative multiplication when NegA xor NegB
23639 bool NegMul = (NegA != NegB);
23641 A = A.getOperand(0);
23643 B = B.getOperand(0);
23645 C = C.getOperand(0);
23649 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23651 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23653 return DAG.getNode(Opcode, dl, VT, A, B, C);
23656 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23657 TargetLowering::DAGCombinerInfo &DCI,
23658 const X86Subtarget *Subtarget) {
23659 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
23660 // (and (i32 x86isd::setcc_carry), 1)
23661 // This eliminates the zext. This transformation is necessary because
23662 // ISD::SETCC is always legalized to i8.
23664 SDValue N0 = N->getOperand(0);
23665 EVT VT = N->getValueType(0);
23667 if (N0.getOpcode() == ISD::AND &&
23669 N0.getOperand(0).hasOneUse()) {
23670 SDValue N00 = N0.getOperand(0);
23671 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23673 if (!C || C->getZExtValue() != 1)
23675 return DAG.getNode(ISD::AND, dl, VT,
23676 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23677 N00.getOperand(0), N00.getOperand(1)),
23678 DAG.getConstant(1, dl, VT));
23682 if (N0.getOpcode() == ISD::TRUNCATE &&
23684 N0.getOperand(0).hasOneUse()) {
23685 SDValue N00 = N0.getOperand(0);
23686 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23687 return DAG.getNode(ISD::AND, dl, VT,
23688 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23689 N00.getOperand(0), N00.getOperand(1)),
23690 DAG.getConstant(1, dl, VT));
23693 if (VT.is256BitVector()) {
23694 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23699 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
23700 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
23701 // This exposes the zext to the udivrem lowering, so that it directly extends
23702 // from AH (which we otherwise need to do contortions to access).
23703 if (N0.getOpcode() == ISD::UDIVREM &&
23704 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
23705 (VT == MVT::i32 || VT == MVT::i64)) {
23706 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
23707 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
23708 N0.getOperand(0), N0.getOperand(1));
23709 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
23710 return R.getValue(1);
23716 // Optimize x == -y --> x+y == 0
23717 // x != -y --> x+y != 0
23718 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23719 const X86Subtarget* Subtarget) {
23720 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23721 SDValue LHS = N->getOperand(0);
23722 SDValue RHS = N->getOperand(1);
23723 EVT VT = N->getValueType(0);
23726 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23728 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23729 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
23730 LHS.getOperand(1));
23731 return DAG.getSetCC(DL, N->getValueType(0), addV,
23732 DAG.getConstant(0, DL, addV.getValueType()), CC);
23734 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23735 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23736 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23737 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
23738 RHS.getOperand(1));
23739 return DAG.getSetCC(DL, N->getValueType(0), addV,
23740 DAG.getConstant(0, DL, addV.getValueType()), CC);
23743 if (VT.getScalarType() == MVT::i1 &&
23744 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
23746 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23747 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23748 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23750 if (!IsSEXT0 || !IsVZero1) {
23751 // Swap the operands and update the condition code.
23752 std::swap(LHS, RHS);
23753 CC = ISD::getSetCCSwappedOperands(CC);
23755 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23756 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
23757 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23760 if (IsSEXT0 && IsVZero1) {
23761 assert(VT == LHS.getOperand(0).getValueType() &&
23762 "Uexpected operand type");
23763 if (CC == ISD::SETGT)
23764 return DAG.getConstant(0, DL, VT);
23765 if (CC == ISD::SETLE)
23766 return DAG.getConstant(1, DL, VT);
23767 if (CC == ISD::SETEQ || CC == ISD::SETGE)
23768 return DAG.getNOT(DL, LHS.getOperand(0), VT);
23770 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
23771 "Unexpected condition code!");
23772 return LHS.getOperand(0);
23779 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
23780 SelectionDAG &DAG) {
23782 MVT VT = Load->getSimpleValueType(0);
23783 MVT EVT = VT.getVectorElementType();
23784 SDValue Addr = Load->getOperand(1);
23785 SDValue NewAddr = DAG.getNode(
23786 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
23787 DAG.getConstant(Index * EVT.getStoreSize(), dl,
23788 Addr.getSimpleValueType()));
23791 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
23792 DAG.getMachineFunction().getMachineMemOperand(
23793 Load->getMemOperand(), 0, EVT.getStoreSize()));
23797 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23798 const X86Subtarget *Subtarget) {
23800 MVT VT = N->getOperand(1)->getSimpleValueType(0);
23801 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23802 "X86insertps is only defined for v4x32");
23804 SDValue Ld = N->getOperand(1);
23805 if (MayFoldLoad(Ld)) {
23806 // Extract the countS bits from the immediate so we can get the proper
23807 // address when narrowing the vector load to a specific element.
23808 // When the second source op is a memory address, insertps doesn't use
23809 // countS and just gets an f32 from that address.
23810 unsigned DestIndex =
23811 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23813 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23815 // Create this as a scalar to vector to match the instruction pattern.
23816 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23817 // countS bits are ignored when loading from memory on insertps, which
23818 // means we don't need to explicitly set them to 0.
23819 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23820 LoadScalarToVector, N->getOperand(2));
23825 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
23826 SDValue V0 = N->getOperand(0);
23827 SDValue V1 = N->getOperand(1);
23829 EVT VT = N->getValueType(0);
23831 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23832 // operands and changing the mask to 1. This saves us a bunch of
23833 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23834 // x86InstrInfo knows how to commute this back after instruction selection
23835 // if it would help register allocation.
23837 // TODO: If optimizing for size or a processor that doesn't suffer from
23838 // partial register update stalls, this should be transformed into a MOVSD
23839 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23841 if (VT == MVT::v2f64)
23842 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23843 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23844 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23845 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23851 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23852 // as "sbb reg,reg", since it can be extended without zext and produces
23853 // an all-ones bit which is more useful than 0/1 in some cases.
23854 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23857 return DAG.getNode(ISD::AND, DL, VT,
23858 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23859 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23861 DAG.getConstant(1, DL, VT));
23862 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23863 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23864 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23865 DAG.getConstant(X86::COND_B, DL, MVT::i8),
23869 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23870 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23871 TargetLowering::DAGCombinerInfo &DCI,
23872 const X86Subtarget *Subtarget) {
23874 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23875 SDValue EFLAGS = N->getOperand(1);
23877 if (CC == X86::COND_A) {
23878 // Try to convert COND_A into COND_B in an attempt to facilitate
23879 // materializing "setb reg".
23881 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23882 // cannot take an immediate as its first operand.
23884 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23885 EFLAGS.getValueType().isInteger() &&
23886 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23887 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23888 EFLAGS.getNode()->getVTList(),
23889 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23890 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23891 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23895 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23896 // a zext and produces an all-ones bit which is more useful than 0/1 in some
23898 if (CC == X86::COND_B)
23899 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23903 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23904 if (Flags.getNode()) {
23905 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23906 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23912 // Optimize branch condition evaluation.
23914 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23915 TargetLowering::DAGCombinerInfo &DCI,
23916 const X86Subtarget *Subtarget) {
23918 SDValue Chain = N->getOperand(0);
23919 SDValue Dest = N->getOperand(1);
23920 SDValue EFLAGS = N->getOperand(3);
23921 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23925 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23926 if (Flags.getNode()) {
23927 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
23928 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23935 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23936 SelectionDAG &DAG) {
23937 // Take advantage of vector comparisons producing 0 or -1 in each lane to
23938 // optimize away operation when it's from a constant.
23940 // The general transformation is:
23941 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23942 // AND(VECTOR_CMP(x,y), constant2)
23943 // constant2 = UNARYOP(constant)
23945 // Early exit if this isn't a vector operation, the operand of the
23946 // unary operation isn't a bitwise AND, or if the sizes of the operations
23947 // aren't the same.
23948 EVT VT = N->getValueType(0);
23949 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23950 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23951 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23954 // Now check that the other operand of the AND is a constant. We could
23955 // make the transformation for non-constant splats as well, but it's unclear
23956 // that would be a benefit as it would not eliminate any operations, just
23957 // perform one more step in scalar code before moving to the vector unit.
23958 if (BuildVectorSDNode *BV =
23959 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23960 // Bail out if the vector isn't a constant.
23961 if (!BV->isConstant())
23964 // Everything checks out. Build up the new and improved node.
23966 EVT IntVT = BV->getValueType(0);
23967 // Create a new constant of the appropriate type for the transformed
23969 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23970 // The AND node needs bitcasts to/from an integer vector type around it.
23971 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23972 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23973 N->getOperand(0)->getOperand(0), MaskConst);
23974 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23981 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23982 const X86Subtarget *Subtarget) {
23983 // First try to optimize away the conversion entirely when it's
23984 // conditionally from a constant. Vectors only.
23985 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23986 if (Res != SDValue())
23989 // Now move on to more general possibilities.
23990 SDValue Op0 = N->getOperand(0);
23991 EVT InVT = Op0->getValueType(0);
23993 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23994 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23996 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23997 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23998 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
24001 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24002 // a 32-bit target where SSE doesn't support i64->FP operations.
24003 if (Op0.getOpcode() == ISD::LOAD) {
24004 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24005 EVT VT = Ld->getValueType(0);
24006 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
24007 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24008 !Subtarget->is64Bit() && VT == MVT::i64) {
24009 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24010 SDValue(N, 0), Ld->getValueType(0), Ld->getChain(), Op0, DAG);
24011 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24018 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24019 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24020 X86TargetLowering::DAGCombinerInfo &DCI) {
24021 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24022 // the result is either zero or one (depending on the input carry bit).
24023 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24024 if (X86::isZeroNode(N->getOperand(0)) &&
24025 X86::isZeroNode(N->getOperand(1)) &&
24026 // We don't have a good way to replace an EFLAGS use, so only do this when
24028 SDValue(N, 1).use_empty()) {
24030 EVT VT = N->getValueType(0);
24031 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24032 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24033 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24034 DAG.getConstant(X86::COND_B, DL,
24037 DAG.getConstant(1, DL, VT));
24038 return DCI.CombineTo(N, Res1, CarryOut);
24044 // fold (add Y, (sete X, 0)) -> adc 0, Y
24045 // (add Y, (setne X, 0)) -> sbb -1, Y
24046 // (sub (sete X, 0), Y) -> sbb 0, Y
24047 // (sub (setne X, 0), Y) -> adc -1, Y
24048 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24051 // Look through ZExts.
24052 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24053 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24056 SDValue SetCC = Ext.getOperand(0);
24057 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24060 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24061 if (CC != X86::COND_E && CC != X86::COND_NE)
24064 SDValue Cmp = SetCC.getOperand(1);
24065 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24066 !X86::isZeroNode(Cmp.getOperand(1)) ||
24067 !Cmp.getOperand(0).getValueType().isInteger())
24070 SDValue CmpOp0 = Cmp.getOperand(0);
24071 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24072 DAG.getConstant(1, DL, CmpOp0.getValueType()));
24074 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24075 if (CC == X86::COND_NE)
24076 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24077 DL, OtherVal.getValueType(), OtherVal,
24078 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24080 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24081 DL, OtherVal.getValueType(), OtherVal,
24082 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24085 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24086 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24087 const X86Subtarget *Subtarget) {
24088 EVT VT = N->getValueType(0);
24089 SDValue Op0 = N->getOperand(0);
24090 SDValue Op1 = N->getOperand(1);
24092 // Try to synthesize horizontal adds from adds of shuffles.
24093 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24094 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24095 isHorizontalBinOp(Op0, Op1, true))
24096 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24098 return OptimizeConditionalInDecrement(N, DAG);
24101 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24102 const X86Subtarget *Subtarget) {
24103 SDValue Op0 = N->getOperand(0);
24104 SDValue Op1 = N->getOperand(1);
24106 // X86 can't encode an immediate LHS of a sub. See if we can push the
24107 // negation into a preceding instruction.
24108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24109 // If the RHS of the sub is a XOR with one use and a constant, invert the
24110 // immediate. Then add one to the LHS of the sub so we can turn
24111 // X-Y -> X+~Y+1, saving one register.
24112 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24113 isa<ConstantSDNode>(Op1.getOperand(1))) {
24114 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24115 EVT VT = Op0.getValueType();
24116 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24118 DAG.getConstant(~XorC, SDLoc(Op1), VT));
24119 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24120 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24124 // Try to synthesize horizontal adds from adds of shuffles.
24125 EVT VT = N->getValueType(0);
24126 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24127 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24128 isHorizontalBinOp(Op0, Op1, true))
24129 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24131 return OptimizeConditionalInDecrement(N, DAG);
24134 /// performVZEXTCombine - Performs build vector combines
24135 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24136 TargetLowering::DAGCombinerInfo &DCI,
24137 const X86Subtarget *Subtarget) {
24139 MVT VT = N->getSimpleValueType(0);
24140 SDValue Op = N->getOperand(0);
24141 MVT OpVT = Op.getSimpleValueType();
24142 MVT OpEltVT = OpVT.getVectorElementType();
24143 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24145 // (vzext (bitcast (vzext (x)) -> (vzext x)
24147 while (V.getOpcode() == ISD::BITCAST)
24148 V = V.getOperand(0);
24150 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24151 MVT InnerVT = V.getSimpleValueType();
24152 MVT InnerEltVT = InnerVT.getVectorElementType();
24154 // If the element sizes match exactly, we can just do one larger vzext. This
24155 // is always an exact type match as vzext operates on integer types.
24156 if (OpEltVT == InnerEltVT) {
24157 assert(OpVT == InnerVT && "Types must match for vzext!");
24158 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24161 // The only other way we can combine them is if only a single element of the
24162 // inner vzext is used in the input to the outer vzext.
24163 if (InnerEltVT.getSizeInBits() < InputBits)
24166 // In this case, the inner vzext is completely dead because we're going to
24167 // only look at bits inside of the low element. Just do the outer vzext on
24168 // a bitcast of the input to the inner.
24169 return DAG.getNode(X86ISD::VZEXT, DL, VT,
24170 DAG.getNode(ISD::BITCAST, DL, OpVT, V));
24173 // Check if we can bypass extracting and re-inserting an element of an input
24174 // vector. Essentialy:
24175 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24176 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24177 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24178 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24179 SDValue ExtractedV = V.getOperand(0);
24180 SDValue OrigV = ExtractedV.getOperand(0);
24181 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24182 if (ExtractIdx->getZExtValue() == 0) {
24183 MVT OrigVT = OrigV.getSimpleValueType();
24184 // Extract a subvector if necessary...
24185 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24186 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24187 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24188 OrigVT.getVectorNumElements() / Ratio);
24189 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24190 DAG.getIntPtrConstant(0, DL));
24192 Op = DAG.getNode(ISD::BITCAST, DL, OpVT, OrigV);
24193 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24200 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24201 DAGCombinerInfo &DCI) const {
24202 SelectionDAG &DAG = DCI.DAG;
24203 switch (N->getOpcode()) {
24205 case ISD::EXTRACT_VECTOR_ELT:
24206 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24209 case X86ISD::SHRUNKBLEND:
24210 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24211 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
24212 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24213 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
24214 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
24215 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
24216 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
24219 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
24220 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
24221 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
24222 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
24223 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
24224 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24225 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
24226 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
24227 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24228 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
24229 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
24231 case X86ISD::FOR: return PerformFORCombine(N, DAG);
24233 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
24234 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
24235 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
24236 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
24237 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
24238 case ISD::ANY_EXTEND:
24239 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
24240 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
24241 case ISD::SIGN_EXTEND_INREG:
24242 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
24243 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
24244 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
24245 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
24246 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
24247 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
24248 case X86ISD::SHUFP: // Handle all target specific shuffles
24249 case X86ISD::PALIGNR:
24250 case X86ISD::UNPCKH:
24251 case X86ISD::UNPCKL:
24252 case X86ISD::MOVHLPS:
24253 case X86ISD::MOVLHPS:
24254 case X86ISD::PSHUFB:
24255 case X86ISD::PSHUFD:
24256 case X86ISD::PSHUFHW:
24257 case X86ISD::PSHUFLW:
24258 case X86ISD::MOVSS:
24259 case X86ISD::MOVSD:
24260 case X86ISD::VPERMILPI:
24261 case X86ISD::VPERM2X128:
24262 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
24263 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
24264 case ISD::INTRINSIC_WO_CHAIN:
24265 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
24266 case X86ISD::INSERTPS: {
24267 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
24268 return PerformINSERTPSCombine(N, DAG, Subtarget);
24271 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
24277 /// isTypeDesirableForOp - Return true if the target has native support for
24278 /// the specified value type and it is 'desirable' to use the type for the
24279 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
24280 /// instruction encodings are longer and some i16 instructions are slow.
24281 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
24282 if (!isTypeLegal(VT))
24284 if (VT != MVT::i16)
24291 case ISD::SIGN_EXTEND:
24292 case ISD::ZERO_EXTEND:
24293 case ISD::ANY_EXTEND:
24306 /// IsDesirableToPromoteOp - This method query the target whether it is
24307 /// beneficial for dag combiner to promote the specified node. If true, it
24308 /// should return the desired promotion type by reference.
24309 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24310 EVT VT = Op.getValueType();
24311 if (VT != MVT::i16)
24314 bool Promote = false;
24315 bool Commute = false;
24316 switch (Op.getOpcode()) {
24319 LoadSDNode *LD = cast<LoadSDNode>(Op);
24320 // If the non-extending load has a single use and it's not live out, then it
24321 // might be folded.
24322 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24323 Op.hasOneUse()*/) {
24324 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24325 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24326 // The only case where we'd want to promote LOAD (rather then it being
24327 // promoted as an operand is when it's only use is liveout.
24328 if (UI->getOpcode() != ISD::CopyToReg)
24335 case ISD::SIGN_EXTEND:
24336 case ISD::ZERO_EXTEND:
24337 case ISD::ANY_EXTEND:
24342 SDValue N0 = Op.getOperand(0);
24343 // Look out for (store (shl (load), x)).
24344 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24357 SDValue N0 = Op.getOperand(0);
24358 SDValue N1 = Op.getOperand(1);
24359 if (!Commute && MayFoldLoad(N1))
24361 // Avoid disabling potential load folding opportunities.
24362 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24364 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24374 //===----------------------------------------------------------------------===//
24375 // X86 Inline Assembly Support
24376 //===----------------------------------------------------------------------===//
24378 // Helper to match a string separated by whitespace.
24379 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
24380 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
24382 for (StringRef Piece : Pieces) {
24383 if (!S.startswith(Piece)) // Check if the piece matches.
24386 S = S.substr(Piece.size());
24387 StringRef::size_type Pos = S.find_first_not_of(" \t");
24388 if (Pos == 0) // We matched a prefix.
24397 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24399 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24400 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24401 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24402 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24404 if (AsmPieces.size() == 3)
24406 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24413 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24414 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24416 std::string AsmStr = IA->getAsmString();
24418 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24419 if (!Ty || Ty->getBitWidth() % 16 != 0)
24422 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24423 SmallVector<StringRef, 4> AsmPieces;
24424 SplitString(AsmStr, AsmPieces, ";\n");
24426 switch (AsmPieces.size()) {
24427 default: return false;
24429 // FIXME: this should verify that we are targeting a 486 or better. If not,
24430 // we will turn this bswap into something that will be lowered to logical
24431 // ops instead of emitting the bswap asm. For now, we don't support 486 or
24432 // lower so don't worry about this.
24434 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
24435 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
24436 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
24437 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
24438 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
24439 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
24440 // No need to check constraints, nothing other than the equivalent of
24441 // "=r,0" would be valid here.
24442 return IntrinsicLowering::LowerToByteSwap(CI);
24445 // rorw $$8, ${0:w} --> llvm.bswap.i16
24446 if (CI->getType()->isIntegerTy(16) &&
24447 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24448 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
24449 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
24451 const std::string &ConstraintsStr = IA->getConstraintString();
24452 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24453 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24454 if (clobbersFlagRegisters(AsmPieces))
24455 return IntrinsicLowering::LowerToByteSwap(CI);
24459 if (CI->getType()->isIntegerTy(32) &&
24460 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24461 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
24462 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
24463 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
24465 const std::string &ConstraintsStr = IA->getConstraintString();
24466 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24467 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24468 if (clobbersFlagRegisters(AsmPieces))
24469 return IntrinsicLowering::LowerToByteSwap(CI);
24472 if (CI->getType()->isIntegerTy(64)) {
24473 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24474 if (Constraints.size() >= 2 &&
24475 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24476 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24477 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
24478 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
24479 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
24480 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
24481 return IntrinsicLowering::LowerToByteSwap(CI);
24489 /// getConstraintType - Given a constraint letter, return the type of
24490 /// constraint it is for this target.
24491 X86TargetLowering::ConstraintType
24492 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24493 if (Constraint.size() == 1) {
24494 switch (Constraint[0]) {
24505 return C_RegisterClass;
24529 return TargetLowering::getConstraintType(Constraint);
24532 /// Examine constraint type and operand type and determine a weight value.
24533 /// This object must already have been set up with the operand type
24534 /// and the current alternative constraint selected.
24535 TargetLowering::ConstraintWeight
24536 X86TargetLowering::getSingleConstraintMatchWeight(
24537 AsmOperandInfo &info, const char *constraint) const {
24538 ConstraintWeight weight = CW_Invalid;
24539 Value *CallOperandVal = info.CallOperandVal;
24540 // If we don't have a value, we can't do a match,
24541 // but allow it at the lowest weight.
24542 if (!CallOperandVal)
24544 Type *type = CallOperandVal->getType();
24545 // Look at the constraint type.
24546 switch (*constraint) {
24548 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24559 if (CallOperandVal->getType()->isIntegerTy())
24560 weight = CW_SpecificReg;
24565 if (type->isFloatingPointTy())
24566 weight = CW_SpecificReg;
24569 if (type->isX86_MMXTy() && Subtarget->hasMMX())
24570 weight = CW_SpecificReg;
24574 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24575 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24576 weight = CW_Register;
24579 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24580 if (C->getZExtValue() <= 31)
24581 weight = CW_Constant;
24585 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24586 if (C->getZExtValue() <= 63)
24587 weight = CW_Constant;
24591 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24592 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24593 weight = CW_Constant;
24597 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24598 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24599 weight = CW_Constant;
24603 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24604 if (C->getZExtValue() <= 3)
24605 weight = CW_Constant;
24609 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24610 if (C->getZExtValue() <= 0xff)
24611 weight = CW_Constant;
24616 if (isa<ConstantFP>(CallOperandVal)) {
24617 weight = CW_Constant;
24621 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24622 if ((C->getSExtValue() >= -0x80000000LL) &&
24623 (C->getSExtValue() <= 0x7fffffffLL))
24624 weight = CW_Constant;
24628 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24629 if (C->getZExtValue() <= 0xffffffff)
24630 weight = CW_Constant;
24637 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24638 /// with another that has more specific requirements based on the type of the
24639 /// corresponding operand.
24640 const char *X86TargetLowering::
24641 LowerXConstraint(EVT ConstraintVT) const {
24642 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24643 // 'f' like normal targets.
24644 if (ConstraintVT.isFloatingPoint()) {
24645 if (Subtarget->hasSSE2())
24647 if (Subtarget->hasSSE1())
24651 return TargetLowering::LowerXConstraint(ConstraintVT);
24654 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24655 /// vector. If it is invalid, don't add anything to Ops.
24656 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24657 std::string &Constraint,
24658 std::vector<SDValue>&Ops,
24659 SelectionDAG &DAG) const {
24662 // Only support length 1 constraints for now.
24663 if (Constraint.length() > 1) return;
24665 char ConstraintLetter = Constraint[0];
24666 switch (ConstraintLetter) {
24669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24670 if (C->getZExtValue() <= 31) {
24671 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24672 Op.getValueType());
24678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24679 if (C->getZExtValue() <= 63) {
24680 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24681 Op.getValueType());
24687 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24688 if (isInt<8>(C->getSExtValue())) {
24689 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24690 Op.getValueType());
24696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24697 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
24698 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
24699 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
24700 Op.getValueType());
24706 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24707 if (C->getZExtValue() <= 3) {
24708 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24709 Op.getValueType());
24715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24716 if (C->getZExtValue() <= 255) {
24717 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24718 Op.getValueType());
24724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24725 if (C->getZExtValue() <= 127) {
24726 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24727 Op.getValueType());
24733 // 32-bit signed value
24734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24735 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24736 C->getSExtValue())) {
24737 // Widen to 64 bits here to get it sign extended.
24738 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
24741 // FIXME gcc accepts some relocatable values here too, but only in certain
24742 // memory models; it's complicated.
24747 // 32-bit unsigned value
24748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24749 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24750 C->getZExtValue())) {
24751 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
24752 Op.getValueType());
24756 // FIXME gcc accepts some relocatable values here too, but only in certain
24757 // memory models; it's complicated.
24761 // Literal immediates are always ok.
24762 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24763 // Widen to 64 bits here to get it sign extended.
24764 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
24768 // In any sort of PIC mode addresses need to be computed at runtime by
24769 // adding in a register or some sort of table lookup. These can't
24770 // be used as immediates.
24771 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24774 // If we are in non-pic codegen mode, we allow the address of a global (with
24775 // an optional displacement) to be used with 'i'.
24776 GlobalAddressSDNode *GA = nullptr;
24777 int64_t Offset = 0;
24779 // Match either (GA), (GA+C), (GA+C1+C2), etc.
24781 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24782 Offset += GA->getOffset();
24784 } else if (Op.getOpcode() == ISD::ADD) {
24785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24786 Offset += C->getZExtValue();
24787 Op = Op.getOperand(0);
24790 } else if (Op.getOpcode() == ISD::SUB) {
24791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24792 Offset += -C->getZExtValue();
24793 Op = Op.getOperand(0);
24798 // Otherwise, this isn't something we can handle, reject it.
24802 const GlobalValue *GV = GA->getGlobal();
24803 // If we require an extra load to get this address, as in PIC mode, we
24804 // can't accept it.
24805 if (isGlobalStubReference(
24806 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24809 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24810 GA->getValueType(0), Offset);
24815 if (Result.getNode()) {
24816 Ops.push_back(Result);
24819 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24822 std::pair<unsigned, const TargetRegisterClass *>
24823 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
24824 const std::string &Constraint,
24826 // First, see if this is a constraint that directly corresponds to an LLVM
24828 if (Constraint.size() == 1) {
24829 // GCC Constraint Letters
24830 switch (Constraint[0]) {
24832 // TODO: Slight differences here in allocation order and leaving
24833 // RIP in the class. Do they matter any more here than they do
24834 // in the normal allocation?
24835 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24836 if (Subtarget->is64Bit()) {
24837 if (VT == MVT::i32 || VT == MVT::f32)
24838 return std::make_pair(0U, &X86::GR32RegClass);
24839 if (VT == MVT::i16)
24840 return std::make_pair(0U, &X86::GR16RegClass);
24841 if (VT == MVT::i8 || VT == MVT::i1)
24842 return std::make_pair(0U, &X86::GR8RegClass);
24843 if (VT == MVT::i64 || VT == MVT::f64)
24844 return std::make_pair(0U, &X86::GR64RegClass);
24847 // 32-bit fallthrough
24848 case 'Q': // Q_REGS
24849 if (VT == MVT::i32 || VT == MVT::f32)
24850 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24851 if (VT == MVT::i16)
24852 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24853 if (VT == MVT::i8 || VT == MVT::i1)
24854 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24855 if (VT == MVT::i64)
24856 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24858 case 'r': // GENERAL_REGS
24859 case 'l': // INDEX_REGS
24860 if (VT == MVT::i8 || VT == MVT::i1)
24861 return std::make_pair(0U, &X86::GR8RegClass);
24862 if (VT == MVT::i16)
24863 return std::make_pair(0U, &X86::GR16RegClass);
24864 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24865 return std::make_pair(0U, &X86::GR32RegClass);
24866 return std::make_pair(0U, &X86::GR64RegClass);
24867 case 'R': // LEGACY_REGS
24868 if (VT == MVT::i8 || VT == MVT::i1)
24869 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24870 if (VT == MVT::i16)
24871 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24872 if (VT == MVT::i32 || !Subtarget->is64Bit())
24873 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24874 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24875 case 'f': // FP Stack registers.
24876 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24877 // value to the correct fpstack register class.
24878 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24879 return std::make_pair(0U, &X86::RFP32RegClass);
24880 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24881 return std::make_pair(0U, &X86::RFP64RegClass);
24882 return std::make_pair(0U, &X86::RFP80RegClass);
24883 case 'y': // MMX_REGS if MMX allowed.
24884 if (!Subtarget->hasMMX()) break;
24885 return std::make_pair(0U, &X86::VR64RegClass);
24886 case 'Y': // SSE_REGS if SSE2 allowed
24887 if (!Subtarget->hasSSE2()) break;
24889 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24890 if (!Subtarget->hasSSE1()) break;
24892 switch (VT.SimpleTy) {
24894 // Scalar SSE types.
24897 return std::make_pair(0U, &X86::FR32RegClass);
24900 return std::make_pair(0U, &X86::FR64RegClass);
24908 return std::make_pair(0U, &X86::VR128RegClass);
24916 return std::make_pair(0U, &X86::VR256RegClass);
24921 return std::make_pair(0U, &X86::VR512RegClass);
24927 // Use the default implementation in TargetLowering to convert the register
24928 // constraint into a member of a register class.
24929 std::pair<unsigned, const TargetRegisterClass*> Res;
24930 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
24932 // Not found as a standard register?
24934 // Map st(0) -> st(7) -> ST0
24935 if (Constraint.size() == 7 && Constraint[0] == '{' &&
24936 tolower(Constraint[1]) == 's' &&
24937 tolower(Constraint[2]) == 't' &&
24938 Constraint[3] == '(' &&
24939 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24940 Constraint[5] == ')' &&
24941 Constraint[6] == '}') {
24943 Res.first = X86::FP0+Constraint[4]-'0';
24944 Res.second = &X86::RFP80RegClass;
24948 // GCC allows "st(0)" to be called just plain "st".
24949 if (StringRef("{st}").equals_lower(Constraint)) {
24950 Res.first = X86::FP0;
24951 Res.second = &X86::RFP80RegClass;
24956 if (StringRef("{flags}").equals_lower(Constraint)) {
24957 Res.first = X86::EFLAGS;
24958 Res.second = &X86::CCRRegClass;
24962 // 'A' means EAX + EDX.
24963 if (Constraint == "A") {
24964 Res.first = X86::EAX;
24965 Res.second = &X86::GR32_ADRegClass;
24971 // Otherwise, check to see if this is a register class of the wrong value
24972 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24973 // turn into {ax},{dx}.
24974 if (Res.second->hasType(VT))
24975 return Res; // Correct type already, nothing to do.
24977 // All of the single-register GCC register classes map their values onto
24978 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
24979 // really want an 8-bit or 32-bit register, map to the appropriate register
24980 // class and return the appropriate register.
24981 if (Res.second == &X86::GR16RegClass) {
24982 if (VT == MVT::i8 || VT == MVT::i1) {
24983 unsigned DestReg = 0;
24984 switch (Res.first) {
24986 case X86::AX: DestReg = X86::AL; break;
24987 case X86::DX: DestReg = X86::DL; break;
24988 case X86::CX: DestReg = X86::CL; break;
24989 case X86::BX: DestReg = X86::BL; break;
24992 Res.first = DestReg;
24993 Res.second = &X86::GR8RegClass;
24995 } else if (VT == MVT::i32 || VT == MVT::f32) {
24996 unsigned DestReg = 0;
24997 switch (Res.first) {
24999 case X86::AX: DestReg = X86::EAX; break;
25000 case X86::DX: DestReg = X86::EDX; break;
25001 case X86::CX: DestReg = X86::ECX; break;
25002 case X86::BX: DestReg = X86::EBX; break;
25003 case X86::SI: DestReg = X86::ESI; break;
25004 case X86::DI: DestReg = X86::EDI; break;
25005 case X86::BP: DestReg = X86::EBP; break;
25006 case X86::SP: DestReg = X86::ESP; break;
25009 Res.first = DestReg;
25010 Res.second = &X86::GR32RegClass;
25012 } else if (VT == MVT::i64 || VT == MVT::f64) {
25013 unsigned DestReg = 0;
25014 switch (Res.first) {
25016 case X86::AX: DestReg = X86::RAX; break;
25017 case X86::DX: DestReg = X86::RDX; break;
25018 case X86::CX: DestReg = X86::RCX; break;
25019 case X86::BX: DestReg = X86::RBX; break;
25020 case X86::SI: DestReg = X86::RSI; break;
25021 case X86::DI: DestReg = X86::RDI; break;
25022 case X86::BP: DestReg = X86::RBP; break;
25023 case X86::SP: DestReg = X86::RSP; break;
25026 Res.first = DestReg;
25027 Res.second = &X86::GR64RegClass;
25030 } else if (Res.second == &X86::FR32RegClass ||
25031 Res.second == &X86::FR64RegClass ||
25032 Res.second == &X86::VR128RegClass ||
25033 Res.second == &X86::VR256RegClass ||
25034 Res.second == &X86::FR32XRegClass ||
25035 Res.second == &X86::FR64XRegClass ||
25036 Res.second == &X86::VR128XRegClass ||
25037 Res.second == &X86::VR256XRegClass ||
25038 Res.second == &X86::VR512RegClass) {
25039 // Handle references to XMM physical registers that got mapped into the
25040 // wrong class. This can happen with constraints like {xmm0} where the
25041 // target independent register mapper will just pick the first match it can
25042 // find, ignoring the required type.
25044 if (VT == MVT::f32 || VT == MVT::i32)
25045 Res.second = &X86::FR32RegClass;
25046 else if (VT == MVT::f64 || VT == MVT::i64)
25047 Res.second = &X86::FR64RegClass;
25048 else if (X86::VR128RegClass.hasType(VT))
25049 Res.second = &X86::VR128RegClass;
25050 else if (X86::VR256RegClass.hasType(VT))
25051 Res.second = &X86::VR256RegClass;
25052 else if (X86::VR512RegClass.hasType(VT))
25053 Res.second = &X86::VR512RegClass;
25059 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25061 // Scaling factors are not free at all.
25062 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25063 // will take 2 allocations in the out of order engine instead of 1
25064 // for plain addressing mode, i.e. inst (reg1).
25066 // vaddps (%rsi,%drx), %ymm0, %ymm1
25067 // Requires two allocations (one for the load, one for the computation)
25069 // vaddps (%rsi), %ymm0, %ymm1
25070 // Requires just 1 allocation, i.e., freeing allocations for other operations
25071 // and having less micro operations to execute.
25073 // For some X86 architectures, this is even worse because for instance for
25074 // stores, the complex addressing mode forces the instruction to use the
25075 // "load" ports instead of the dedicated "store" port.
25076 // E.g., on Haswell:
25077 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25078 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25079 if (isLegalAddressingMode(AM, Ty))
25080 // Scale represents reg2 * scale, thus account for 1
25081 // as soon as we use a second register.
25082 return AM.Scale != 0;
25086 bool X86TargetLowering::isTargetFTOL() const {
25087 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();